在ruby

时间:2017-01-10 12:14:18

标签: arrays ruby random

我有一系列问题,我希望从中得到一个非收获的随机问题。所以例如5个问题,如果被问到,我只会重新开始。我想把它放入一个方法(或类似的东西)

def askrandom
questions = ["A?", "B?" , "C?" , "D?"]

return #random question
end

输出应该是

A? C? D? B? #all questions where asked once, so repeat

B? D? C? A? ...

5 个答案:

答案 0 :(得分:2)

为避免重复问题,您必须将剩余的问题存储在某处,让我们使用实例变量:

def initialize
  @remaining_questions = []
end

让我们将问题提取到自己的方法中:

def questions
  ["A?", "B?" , "C?" , "D?"]
end

现在,如果@remaining_questions为空,则使用随机播放的questions副本对其进行初始化。然后,您只需删除(并返回)第一项:

def ask_random
  @remaining_questions = questions.shuffle if @remaining_questions.empty?
  @remaining_questions.shift
end

答案 1 :(得分:2)

这与@ Stefan的解决方案非常接近,但想法略有改变。

class Questions
  def initialize(array_of_questions)
    @questions = array_of_questions
    @nums ||= get_nums
  end

  def get_nums
    (0...@questions.size).to_a.shuffle
  end

  def get_num
    @nums.pop or (@nums = get_nums).pop
  end

  def pick
    @questions[get_num]
  end
end

questions = Questions.new(["A", "B", "C", "D"])

10.times.map{ questions.pick }
#=> ["B", "D", "C", "A", "C", "A", "B", "D", "A", "B"]

答案 2 :(得分:0)

纯粹的功能方法:

def ask(question)
  question.tap { |q| puts "Asking question #{q}" }
end

def askrandom(asked = [], remaining = ["A?", "B?" , "C?" , "D?"].shuffle)
  return asked if remaining.empty?
  askrandom(asked << ask(remaining.pop), remaining)
end

答案 3 :(得分:0)

def fire_away(questions)
  @n = (@n || -1) + 1
  @order = [*0...questions.size].shuffle if @n % questions.size == 0
  questions[@order.shift]
end

q = ["A?", "B?" , "C?" , "D?"]

fire_away q #=> "D?" 
fire_away q #=> "A?" 
fire_away q #=> "C?" 
fire_away q #=> "B?" 
fire_away q #=> "B?" 
fire_away q #=> "C?" 
fire_away q #=> "A?" 
fire_away q #=> "D?" 
fire_away q #=> "A?" 
fire_away q #=> "C?" 
fire_away q #=> "B?" 
fire_away q #=> "D?" 

您可能还需要方法

def reset_questions
  @n = nil
end

@ fl00r提出以下建议,以避免需要在定义fire_away的类中可见的实例变量(并且不需要方法reset_questions):

def fire_away(questions)
  n = -1
  order = nil
  Proc.new do
    n += 1
    order = [*0...questions.size].shuffle if n % questions.size == 0
    questions[order.shift]
  end
end

iterator = fire_away ["A", "B", "C", "D"]

iterator.call #=> "C" 
iterator.call #=> "A" 
iterator.call #=> "B" 
iterator.call #=> "D"
iterator.call #=> "D"

另一种方法是创建一个单独的类(非常接近@ fl00r&#39;答案)。

class Questions
  def initialize(*questions)
    @questions = questions
    @n = -1
  end
  def next_question
    @n += 1
    @order = [*0...@questions.size].shuffle if @n % @questions.size == 0
    @questions[@order.shift]        
  end
end

q = Questions.new("A?", "B?" , "C?" , "D?")
q.next_question #=> "C?" 
q.next_question #=> "A?" 
q.next_question #=> "D?" 
q.next_question #=> "B?" 
q.next_question #=> "B?" 

这两项修改明显优于我原来的答案。

答案 4 :(得分:-1)

我通常会创建一个新数组,随机后我会追加一个随机的值,如果它在新数组中不存在。
如果您像上次一样得到相同的输出,则意味着输出是在新数组中,因为您附加了它 抱歉我的傻英语。