Skip to content

Commit 08aa835

Browse files
committed
Added day 2017-15
1 parent d15829e commit 08aa835

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed

2017/15-Dueling Generators.py

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
# -------------------------------- Input data -------------------------------- #
2+
import os
3+
4+
test_data = {}
5+
6+
test = 1
7+
test_data[test] = {"input": """Generator A starts with 65
8+
Generator B starts with 8921""",
9+
"expected": ['588', 'Unknown'],
10+
}
11+
12+
test = 'real'
13+
input_file = os.path.join(os.path.dirname(__file__), 'Inputs', os.path.basename(__file__).replace('.py', '.txt'))
14+
test_data[test] = {"input": open(input_file, "r+").read().strip(),
15+
"expected": ['597', 'Unknown'],
16+
}
17+
18+
# -------------------------------- Control program execution -------------------------------- #
19+
20+
case_to_test = 'real'
21+
part_to_test = 2
22+
verbose_level = 1
23+
24+
# -------------------------------- Initialize some variables -------------------------------- #
25+
26+
puzzle_input = test_data[case_to_test]['input']
27+
puzzle_expected_result = test_data[case_to_test]['expected'][part_to_test-1]
28+
puzzle_actual_result = 'Unknown'
29+
30+
31+
# -------------------------------- Actual code execution -------------------------------- #
32+
33+
divisor = 2147483647
34+
factors = {'A': 16807, 'B': 48271}
35+
value = {'A': 0, 'B': 0}
36+
37+
38+
def gen_a ():
39+
while True:
40+
value['A'] *= factors['A']
41+
value['A'] %= divisor
42+
if value['A'] % 4 == 0:
43+
yield value['A']
44+
45+
def gen_b ():
46+
while True:
47+
value['B'] *= factors['B']
48+
value['B'] %= divisor
49+
if value['B'] % 8 == 0:
50+
yield value['B']
51+
52+
if part_to_test == 1:
53+
for string in puzzle_input.split('\n'):
54+
_, generator, _, _, start_value = string.split()
55+
value[generator] = int(start_value)
56+
57+
nb_matches = 0
58+
for i in range (40 * 10 ** 6):
59+
value = {gen: value[gen] * factors[gen] % divisor for gen in value}
60+
if '{0:b}'.format(value['A'])[-16:] == '{0:b}'.format(value['B'])[-16:]:
61+
nb_matches += 1
62+
63+
puzzle_actual_result = nb_matches
64+
65+
66+
else:
67+
for string in puzzle_input.split('\n'):
68+
_, generator, _, _, start_value = string.split()
69+
value[generator] = int(start_value)
70+
71+
nb_matches = 0
72+
A = gen_a()
73+
B = gen_b()
74+
for count_pairs in range (5 * 10**6):
75+
a, b = next(A), next(B)
76+
if '{0:b}'.format(a)[-16:] == '{0:b}'.format(b)[-16:]:
77+
nb_matches += 1
78+
79+
80+
puzzle_actual_result = nb_matches
81+
82+
83+
84+
# -------------------------------- Outputs / results -------------------------------- #
85+
86+
if verbose_level >= 3:
87+
print ('Input : ' + puzzle_input)
88+
print ('Expected result : ' + str(puzzle_expected_result))
89+
print ('Actual result : ' + str(puzzle_actual_result))
90+
91+
92+
93+

0 commit comments

Comments
 (0)