38
loading...
This website collects cookies to deliver better user experience
line.split()
, and iterate over using file.readlines()
. Note: in-line opening a file like this with open()
outside a context manager is generally bad practice, but relatively benign in a small script like this.lines = [line.split() for line in open('day_2.txt').readlines()]
a = [0, 1]
b = [1, 1]
c = [a[0] + b[0], a[1] + b[1]]
a = 0 + 1j
b = 1 + 1j
c = a + b
if
statementmoves = dict(forward=1, down=1j, up=-1j)
map()
) a function that multiplies together one of these move vectors and the distance number provided in the file. And then sum together all the resultant vectors for the final position of the sub.pos = sum(map(lambda line: moves[line[0]]*int(line[1]), lines))
multiplied = pos.real * pos.imag
# down move
new_aim = aim + amount
# up move
new_aim = aim - amount
# forward move
new_dist = dist + amount
new_depth = depth + depth * aim
[dist, depth, aim, 1]
(a
is the amount we're moving by)# down move
[1, 0, 0, 0] # dist
[0, 1, 0, 0] # depth
[0, 0, 1, a] # aim
[0, 0, 0, 1] # 1
# up move
[1, 0, 0, 0] # dist
[0, 1, 0, 0] # depth
[0, 0, 1,-a] # aim
[0, 0, 0, 1] # 1
# forward move
[1, 0, 0, a] # dist
[0, 1, a, 0] # depth
[0, 0, 1, 0] # aim
[0, 0, 0, 1] # 1
I_4 + amount * M
moves = defaultdict(lambda: np.zeros([4, 4]))
moves["down"][2, 3] = 1
moves["up"][2, 3] = -1
moves["forward"][0:2, 2:4] = [[0,1],[1,0]]
reduce()
to avoid writing out a loop.pos = reduce(lambda pos, line: (np.identity(4)+moves[line[0]]*int(line[1])).dot(pos), lines, [0, 0, 0, 1])
multiplied = pos[0]*pos[1]
lines = [x.split() for x in open('day_2.txt').readlines()]
moves = dict(forward=1, down=1j, up=-1j)
pos = sum(map(lambda line: moves[line[0]]*int(line[1]), lines))
result = pos.real * pos.imag
print("Part 1 result:", result )
from collections import defaultdict
from functools import reduce
import numpy as np
moves = defaultdict(lambda: np.zeros([4, 4]))
moves["down"][2, 3] = 1
moves["up"][2, 3] = -1
moves["forward"][0:2, 2:4] = [[0,1],[1,0]]
pos = reduce(lambda pos, line: (np.identity(4)+moves[line[0]]*int(line[1])).dot(pos), lines, [0, 0, 0, 1])
result = pos[0]*pos[1]
print("Part 2 result:", result )