Skip to content

Commit

Permalink
12-1
Browse files Browse the repository at this point in the history
  • Loading branch information
koosvary committed Dec 17, 2024
1 parent 884a337 commit a63181c
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 4 deletions.
93 changes: 89 additions & 4 deletions 2024/12/12-1.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,93 @@
width = 0
width = height = 0
map = {}

with open("2024/12/testinput.txt") as f:
def printMap():
output = ""
for i in range(height):
line = ""
for j in range(width):
line += map[i,j]
output += line + "\n"
print(output)

def findNeighbours(node):
x, y = node
nodes = set()
directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
for direction in directions:
dirX, dirY = direction
neighbour = (x + dirX, y + dirY)
if neighbour in map:
nodes.add(neighbour)
return nodes

def findFences(region):
totalFences = 0
for node in region:
neighbours = findNeighbours(node)
fences = 4 - len(neighbours)
for candidate in neighbours:
if candidate not in region:
# there's a fence between the candidate
fences += 1

totalFences += fences
return totalFences

def getRegion(node):
region = set() # set is like dict but I don't have to do that stupid (x,y): True thing I was doing
checkedNodes = set()
# do BFS or something
uncheckedNeighbours = [node]
while len(uncheckedNeighbours) != 0:
node = uncheckedNeighbours[0]
region.add(node)
checkedNodes.add(node)
# get neighbours
# add them to list if they have the same character

neighbourCandidates = findNeighbours(node)
unvisitedNeighbours = [neighbour for neighbour in neighbourCandidates if (map[neighbour] == map[node] and neighbour not in checkedNodes and neighbour not in uncheckedNeighbours)]
uncheckedNeighbours += unvisitedNeighbours
del uncheckedNeighbours[0]

return region

with open("2024/12/input.txt") as f:
for i, line in enumerate(f):
width = i + 1;
line = line.strip()
if i == 0:
width = height = int(len(line))
for j, char in enumerate(line):
map[i,j] = char

printMap()

# ideas
# don't actually put fences up, it'll be a nightmare
# for each area, recursively crawl across a spot for area, add them to a 2D list
# find orthogonally adjacent neighbours for each of these spots
# fencesAtSpot = 4 - neighbours
# pray.

visitedNodes = set()
regions = []
totalCost = 0

for i in range(height):
for j in range(width):
node = (i, j)
if node not in visitedNodes:
# region finding
newRegion = getRegion(node)
regions.append(newRegion)
visitedNodes |= newRegion

# costs
area = len(newRegion)
perimeter = findFences(newRegion)
cost = area * perimeter
totalCost += cost
print(f'{map[list(newRegion)[0]]}: {cost}')

print(totalCost)
5 changes: 5 additions & 0 deletions 2024/12/testinput3.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
OOOOO
OXOXO
OOOOO
OXOXO
OOOOO

0 comments on commit a63181c

Please sign in to comment.