blob: 2debadff6dd4c1f67d181042e0a0d77f0e4f5ffd (
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
|
#!/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)
|