-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsol16.py
127 lines (88 loc) · 3.09 KB
/
sol16.py
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
import utils
import re
def initialise():
global ticketInput, rules, otherTickets, validNumbers, ruleDict, ticket
ticketInput = utils.loadInputFile("input_16.txt")
rules = []
otherTickets = []
for line in ticketInput:
if line == "":
break
rules.append(line)
for idx, line in enumerate(ticketInput):
if line == "your ticket:":
ticket = ticketInput[idx+1]
break
ticket = [int(x) for x in ticket.split(",")]
for i in range(idx+4, len(ticketInput)):
otherTickets.append(ticketInput[i].split(","))
validNumbers = []
exp = re.compile(r"^(.*): (\d+)-(\d+) or (\d+)-(\d+).*$")
ruleDict = {}
for rule in rules:
m = re.match(exp, rule)
validNumbers.extend(range(int(m.group(2)), int(m.group(3))+1))
validNumbers.extend(range(int(m.group(4)), int(m.group(5))+1))
ruleDict[m.group(1)] = []
ruleDict[m.group(1)].extend(range(int(m.group(2)), int(m.group(3))+1))
ruleDict[m.group(1)].extend(range(int(m.group(4)), int(m.group(5))+1))
def extractColumn(list, idx):
return [int(row[idx]) for row in list]
def part1():
global otherTickets, validNumbers, validTickets
errorNumbers = []
validTickets = []
for otherTicket in otherTickets:
valid = True
tempValidNumbers = validNumbers[:]
for number in otherTicket:
number = int(number)
if number not in tempValidNumbers:
errorNumbers.append(number)
valid = False
else:
tempValidNumbers.remove(number)
if valid:
validTickets.append(otherTicket)
return sum(errorNumbers)
def part2():
global rules, validTickets, ruleDict, ticket
positions = []
cols = len(validTickets[0])
col = []
possibilities = {}
for i in range(0, cols):
possibilities[i] = []
for i in range(0, cols):
for rule in ruleDict:
valid = True
for j in extractColumn(validTickets, i):
if j not in ruleDict[rule]:
valid = False
break
if valid:
possibilities[i].append(rule)
complete = False
while not complete:
complete = True
for possibility in possibilities:
if len(possibilities[possibility]) == 1:
item = possibilities[possibility][0]
possibilities[possibility] = []
if item.startswith('departure'):
positions.append(possibility)
# remove and break
for possibilityInner in possibilities:
try:
possibilities[possibilityInner].remove(item)
except ValueError:
pass
if len(possibilities[possibility]) != 0:
complete = False
result = 1
for position in positions:
result *= int(ticket[position])
return result
initialise()
print("Part 1:", part1()) # 22977
print("Part 2:", part2()) # 998358379943