-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay07.py
More file actions
61 lines (44 loc) · 1.37 KB
/
Copy pathDay07.py
File metadata and controls
61 lines (44 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from os import popen
import Utility
filePath = 'input/day07/part1.txt'
def getHorizontalPositions():
inputLines = Utility.getLinesFromFile(filePath)
return list(map(int, inputLines[0].split(',')))
def solvePart1():
positions = getHorizontalPositions()
sortedPositions = sorted(positions)
optimalPosition = sortedPositions[len(sortedPositions)//2]
maxValue = max(positions)
spread = [0 for i in range(maxValue + 1)]
for i in positions:
spread[i] += 1
score = 0
for n in range(maxValue + 1):
score += abs(optimalPosition - n) * spread[n]
print('Solution to part1:')
print(optimalPosition)
print(score)
def calculateCost(start, end):
diff = abs(start - end)
return diff * (diff + 1) / 2
def solvePart2():
positions = getHorizontalPositions()
maxValue = max(positions)
spread = [0 for i in range(maxValue + 1)]
for i in positions:
spread[i] += 1
bestScore = len(positions) * (maxValue**2)
bestValue = 0
for i in range(maxValue + 1):
score = 0
for n in range(maxValue + 1):
score += calculateCost(i, n) * spread[n]
if (score < bestScore):
bestScore = score
bestValue = i
print('Solution to part2:')
print(bestValue)
print(bestScore)
if(__name__ == '__main__'):
solvePart1()
solvePart2()