繁体   English   中英

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

[英]How to generate new random word element in array

我正在尝试从数组元素中生成一个新的随机选择。 当前,它在第一次通过数组时随机选择,然后下一次选择相同,直到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
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

创建正确答案的外循环

您可以通过在外部循环中遍历正确答案并使用#shuffle等Array方法来完成所需的操作。 #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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM