Skip to content

Commit

Permalink
2024 Day 12 Part 1 Completed
Browse files Browse the repository at this point in the history
  • Loading branch information
pcorliss committed Dec 13, 2024
1 parent 0ec7c90 commit 0c5ff6b
Show file tree
Hide file tree
Showing 2 changed files with 128 additions and 0 deletions.
83 changes: 83 additions & 0 deletions 2024/12/daily.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import itertools
import sys

def parse(input_text):
out = []
for line in input_text.strip().split('\n'):
if len(line) == 0:
continue
out.append(list(line))

return out

CARDINALS = [(0, 1), (0, -1), (1, 0), (-1, 0)]

def blocks(grid, x, y):
block = set()
block.add((x, y))
char = grid[y][x]

candidates = [(x, y)]
while len(candidates) > 0:
x, y = candidates.pop()
for dx, dy in CARDINALS:
new_x = x + dx
new_y = y + dy
if new_x < 0 or new_x >= len(grid[0]) or new_y < 0 or new_y >= len(grid):
continue
if (new_x, new_y) in block:
continue
if grid[new_y][new_x] == char:
block.add((new_x, new_y))
candidates.append((new_x, new_y))

return block

def perimeter(grid, block):
sum = 0
for x, y in block:
for dx, dy in CARDINALS:
new_x = x + dx
new_y = y + dy
# Grid Border
if new_x < 0 or new_x >= len(grid[0]) or new_y < 0 or new_y >= len(grid):
sum += 1
continue
# Contiguous
if (new_x, new_y) in block:
continue

# Borders other blocks on this side
sum += 1

return sum

def part1(input_text):
grid = parse(input_text)
block_sets = []
visited = set()

for y in range(len(grid)):
for x in range(len(grid[y])):
if (x, y) in visited:
continue
block = blocks(grid, x, y)
block_sets.append(block)
visited.update(block)

sum = 0
for block in block_sets:
p = perimeter(grid, block)
sum += p * len(block)

return sum

def part2(input_text):
return 0

if __name__ == "__main__":
with open(__file__.rsplit('/', 1)[0] + "/input.txt", 'r') as file:
print(part1(file.read()))

with open(__file__.rsplit('/', 1)[0] + "/input.txt", 'r') as file:
print(part2(file.read()))
45 changes: 45 additions & 0 deletions 2024/12/daily_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import pytest
from daily import *

@pytest.fixture
def sample_data():
return """
RRRRIICCFF
RRRRIICCCF
VVRRRCCFFF
VVRCCCJFFF
VVVVCJJCFE
VVIVCCJJEE
VVIIICJJEE
MIIIIIJJEE
MIIISIJEEE
MMMISSJEEE
"""

@pytest.fixture
def parsed_data(sample_data):
return parse(sample_data)

def test_parse(sample_data):
grid = parse(sample_data)
assert grid[0][0] == 'R'
assert grid[9][9] == 'E'

def test_blocks(parsed_data):
pos_set = blocks(parsed_data, 0, 0)

assert len(pos_set) == 12
assert (0,0) in pos_set
assert (4,2) in pos_set
assert (2,3) in pos_set

def test_perimeter(parsed_data):
b = blocks(parsed_data, 0, 0)
assert perimeter(parsed_data, b) == 18


def test_part1(sample_data):
assert part1(sample_data) == 1930

# def test_part2(sample_data):
# assert part2(sample_data) == 81

0 comments on commit 0c5ff6b

Please sign in to comment.