Advertisement
Guest User

Untitled

a guest
Dec 13th, 2019
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Julia 1.39 KB | None | 0 0
  1. using StaticArrays
  2.  
  3. function parse_input(lines)
  4.     rx = r"<x=(-?\d+), y=(-?\d+), z=(-?\d+)>"
  5.     return [
  6.         SVector{3,Int}(parse.(Int, match(rx, line).captures))
  7.         for line in lines
  8.     ]
  9. end
  10.  
  11. function step!(positions, velocities)
  12.     for (idx, p1) ∈ enumerate(positions), p2 ∈ positions
  13.         velocities[idx] += sign.(p2 - p1)
  14.     end
  15.     positions .+= velocities
  16. end
  17.  
  18. function part1(positions)
  19.     positions = copy(positions)
  20.     velocities = fill(zero(positions[1]), length(positions))
  21.     for _ ∈ 1:1000
  22.         step!(positions, velocities)
  23.     end
  24.     return sum([sum(abs.(p)) for p in positions] .* [sum(abs.(v)) for v in velocities])
  25. end
  26.  
  27. function part2(positions)
  28.     initial, positions = positions, copy(positions)
  29.     velocities = fill(zero(positions[1]), length(positions))
  30.     periods = [0, 0, 0]
  31.     n = 1
  32.     while any(==(0), periods)
  33.         step!(positions, velocities)
  34.         for idx in eachindex(periods)
  35.             same_pos = getindex.(positions, idx) == getindex.(initial, idx)
  36.             same_vel = all(==(0), getindex.(velocities, idx))
  37.             if same_pos && same_vel
  38.                 periods[idx] = n
  39.             end
  40.         end
  41.         n += 1
  42.     end
  43.     return lcm(periods)
  44. end
  45.  
  46. input = readlines("input_12.txt")
  47. positions = parse_input(input)
  48. println("Part 1: ", part1(positions))
  49. println("Part 2: ", part2(positions))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement