【问题标题】:How to generate new random word element in array如何在数组中生成新的随机词元素
【发布时间】:2014-11-18 21:41:01
【问题描述】:

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

【问题讨论】:

  • 你的意思是一个新的随机颜色?只需移动循环内选择随机颜色的线即可。
  • 每次在循环内采样,例如correct_guesses.include?(colors.sample)

标签: ruby arrays


【解决方案1】:
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

【讨论】:

  • 我知道您尽可能地遵守 OP 的代码,但 OP 应该知道删除 num_guess = 0num_guess = num_guess + 1 行并替换 while 会更符合规范符合total_guesses.times do |num_guess|。可能还将else 更改为end 并在关闭end 之前删除end
【解决方案2】:

为正确答案创建一个外循环

您可以通过在外部循环中迭代您的正确答案来做您想做的事情,并使用像 #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

【讨论】:

  • 侏儒,玩家只能获得有限的猜测次数。在示例中它是 10,因为只有六种颜色,所以应该很多,但您可能希望将其视为变量。将删除此评论...
  • @CarySwoveland 不。 colors.each_index 对每种可用的颜色进行猜测。根据定义,如果你不能重复猜测,你永远不需要更多。如果您希望它少于,那么(0...4) 或任何OP 的选项。你可以把自己逼疯,试图去想每一个边缘情况;规范的答案很棒,但不必要的详尽答案只会浪费每个人的时间。 YMMV。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-27
  • 1970-01-01
  • 1970-01-01
  • 2017-05-10
  • 1970-01-01
  • 2020-07-20
  • 1970-01-01
相关资源
最近更新 更多