Created
December 11, 2020 22:17
-
-
Save unbibium/7853d4b2db26974a5768e499bb2816b6 to your computer and use it in GitHub Desktop.
Advent of Code day 3 solution
This file contains 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
#!/usr/bin/env python3 | |
print("tmap") | |
import os,sys,re | |
class Grid: | |
def __init__(self, fn): | |
self.trees = set() | |
rowlens = set() | |
with open(fn) as fi: | |
row=0 | |
for line in fi.readlines(): | |
line = line.strip() | |
if len(line) < 1: continue | |
for col in range(len(line)): | |
if line[col] == '#': | |
self.trees.add( (col, row) ) | |
rowlens.add(len(line)) | |
row += 1 | |
if len(rowlens) > 1: | |
raise ValueError("lines of multiple lengths: %r" % rowlens) | |
self.width = min(rowlens) | |
self.length = row | |
def treeAt(self, x, y): | |
return (x % self.width, y) in self.trees | |
def traverse(grid, x=0, y=0, dx=3, dy=1): | |
trees = 0 | |
while y >= 0 and y < grid.length: | |
if grid.treeAt(x,y): | |
trees += 1 | |
x += dx | |
y += dy | |
return trees | |
print(sys.argv) | |
if len(sys.argv) < 2: | |
print("Usage:",sys.argv[0],"mapfile [dx] [dy]") | |
sys.exit(1) | |
dx, dy = 3, 1 | |
if len(sys.argv) > 3: | |
dy = int(sys.argv[3]) | |
if len(sys.argv) > 2: | |
dx = int(sys.argv[2]) | |
gridfn = sys.argv[1] | |
grid = Grid(gridfn) | |
print( traverse(grid, dx=dx, dy=dy) ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment