aboutsummaryrefslogtreecommitdiff
path: root/day12/part1
diff options
context:
space:
mode:
authorNat Lasseter <user@4574.co.uk>2019-12-12 10:47:43 +0000
committerNat Lasseter <user@4574.co.uk>2019-12-12 10:47:43 +0000
commitc10f57e05b79ac82d8fc55c534a0e665b3e13344 (patch)
tree04dc8f45aab37ec8cffb039ac342fbb105d3511e /day12/part1
parent6fd5a2e117df690f4b3d79c0ca140805bbb29282 (diff)
Day 12, Part 1 only
Diffstat (limited to 'day12/part1')
-rwxr-xr-xday12/part143
1 files changed, 43 insertions, 0 deletions
diff --git a/day12/part1 b/day12/part1
new file mode 100755
index 0000000..2debadf
--- /dev/null
+++ b/day12/part1
@@ -0,0 +1,43 @@
+#!/usr/bin/env ruby
+
+def apply_gravity(moons)
+ (0...moons.count).to_a.combination(2).each do |a, b|
+ 3.times do |i|
+ case moons[a][0][i] <=> moons[b][0][i]
+ when -1
+ moons[a][1][i] += 1
+ moons[b][1][i] -= 1
+ when 1
+ moons[b][1][i] += 1
+ moons[a][1][i] -= 1
+ end
+ end
+ end
+ moons
+end
+
+def update(moons)
+ moons.map do |moon|
+ [moon[0].zip(moon[1]).map(&:sum), moon[1]]
+ end
+end
+
+def calculate_energy(moons)
+ moons.map { |moon|
+ moon[0].map(&:abs).sum * moon[1].map(&:abs).sum
+ }.sum
+end
+
+input = $stdin.readlines.map(&:strip)
+
+moons = input.map do |line|
+ m = line.scan(/-?\d+/)
+ [[m[0].to_i, m[1].to_i, m[2].to_i], [0, 0, 0]]
+end
+
+1000.times do
+ moons = apply_gravity(moons)
+ moons = update(moons)
+end
+
+puts calculate_energy(moons)