LoginSignup
2
0

More than 1 year has passed since last update.

[Ruby]点数を自動的に当てるプログラム

Posted at

はじめに

プログラミングの基礎力を上げる勉強したので、勉強記録として投稿します。

問題

スコアを当てるプログラムを書きなさい。
ただし中央値で判定を繰り返して答えを求めるような設計にしてください。
また最高点は動的に変えられるものとする

※以下具体例
100点満点の場合
スクリーンショット 2021-06-14 1.01.38.png

それ以上の数字だった場合は

スクリーンショット 2021-06-14 1.02.57.png

このように中央値を取っていき少しづつ正解の数字を当てていくようにします。
また中央値をとった回数がわかるようにします

例:83が答えの場合
答えは83で6回判定しました

解答

回答は以下になります。

def guess_score(limit,score)
  uplimit = limit 
  downlimit = 0
  guess = limit / 2
  p guess
  if guess == score
    puts "答えは" + guess.to_s + "1回判定しました"
  end
  2.step do |i|
    if score > guess
      downlimit = guess
      guess += (uplimit - guess)/2
    elsif score < guess
      uplimit = guess
      guess -= (guess - downlimit)/2
    end

    guess.ceil
    if guess == score
      puts "答えは" + guess.to_s + "で"+ i.to_s + "回判定しました"
    end
    p guess
  end
end

実行すると以下のようになります。

guess_score(100,83)

=>
50
75
87
81
84
答えは83で6回判定しました
2
0
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
2
0