Day 7: The Treachery of Whales

# Adbent Calendar Day1-1

array = [];
File.foreach("7_input.dat").with_index do |line, line_num|
  array.push(line)
end
positions = array[0].split(',').map(&:to_i)
# p positions

# p positions.size

# p positions.max

# p positions.min


i = positions.min
max = positions.max
cont = []
while i != max do
  e = 0
  positions.each do |n|
    if i != n then
      temp = 0
      a = (n-i).abs
      b = (n-i).abs + 1
      c = (a * b)/ 2
      e = e + c
    end
  end
  cont.push(e)
  puts "#{i} position: #{e} energy"
  i = i + 1
end

puts cont.min

雑感

二点間の距離を比較していく問題。問1は差の絶対値を取るだけでよく、問2は距離の増え方がいわゆる階差数列になっているかに気づけるかどうかがポイントだった。d=(n)*(n+1)/2が分かれば後は単純処理。そのうちフィボナッチ数列とかも出てくるかも?

今回のもおもしろかった。