aboutsummaryrefslogtreecommitdiff
path: root/day12
diff options
context:
space:
mode:
authorNat Lasseter <user@4574.co.uk>2019-12-12 11:57:27 +0000
committerNat Lasseter <user@4574.co.uk>2019-12-12 11:57:27 +0000
commit87f64bc00dbe5778bfc273754a3e561c1f25ac57 (patch)
tree855d6b6f37fec8880a324c61a9cfa8f83fc5f45b /day12
parentc10f57e05b79ac82d8fc55c534a0e665b3e13344 (diff)
Day 12, part2, passes examples, takes forever with my input
Diffstat (limited to 'day12')
-rwxr-xr-xday12/part280
1 files changed, 80 insertions, 0 deletions
diff --git a/day12/part2 b/day12/part2
new file mode 100755
index 0000000..237432f
--- /dev/null
+++ b/day12/part2
@@ -0,0 +1,80 @@
+#!/usr/bin/env ruby
+
+def apply_gravity(moons)
+ ms = moons.map { |m| [m[0], m[1]] }
+ (0...ms.count).to_a.combination(2).each do |a, b|
+ case ms[a][0] <=> ms[b][0]
+ when -1
+ ms[a][1] += 1
+ ms[b][1] -= 1
+ when 1
+ ms[b][1] += 1
+ ms[a][1] -= 1
+ end
+ end
+ ms
+end
+
+def update(moons)
+ moons.map do |moon|
+ [moon[0] + moon[1], moon[1]]
+ end
+end
+
+input = $stdin.readlines.map(&:strip)
+
+moonsx = input.map do |line|
+ m = line.scan(/-?\d+/)
+ [m[0].to_i, 0]
+end
+
+moonsy = input.map do |line|
+ m = line.scan(/-?\d+/)
+ [m[1].to_i, 0]
+end
+
+moonsz = input.map do |line|
+ m = line.scan(/-?\d+/)
+ [m[2].to_i, 0]
+end
+
+xs = [moonsx.dup]
+loop do
+ moonsx = apply_gravity(moonsx)
+ moonsx = update(moonsx)
+ if xs.include?(moonsx) then
+ break
+ else
+ xs << moonsx.dup
+ end
+end
+xintro = xs.index(moonsx)
+xlen = xs.count - xintro
+
+ys = [moonsy.dup]
+loop do
+ moonsy = apply_gravity(moonsy)
+ moonsy = update(moonsy)
+ if ys.include?(moonsy) then
+ break
+ else
+ ys << moonsy.dup
+ end
+end
+yintro = ys.index(moonsy)
+ylen = ys.count - yintro
+
+zs = [moonsz.dup]
+loop do
+ moonsz = apply_gravity(moonsz)
+ moonsz = update(moonsz)
+ if zs.include?(moonsz) then
+ break
+ else
+ zs << moonsz.dup
+ end
+end
+zintro = zs.index(moonsz)
+zlen = zs.count - zintro
+
+puts [xintro, yintro, zintro].max + [xlen, ylen, zlen].reduce(1, :lcm)