Skip to content

Commit 39a6228

Browse files
committed
part 2 done
1 parent eaba8ee commit 39a6228

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

day_5/day5.py

+36-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ def get_input():
1111
if '|' in line:
1212
key, value = map(int, line.split('|'))
1313

14-
# If the key is already in the dictionary, append the value to the list
1514
if key not in pipe_separated_dict:
1615
pipe_separated_dict[key] = []
1716
pipe_separated_dict[key].append(value)
@@ -42,15 +41,51 @@ def is_valid_ordering(ordering, rules):
4241
def get_mid_value(ordering):
4342
return ordering[len(ordering) // 2]
4443

44+
45+
def sort(ordering, rules):
46+
made_change = False
47+
48+
# is there any value to the left that violates the rules?
49+
# step through them backwards
50+
51+
for i in range(len(ordering) - 1, -1, -1):
52+
53+
if ordering[i] not in rules:
54+
continue
55+
56+
for j in range(i - 1, -1, -1):
57+
if ordering[j] in rules[ordering[i]]:
58+
59+
# move ordering[j] to the right of ordering[i]
60+
value_to_move = ordering.pop(j)
61+
ordering.insert(i + 1, value_to_move)
62+
63+
made_change = True
64+
break
65+
66+
if made_change:
67+
break
68+
69+
# if a change was made, call sort again to recheck for rule violations
70+
if made_change:
71+
sort(ordering, rules)
72+
73+
return ordering
74+
75+
4576
def main():
4677
rules, orderings = get_input()
4778

4879
tally = 0
80+
incorrects_tally = 0
4981
for ordering in orderings:
5082
if is_valid_ordering(ordering, rules):
5183
tally = tally + get_mid_value(ordering)
84+
else:
85+
incorrects_tally = incorrects_tally + get_mid_value(sort(ordering, rules))
5286

5387
print(tally)
88+
print(incorrects_tally)
5489

5590

5691
if __name__ == "__main__":

0 commit comments

Comments
 (0)