如何在这个BINGO程序中返回相同的随机数,ruby?

时间:2015-01-30 15:00:41

标签: ruby

我试图继续返回最初生成的相同随机数,然后迭代继续寻找匹配的数字,只要" BINGO"没有垂直,水平或对角线。

class BingoBoard 


    def initialize
      @bingo_board = Array.new(5) {Array(5.times.map{rand(1..100)})} #creates array with 5 sub arrays containing randomly generated numbers.
      @bingo = {'B'=>0,'I'=>1,'N'=>2,'G'=>3,'O'=>4} 
      @num = rand(1..100) #random number
      @letter_index = @bingo.values.sample #randomly generated index to target the elements in the matching index of the arrays sub-arrays.
    end

def generator #generates the display
  if @letter_index == 0
    puts"B #{@num}"
  elsif @letter_index == 1
    puts"I #{@num}"
    elsif @letter_index == 2
    puts"N #{@num}"
    elsif @letter_index == 3
    puts"G #{@num}"
    elsif @letter_index == 4
    puts"O #{@num}"
  end
end

def play #stamps X if random number is found inside sub-array of targeted index.
    if @bingo_board[@letter_index].include?(@num)
    @bingo_board[@letter_index].map! {|el| el == @num ? "X" : el}
        puts ('%3s ' * 5) % 'BINGO'.split('')
          5.times do |y|
            5.times { |x| print "%3s " % @bingo_board[x][y] } #print the sub arrays vertically, with each index side by side, starting with 0 on the left.
            puts ""
          end
    else #prints the bingo_board.
          puts ('%3s ' * 5) % 'BINGO'.split('')
          5.times do |y|
          5.times { |x| print "%3s " % @bingo_board[x][y] }
            puts " "
      end
    end
 end

def run # one method to rule them all!
  generator
  play
end

end

#=> B 83
        #  B   I   N   G   O
        #  X  18  75  83   8
        # 71  22  47  71  86
        #  3  96  50  92  96
        # 31  69  58  53  47
        # 15  78  15  94  47
#=> I 22
       #  B   I   N   G   O
       #  X  18  75  83   8
       # 71   X  47  71  86
       #  3  96  50  92  96
       # 31  69  58  53  47
       # 15  78  15  94  47
    #=> N 50
      #  B   I   N   G   O
      #  X  18  75  83   8
      # 71   X  47  71  86
      #  3  96   X  92  96
      # 31  69  58  53  47
      # 15  78  15  94  47
    #=> G 53
       #  B   I   N   G   O
       #  X  18  75  83   8
       # 71   X  47  71  86
       #  3  96   X  92  96
       # 31  69  58   X  47
       # 15  78  15  94  47
    #=> O 47
       #  B   I   N   G   O
       #  X  18  75  83   8
       # 71   X  47  71  86
       #  3  96   X  92  96
       # 31  69  58   X  47
       # 15  78  15  94   X


    #=>      "BINGO!!"

1 个答案:

答案 0 :(得分:1)

为了在ruby中生成相同的“随机”数字,您需要提供seed

因此,您首先需要创建一个带种子的随机数生成器,而不是使用rand

my_random_number_generator = Random.new(1234)

然后使用:

@bingo_board = Array.new(5) {Array(5.times.map{my_random_number_generator.rand(1..100)})}

这将始终以相同的顺序生成相同的数字。