如何在数组中生成新的随机字元素

时间:2014-11-18 21:41:02

标签: ruby arrays

我正在尝试从数组元素生成一个新的随机选择。目前,它在第一次通过数组时随机选择,然后下一个选择是相同的,直到10次。

colors = ["red", "green", "orange", "yellow", "blue", "purple"]
comp_guess = colors.sample

correct_guesses = ["red","green","orange","yellow"]
total_guesses = 10
num_guess = 0

while num_guess < total_guesses do
  if(correct_guesses.include?(comp_guess))
    puts comp_guess
    puts "You got it right."
    num_guess = num_guess + 1
  else
    puts "You got it wrong. Guess again."
  end
  puts "The number of guess is " + num_guess.to_s
end

运行后的输出。一旦进入循环,我想要新的随机数。

orange
You got it right.
The number of guess is 1
orange
You got it right.
The number of guess is 2
orange
You got it right.
The number of guess is 3
orange
You got it right.
The number of guess is 4
orange
You got it right.
The number of guess is 5
orange
You got it right.
The number of guess is 6
orange
You got it right.
The number of guess is 7
orange
You got it right.
The number of guess is 8
orange
You got it right.
The number of guess is 9
orange
You got it right.
The number of guess is 10

2 个答案:

答案 0 :(得分:2)

colors = ["red", "green", "orange", "yellow", "blue", "purple"]   
correct_guesses = ["red","green","orange","yellow"]

total_guesses = 10
num_guess = 0

while num_guess < total_guesses do
  comp_guess = colors.sample
  puts comp_guess
  if(correct_guesses.include?(comp_guess))
    puts "You got it right."
    break
  else
    puts "You got it wrong. Guess again."
    num_guess = num_guess + 1
  end
  puts "The number of guess is " + num_guess.to_s
end

答案 1 :(得分:0)

为正确答案创建外部循环

您可以通过在外部循环中迭代正确答案,并使用#shuffle!#each_index等数组方法来处理随机化,从而实现您想要的效果。当你想避免多次猜测时,这通常比#sample更好。例如:

colors  = %w[Red Green Orange Yellow Blue Purple]
answers = colors.shuffle.take 4

answers.each do |answer|
  puts "Secret color is: #{answer}"
  colors.shuffle!
  colors.each_index do |i|
    guess = colors[i]
    print "Guess #{i.succ}: "
    if guess == answer
      puts "#{guess} is right. "
      break
    else
      puts "#{guess} is wrong."
    end
  end
  puts
end