aboutsummaryrefslogtreecommitdiff
path: root/day12/part1
diff options
context:
space:
mode:
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)