Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using StaticArrays
- function parse_input(lines)
- rx = r"<x=(-?\d+), y=(-?\d+), z=(-?\d+)>"
- return [
- SVector{3,Int}(parse.(Int, match(rx, line).captures))
- for line in lines
- ]
- end
- function step!(positions, velocities)
- for (idx, p1) ∈ enumerate(positions), p2 ∈ positions
- velocities[idx] += sign.(p2 - p1)
- end
- positions .+= velocities
- end
- function part1(positions)
- positions = copy(positions)
- velocities = fill(zero(positions[1]), length(positions))
- for _ ∈ 1:1000
- step!(positions, velocities)
- end
- return sum([sum(abs.(p)) for p in positions] .* [sum(abs.(v)) for v in velocities])
- end
- function part2(positions)
- initial, positions = positions, copy(positions)
- velocities = fill(zero(positions[1]), length(positions))
- periods = [0, 0, 0]
- n = 1
- while any(==(0), periods)
- step!(positions, velocities)
- for idx in eachindex(periods)
- same_pos = getindex.(positions, idx) == getindex.(initial, idx)
- same_vel = all(==(0), getindex.(velocities, idx))
- if same_pos && same_vel
- periods[idx] = n
- end
- end
- n += 1
- end
- return lcm(periods)
- end
- input = readlines("input_12.txt")
- positions = parse_input(input)
- println("Part 1: ", part1(positions))
- println("Part 2: ", part2(positions))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement