日々精進

新しく学んだことを書き留めていきます

プログラミングコンテストチャレンジブック演習「Saruman's Army」

今回のお題はこちら。

Rubyはeach_with_indexとかselectとかmapとか、配列に便利なメソッドが揃ってていいですね。

R = 10 #input
X = [1, 7, 15, 20, 30, 50] #input

$covered = Array.new(X.length, 0)
count = 0
for i in 0..(X.length - 1)
  if $covered[i] == 0
    count += 1
    markingX = X.select{|x| x <= X[i] + R}.max
    X.each_with_index do |x, i|
      $covered[i] = 1 if markingX - R <= x && x <= markingX + R
    end
  end
end

puts count