我的代碼:紅寶石選擇與蘭特方法隨機幾個選項
alea = ["x", " "]
num = alea.length
choice = rand(num)
veinte = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in veinte
puts alea[choice]
end
我希望我的代碼中隨機選擇幾個選項Y沒有唯一的一個。例如:
x
x
x
x
x
x
我該怎麼做?
我的代碼:紅寶石選擇與蘭特方法隨機幾個選項
alea = ["x", " "]
num = alea.length
choice = rand(num)
veinte = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in veinte
puts alea[choice]
end
我希望我的代碼中隨機選擇幾個選項Y沒有唯一的一個。例如:
x
x
x
x
x
x
我該怎麼做?
Array#sample
被髮明出來用於此目的:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map do |elem|
[elem, [true, false].sample]
end.to_h
#⇒ {
# 1 => true,
# 10 => false,
# 2 => true,
# 3 => true,
# 4 => false,
# 5 => true,
# 6 => false,
# 7 => true,
# 8 => false,
# 9 => false
#}
只需編輯代碼:
alea = ["x", " "]
num = alea.length
choice = rand(num)
veinte = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
veinte.map { puts alea[rand(alea.length)] }
你所得到的輸出根據你所編寫的代碼是正確的:
alea = ["x", " "] # => Array on only two elements
num = alea.length # => 2
choice = rand(num) # => rand(2) will only output either 0 or 1 which will always output either alea[0] or alea[1] which is " " or "x"
如果你真的想要一個數組的隨機值,然後我們e @mudasobwa建議的Array類的示例方法
看起來您只需要一定數量的隨機選擇的項目。在這種情況下,只需使用塊形式的Array構造函數:
Array.new(10){ ["x", " "].sample }
#=>[" ", " ", "x", " ", "x", " ", "x", " ", "x", "x"]
這更具可讀性和優雅性。 – Bala
[1,2,3,4,5,6,7,8,9,10] .map do | elem | puts [「x」,「」] .sample end – Cleon
如果您只需要放置''x'-es或空格,'1.upto(10).each {puts [「x」,「」] .sample}更適用(甚至是「10.times {puts ...}」。)當你不需要結果時,你不應該「映射」。 「每個」都足夠了。當你不需要它時,你可以忽略塊變量。 – mudasobwa