LoginSignup
3
6

More than 3 years have passed since last update.

選挙の演説の候補者の計算【ruby初心者】

Last updated at Posted at 2019-06-27

はじめに

演説が終わるたび「他のそれぞれの立候補者の支持者から 1 人ずつ」および「誰も支持していない有権者から 1 人」支持者が増える。
その場合、最終結果で一番多い支持を集めた立候補者の番号を取得する。

実際のコード

#M は立候補者の人数を、N は有権者の人数を、K は演説が行われる回数
m,n,k = gets.split(" ").map &:to_i

#誰がどの順番で演説したかを表す整数 a_1, ..., a_K
a = readlines.map &:to_i

#立候補者の人数に応じて、支持者の人数を図れる配列を用紙
r=[]
m.times {r.push(0)}

#すべての演説が終わった後、最も支持者が多い立候補者の番号(複数ある場合は、すべて出力)
a.each do |i|
    #誰も支持していない人が、指示をする
    if n >0
        n -= 1
        r[i-1] += 1
    end
    #他の人を支持している人が、指示をする
    r.count.times do |t|
        if r[t] >0
            r[t] -= 1
            r[i-1] += 1
        end
    end
end

#最大数を返す
r.each_index do |t|
    if r[t] == r.max
        puts t+1
    end
end
3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6