Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # day11
- from numpy import *
- import time
- from copy import copy, deepcopy
- import numpy.ma as ma
- input = "d11_data.txt"
- test = "d11_test.txt"
- round0 = "d11_test0.txt"
- round1 = "d11_test1.txt"
- round2 = "d11_test2.txt"
- round3 = "d11_test3.txt"
- def read_file(filename):
- with open(filename) as f:
- return f.read().splitlines()
- #change input data here
- data = read_file(test)
- # Changing the input from L,#,. to 0,1,-1 for easy calculations later
- def clean_input(data):
- clean_data=[]
- def cleanstuff(indata):
- for n in indata:
- if n == 'L': return 0
- elif n == '#': return 1
- elif n == '.': return -1
- for line in data:
- line = list(map(cleanstuff,line))
- clean_data.append(line)
- return clean_data
- #Converting datastructure to something more useful and adding a border of -1s to make floating window work easier
- def get_matrix(data):
- area = []
- newlist = [-1 for j in range(len(data[0])+2)]
- area.append(newlist)
- i=1
- for line in data:
- area.append([])
- area[i].append(-1)
- for space in line:
- area[i].append(space)
- area[i].append(-1)
- i+=1
- area.append(newlist)
- m_area = reshape(area,((len(area)),len(area[0])))
- return m_area
- #Build a floating window of 3x3 to check surroundings
- def build_lookup(x,y):
- lookup = []
- lookup.append([(x-1,y-1),(x-1,y),(x-1,y+1)])
- lookup.append([(x,y-1),(None,None),(x,y+1)])
- lookup.append([(x+1,y-1),(x+1,y),(x+1,y+1)])
- return lookup
- #calculating the sum of occupied places around a given index for a given matrix
- def get_sum(lookup, input):
- lookup_sum = 0
- for i in lookup:
- for j in i:
- if (j != (None,None)):
- val=int(input[j[0]][j[1]])
- if val >=0: lookup_sum+=val
- return lookup_sum
- #iterating through the input matrix and changing seats for the output matrix
- def calculate_round(round_data):
- newround = deepcopy(round_data)
- r=1
- for row in round_data[1:-1]:
- c=1
- for column in round_data[1:-1]:
- surround_count = get_sum(build_lookup(r,c),round_data)
- if (surround_count >= 4 and round_data[r][c]==1): newround[r][c]=0
- elif (surround_count == 0 and round_data[r][c]==0): newround[r][c]=1
- c+=1
- r+=1
- return newround
- #recursive run through matrix inputs, until stable state is reached
- def run_rounds(floorplan):
- result=calculate_round(floorplan)
- if ((result==floorplan).all()):
- return result
- return run_rounds(result)
- #start program, and sum up all seats that are occupied
- seats = get_matrix(clean_input(data))
- result_seats = run_rounds(seats)
- masked_result = ma.masked_values(result_seats,-1)
- print(masked_result.sum())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement