@@ -11,7 +11,6 @@ def get_input():
11
11
if '|' in line :
12
12
key , value = map (int , line .split ('|' ))
13
13
14
- # If the key is already in the dictionary, append the value to the list
15
14
if key not in pipe_separated_dict :
16
15
pipe_separated_dict [key ] = []
17
16
pipe_separated_dict [key ].append (value )
@@ -42,15 +41,51 @@ def is_valid_ordering(ordering, rules):
42
41
def get_mid_value (ordering ):
43
42
return ordering [len (ordering ) // 2 ]
44
43
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
+
45
76
def main ():
46
77
rules , orderings = get_input ()
47
78
48
79
tally = 0
80
+ incorrects_tally = 0
49
81
for ordering in orderings :
50
82
if is_valid_ordering (ordering , rules ):
51
83
tally = tally + get_mid_value (ordering )
84
+ else :
85
+ incorrects_tally = incorrects_tally + get_mid_value (sort (ordering , rules ))
52
86
53
87
print (tally )
88
+ print (incorrects_tally )
54
89
55
90
56
91
if __name__ == "__main__" :
0 commit comments