with open('input.txt') as fh: s = fh.read() def count_occupied_adjecent(s, i): cols = s.index('\n') rows = len(s) // (cols + 1) x = i % (cols + 1) y = i // (cols + 1) result = 0 for dx in [-1, 0, 1]: if x + dx >= 0 and x + dx < cols: for dy in [-1, 0, 1]: if (dx or dy) and y + dy >= 0 and y + dy < rows: if s[(y + dy) * (cols + 1) + (x + dx)] == '#': result += 1 return result def evolve1(s): result = '' for i in range(len(s)): if s[i] == 'L': if count_occupied_adjecent(s, i) == 0: result += '#' else: result += 'L' elif s[i] == '#': if count_occupied_adjecent(s, i) >= 4: result += 'L' else: result += '#' else: result += s[i] return result def part1(s): old = '' while s != old: old = s s = evolve1(s) print(s.count('#')) def count_occupied_dir(s, i): cols = s.index('\n') rows = len(s) // (cols + 1) x = i % (cols + 1) y = i // (cols + 1) result = 0 for dx in [-1, 0, 1]: for dy in [-1, 0, 1]: if (dx or dy): xx = x yy = y while ( xx + dx >= 0 and xx + dx < cols and yy + dy >= 0 and yy + dy < rows ): xx += dx yy += dy c = s[yy * (cols + 1) + xx] if c == '#': result += 1 break elif c == 'L': break return result def evolve2(s): result = '' for i in range(len(s)): if s[i] == 'L': if count_occupied_dir(s, i) == 0: result += '#' else: result += 'L' elif s[i] == '#': if count_occupied_dir(s, i) >= 5: result += 'L' else: result += '#' else: result += s[i] return result def part2(s): old = '' while s != old: old = s s = evolve2(s) print(s.count('#')) part1(s) part2(s)