diff --git a/2018/12.py b/2018/12.py index a0f719a..12c2a9c 100644 --- a/2018/12.py +++ b/2018/12.py @@ -1,3 +1,6 @@ +import re + + def to_int(bitlist): out = 0 for bit in bitlist: @@ -5,37 +8,42 @@ def to_int(bitlist): return out -def get_slice(index, pots): - for i in range(index - 2, index + 3): - if i < 0: - yield 0 - yield pots[i] - - -def grow(init, num_gens): - current_gen = init +def grow(init, num_gens, progress=False): + first, last = min(init), max(init) + current_gen = set(init) for g in range(num_gens): - while current_gen[:2] != [0, 0]: - current_gen.insert(0, 0) - while current_gen[-2:] != [0, 0]: - current_gen.append(0) - - next_gen = [] - for i, b in enumerate(current_gen): - key = to_int(get_slice(i, current_gen)) + next_gen = set() + for i in range(first - 2, last + 3): + key = to_int(1 if b in current_gen else 0 for b in range(i - 2, i + 3)) if key in positives: - next_gen.append(1) - else: - next_gen.append(0) + next_gen.add(i) + if i < first: + first = i + if i > last: + last = i current_gen = next_gen + if progress: + print('Generations:', g + 1, end='\r') + + if progress: print('Generations:', g + 1) return current_gen +def test(n): + pots = grow(initial, n) + first, last = min(pots), max(pots) + chars = [] + for i in range(first - 1, last + 2): + chars.append('#' if i in pots else '.') + print(''.join(chars)) + + with open('data/12.txt') as f: - initial = list(next(f)[15:-1]) - initial = list(map(lambda p: int(p == '#'), initial)) + initial = re.search('[#.]+', next(f)).group(0) + initial = {i for i, p in enumerate(initial) if p == '#'} next(f) + positives, negatives = set(), set() for line in f: state, result = line.strip().split(' => ') @@ -46,7 +54,9 @@ with open('data/12.txt') as f: negatives.add(s) -def test(n): - result = grow(initial, n) - print(''.join('#' if p else '.' for p in result)) +pots = grow(initial, 20) +print(f'Part 1: {sum(pots)}\n') + +pots = grow(initial, 5 * 10 ** 10, True) +print(f'Part 2: {pots}\n') diff --git a/2018/data/test.txt b/2018/data/test.txt new file mode 100644 index 0000000..8335d88 --- /dev/null +++ b/2018/data/test.txt @@ -0,0 +1,16 @@ +initial state: #..#.#..##......###...### + +...## => # +..#.. => # +.#... => # +.#.#. => # +.#.## => # +.##.. => # +.#### => # +#.#.# => # +#.### => # +##.#. => # +##.## => # +###.. => # +###.# => # +####. => # \ No newline at end of file