1

可能重复:
如何在 Ruby 中生成一个包含 n 个唯一随机数的列表?

我正在尝试创建一个随机生成的 x 数字数组,没有重复。我选择数字——一次一个——然后将它们与第一个数字进行比较,然后再与数组中的所有其他数字进行比较。我看过其他问题,但我是初学者,解释有点过头了——但我正在学习。

这是我的代码。我认为“希望”正在发生的事情用大写字母解释。我的问题在最后。

array = []
array[0] = rand(10)  #THIS CHOOSES FIRST NUMBER (FN) AND PUTS IT IN THE FIRST ARRAY SPOT
p "fn = #{array[0]}"

for i in 1..6  #START OF FOR LOOP TO GET 6 NUMBERS IN THE ARRAY - WHY 6?  THE FIRST NUMBER THAT POPPED IN MY HEAD
  p "Iteration #{i} -------------------------"  # THIS IS JUST SO I KNOW WHERE I AM IN THE LOOPS

  @x = rand(10)  #THIS CHOOSES THE NEXT NUMBER AND ALL NUMBERS AFTER
  array.each do |uc|  # THIS IS THE LOOP THAT COMPAIRS ALL NUMBERS
    @type = @x == uc ? "yes" : "no"  #DOES THE CHOOSEN NUMBER EQUAL ANY NUMBER IN THE ARRAY
    p "does #{uc} = #{@x}? #{@type}"
    if @type == "yes"  # IF THE COMPAIR IS TRUE, I DONT WANT ANY THING DONE.  IT WILL CYCLE THRU AND GET A NEW NUMBER
      i = 1 
      p "YES #{@x} = #{uc}"
      break
    end  #END OF IF YESS
  end  #END OF ARRAY EACH

  if @type == "no"  #IF NO, PUT NEXT NUMBER (@X) INTO THE NEXT ARRAY SPOT.
    p "in last if type= #{@type}"  #THESE STATMENTS JUST PRINT OUT THE DIFFERENT VARIABLES SO I KNOW I AM GETTING WHAT I EXPECT
    p "in last if x = #{@x}"
    p "in last if i = #{i}"
    @x = array[i]  #THIS "SHOULD" FILL THE NEXT ARRAY SPOT - BUT DOESNT SEEM TO
    p "#{array[i]} is in the array"  #THIS PRINT OUT IS BLANK - STATEMENT ABOVE DID NOT WORK.
    p array[i]
  end  #END OF IF NO
end  #END OF FOR LOOP
4

0 回答 0