blob: f5b0f9684daaa427469df67983834df8099edf91 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
#!/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
initx = moonsx.map { |m| [m[0], m[1]] }
xlen = 0
loop do
moonsx = apply_gravity(moonsx)
moonsx = update(moonsx)
xlen += 1
break if initx == moonsx
end
inity = moonsy.map { |m| [m[0], m[1]] }
ylen = 0
loop do
moonsy = apply_gravity(moonsy)
moonsy = update(moonsy)
ylen += 1
break if inity == moonsy
end
initz = moonsz.map { |m| [m[0], m[1]] }
zlen = 0
loop do
moonsz = apply_gravity(moonsz)
moonsz = update(moonsz)
zlen += 1
break if initz == moonsz
end
puts [xlen, ylen, zlen].reduce(1, :lcm)
|