0
0

More than 3 years have passed since last update.

誕生日あて問題

Last updated at Posted at 2019-11-07

Rubyアルゴリズム問題

誕生日あて問題を作ろう

今回作るプログラムは誕生日あてプログラムです

仕様

①1〜31日のなかから、ランダムで誕生日を一つ自動的に決めます

②予想を入力し、結果により出力を以下5パターン変えます
・正解
・20日以上離れている
・10日以上離れている
・10日以内
・3日以内

③5回で正解しなければゲームオーバーにします

答え

誕生日あて問題回答
#正解
def yes(num)
  puts "正解!"
  puts "#{num}回目であたったよ"
  exit
end

#不正解
def no(num, input, birthday)
  difference = (input - birthday)**2
  if num == 5
    puts "Game Over"
    exit
  elsif difference >= 400
    puts "20日以上離れてる。見当違いだよ"
  elsif difference >= 100
    puts "10日以上離れてる。"
  elsif difference >= 16
    puts "10日以内だよ。少し近いよ"
  else
    puts "3日以内!惜しい!"
  end
end

#誕生日をランダムで決める
birthday = rand(1..31)
puts "私の誕生日を5回以内に当ててね"
num = 1

while true do
  puts "#{num}回目のチャレンジです"
  puts "1~31日のいつだと思いますか?"
  input = gets.to_i

  if birthday == input
    yes(num)
  elsif input < 1 || input >31
    puts "当てる気ありますか?"
  else
    no(num, input, birthday)
  end
  num += 1
end

0
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
0
0