AdventOfCode/2017/14/solution.py
2024-11-25 17:42:14 +01:00

156 lines
3.9 KiB
Python

#!/bin/python3
import sys,re
from pprint import pprint
from functools import reduce
from operator import xor
input_f = 'input'
def list2int(x):
return list(map(int, x))
def toACSII(x):
for idx,i in enumerate(x):
x[idx] = ord(i)
return x
def XOR(x):
return reduce(xor, map(int, t))
part = 1
#########################################
# #
# Part 1 #
# #
#########################################
if part == 0:
size = 256
lengths = []
skip = 0
numbers = []
pos = 0
for i in range(0,size):
numbers.append(i)
with open(input_f) as file:
for line in file:
lengths = list2int(line.rsplit()[0].split(','))
for ldx, length in enumerate(lengths):
sub = [numbers[(pos + i) % len(numbers)] for i in range(length)]
rev = sub[::-1]
for i in range(length):
numbers[(pos + i) % len(numbers)] = rev[i]
pos += (length+skip)
pos = pos % len(numbers)
skip += 1
print(numbers[0]*numbers[1])
#########################################
# #
# Part 2 #
# #
#########################################
grid = []
if part == 1:
size = 256
lengths = []
skip = 0
original_numbers = []
pos = 0
total = 0
for i in range(0,size):
original_numbers.append(i)
with open(input_f) as file:
for line in file:
lengths = list(line.rsplit()[0].split()[0])
#print(lengths)
original_lengths = lengths
for x in range(0,128):
numbers = original_numbers[:]
lengths = []
skip = 0
pos = 0
lengths = original_lengths + ['-'] + list(str(x))
#print(lengths)
#lengths = ['A','o','C',' ','2','0','1','7']
lengths = toACSII(lengths) + [17, 31, 73, 47, 23]
#print('ACSII',lengths)
for i in range(0,64):
for ldx, length in enumerate(lengths):
sub = [numbers[(pos + i) % len(numbers)] for i in range(length)]
rev = sub[::-1]
for i in range(length):
numbers[(pos + i) % len(numbers)] = rev[i]
pos += (length+skip)
pos = pos % len(numbers)
skip += 1
dense = []
for j in range(0,16):
t = numbers[j*16:(j*16)+16]
dense.append(XOR(t))
#print(dense)
hexi = ''
for i in dense:
hexi += format(i, '02x')
#print(hexi)
binary = ''
for i in hexi:
binary += bin(int(i,16))[2:].zfill(4)
grid.append(list(binary))
#for i in hexi:
# print(' '.join(bin(ord(char))[2:] for char in i))
#print(binary)
total += binary.count('1')
print('Part 1:',total)
#input()
for i in range (0,8):
for j in range(0,8):
print(grid[i][j],end='')
print()
def count_blobs(grid):
rows,cols = len(grid), len(grid[0])
visited = [[False for _ in range(cols)] for _ in range(rows)]
directions = [(0,1),(0,-1),(1,0),(-1,0)]
def is_valid(x,y):
return 0 <= x < rows and 0 <= y < cols and not visited[x][y] and grid[x][y] == '1'
def dfs(x, y):
visited[x][y] = True
for dx, dy in directions:
nx, ny = x + dx, y + dy
if is_valid(nx, ny):
dfs(nx, ny)
blob_count = 0
for i in range(rows):
for j in range(cols):
if grid[i][j] == '1' and not visited[i][j]:
blob_count += 1
dfs(i, j)
return blob_count
print(count_blobs(grid))