itch.io is community of indie game creators and players

Devlogs

day 3

aoc 2020
A downloadable advent code

3a.py

# Starting at the top-left corner of your map and following a slope of right 3 and down 1,
# how many trees would you encounter?
# the same pattern repeats to the right many times
# input
with open('3.txt', 'r') as file:
    input = file.read()
# turn the input into a list; each row is '..##.......' where # is a tree
input_list = list(input.split('\n'))
xpos = 0 # this is where you are in the row
row_len = 31 # all rows have the same length in a
num_trees = 0 # counter for number of trees
for row in input_list:
    if row[xpos] == '#':
        num_trees += 1
    xpos = (xpos + 3) % row_len
print(num_trees)

(the actual 3a.py that i have attached has some stuff i put in to debug - it doesn't make a difference now that the code works but i can't be bothered to reupload). main issues here are that i hardcoded row_len (i did check that every row has 31 characters though) as well as the number of steps you move right each time you move down one, which meant some rewriting for the next part.

3b.py

# Starting at the top-left corner of your map and following a slope of right 3 and down 1,
# how many trees would you encounter?
# the same pattern repeats to the right many times
import functools # reduce()
import operator
# input
with open('3.txt', 'r') as file:
    input = file.read()
# turn the input into a list; each row is '..##.......' where # is a tree
input_list = list(input.split('\n'))
row_len = 31 # all rows have the same length in a
dxy_list = [(1,1), (3,1), (5,1), (7,1), (1,2)]
tree_list = [] # will have number of trees
for dx_dy in dxy_list:
    x = 0  # this is where you are in the row
    y = 0  # this is the number row you're on
    dx = dx_dy[0] # this is how many you go right
    dy = dx_dy[1] # this is how many you go down
    num_trees = 0  # counter for number of trees
    while y < len(input_list):
        if input_list[y][x] == '#':
            num_trees += 1
        x = (x + dx) % row_len
        y = y + dy
    # we now have number of trees
    tree_list.append(num_trees)
# we now have the full list
prod_trees = functools.reduce(operator.mul, tree_list)
print(prod_trees)

today i learnt how to get the product of elements in a list.. which isn't completely standard in python 3.7 for some reason. i had to add a coordinate for y and change the loop that went through the "map" to run until y hit the length of the input_list, as opposed to the loop being per entry in the list, since one of the routes given (as in dxy_list) required going down 2 per step.

Files

  • 3.txt 10 kB
    Dec 04, 2020
  • 3a.py 785 bytes
    Dec 04, 2020
  • 3b.py 1.1 kB
    Dec 04, 2020
Download aoc 2020
Leave a comment