Created
January 19, 2020 13:16
-
-
Save kolharsam/db3ee5052b79c23c7631dd308b4c1a50 to your computer and use it in GitHub Desktop.
Advent of Code - Day 18 - Both Parts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from os import system | |
start_grid = [line.rstrip('\n') for line in open("input")] | |
def printGrid(grid): | |
print("\n\n\n\n\n\n\n\n\n\n\n") | |
for r in grid: | |
print (''.join(r)) | |
def getLightsOn(grid): | |
counter = 0 | |
for r in grid: | |
for val in r: | |
if val == '#': | |
counter +=1 | |
return counter | |
def getNeighbourCount(grid, i, j): | |
count = 0 | |
r = len(grid) | |
c = len(grid[0]) | |
neighbours = [(0,1), (0,-1), (1, 0), (-1,0), (1, 1), (1, -1), (-1, 1), (-1, -1)] | |
for n in neighbours: | |
x, y = n | |
inc_i = i + x | |
inc_j = j + y | |
if inc_i >= 0 and inc_j >= 0 and inc_i < r and inc_j < c: | |
if grid[inc_i][inc_j] == '#': | |
count += 1 | |
return count | |
GRID = [] | |
for line in start_grid: | |
GRID.append(list(line)) | |
printGrid(GRID) | |
print (getLightsOn(GRID)) | |
def getNewGrid(x, y): | |
li = [] | |
for _ in range(x): | |
temp = [] | |
for _ in range(y): | |
temp.append('.') | |
li.append(temp) | |
li[0][0] = '#' | |
li[0][y-1] = '#' | |
li[x-1][0] = '#' | |
li[x-1][y-1] = '#' | |
return li | |
def gol(grid, steps): | |
rr = len(grid) | |
cc = len(grid[0]) | |
while steps > 0: | |
NEW_GRID = getNewGrid(rr, cc) | |
for r, _ in enumerate(grid): | |
for c, cell in enumerate(grid[r]): | |
cn = getNeighbourCount(grid, r, c) | |
if cn == 3 and cell == '.': | |
NEW_GRID[r][c] = '#' | |
if cn in (2, 3) and cell == '#': | |
NEW_GRID[r][c] = '#' | |
NEW_GRID[0][0] = '#' | |
NEW_GRID[0][cc-1] = '#' | |
NEW_GRID[rr-1][0] = '#' | |
NEW_GRID[rr-1][cc-1] = '#' | |
grid = NEW_GRID | |
NEW_GRID = [] | |
printGrid(grid) | |
system('clear') | |
print(getLightsOn(grid)) | |
steps -= 1 | |
GRID[0][0] = '#' | |
GRID[0][len(GRID)-1] = '#' | |
GRID[len(GRID)-1][0] = '#' | |
GRID[len(GRID)-1][len(GRID)-1] = '#' | |
# run program for part 2 | |
gol(GRID, 100) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment