0
0

More than 1 year has passed since last update.

randとshuffleメソッドを使って運勢を表示するプログラムを作る

Posted at

問題
誕生日を入力すると、今日の運勢を表示してくれるプログラムを作る。
占い結果については、以下のアルゴリズムにて判定する。
必ず、メソッドを作成しそれを呼び出すように記述。

・引数として誕生日の数字を受け取る(例:4月3日なら403、11月15日なら1115と入力)
・誕生日の数字に、乱数で生成された0 ~ 9の数字のいずれかを掛け算し、その後4で割った時の余りを算出
・シャッフルした占い結果を格納した配列から、上記の数値の順番の値を取り出す
 ["凶","中吉","吉", "大吉"]

自分の答え

def divination(birthday)
    `num = rand(10)` 
calc = birthday*num%4
results=["凶","中吉","吉", "大吉"].shuffle
puts results(calc)
end

birthday=gets.to_i
divination(birth_day)

模範解答

def result_of_uranai(birthday)
  results = ["凶", "中吉", "吉", "大吉"].shuffle
  num = birthday * rand(10) % 4
  puts "今日のあなたの運勢は、#{results[num]}だよ!"
end

puts "誕生日を入力してください!"

birthday = gets.to_i
result_of_uranai(birthday)

模範解答を確認すると、式は一つで完結しており、num = rand(10)と代入は不要。
定義する事に集中して、『puts "誕生日を入力してください!"』や、puts 『"今日のあなたの運勢は、#{results[num]}だよ!"』の文字列が不足している。

rand
指定された範囲でランダムに数値を生成することができる。
リファレンスマニュアル(https://docs.ruby-lang.org/ja/latest/method/Kernel/m/rand.html)

shuffle
配列の要素をランダムシャッフルして、その結果を配列として返す。
リファレンスマニュアル(https://docs.ruby-lang.org/ja/latest/method/Array/i/shuffle.html)

0
0
1

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