advent-of-code

Perserverance, or the lack thereof

git clone git://git.shimmy1996.com/advent-of-code.git
commit 3a7b708f004161627add3ac0b11464a3730cd597
parent 05075a757a7f27700d84013b99dc169e60ee5ae9
Author: Shimmy Xu <shimmy.xu@shimmy1996.com>
Date:   Thu, 12 Dec 2019 13:17:51 -0500

Add Julia solution

Diffstat:
Aday-12/Makefile | 9+++++++++
Aday-12/day-12.jl | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aday-12/input.txt | 4++++
3 files changed, 75 insertions(+), 0 deletions(-)
diff --git a/day-12/Makefile b/day-12/Makefile
@@ -0,0 +1,9 @@
+CC := g++
+CCFLAGS := --std=c++17 -Wall
+
+all: day-12-rust day-12.jl
+	julia day-12.jl
+	./day-12-rust
+
+day-12-rust: day-12.rs
+	rustc $^ -o $@
diff --git a/day-12/day-12.jl b/day-12/day-12.jl
@@ -0,0 +1,62 @@
+function evolve!(coord, velocity)
+    # Computes velocity caused by given coordinates, move them in corresponding
+    # directions, and return the velocity vector.
+    for i in 1:size(coord, 1)
+        for j in (i + 1):size(coord, 1)
+            dv = sign.(coord[j, :] - coord[i, :])
+            velocity[i, :] += dv
+            velocity[j, :] -= dv
+        end
+    end
+end
+
+function calc_energy(coord, velocity)
+    pot = sum(abs.(coord); dims = 2)
+    kin = sum(abs.(velocity); dims = 2)
+    sum(pot .* kin)
+end
+
+function part_1(input)
+    coord = copy(input)
+    velocity = zeros(size(coord))
+    for i in 1:1000
+        evolve!(coord, velocity)
+        coord += velocity
+    end
+    Int(calc_energy(coord, velocity))
+end
+
+function calc_period(coord)
+    coord = copy(coord)
+    velocity = zeros(size(coord))
+    i = 0
+    abs_speed_sum = 1
+    # Cycle reaches half point when all speed reaches 0.
+    while abs_speed_sum != 0
+        evolve!(coord, velocity)
+        coord += velocity
+        abs_speed_sum = sum(abs.(velocity))
+        i += 1
+    end
+    i * 2
+end
+
+function part_2(input)
+    # Each direction should be independent and have their own cycles.
+    # So get the period in each direction and find least common multiplier.
+    period_x = calc_period(input[:, 1])
+    period_y = calc_period(input[:, 2])
+    period_z = calc_period(input[:, 3])
+    lcm(period_x, period_y, period_z)
+end
+
+input = [
+    14 15 -2;
+    17 -3 4;
+    6 12 -13;
+    -2 10 -8;
+]
+
+println("Julia:")
+println("Part 1: ", part_1(input))
+println("Part 2: ", part_2(input))
diff --git a/day-12/input.txt b/day-12/input.txt
@@ -0,0 +1,4 @@
+<x=14, y=15, z=-2>
+<x=17, y=-3, z=4>
+<x=6, y=12, z=-13>
+<x=-2, y=10, z=-8>