1

Possible Duplicate:
How do I generate a list of n unique random numbers in Ruby?

I am trying to create a randomly generated array of x numbers with no duplicates. I am choosing numbers—one at a time—then comparing them to the first number, and then all the other numbers in the array. I have looked at the other questions, but I am a beginner and the explanations are a bit over my head—but I am learning.

Here is my code. There are explanations in capital letters of what I think "hope" is going on. My problem is at the end.

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
Community
  • 1
  • 1
Jeff Kyzer
  • 616
  • 2
  • 7
  • 14
  • Why on earth are you using `"yes"` & `"no"` instead of `true` & `false`?? – Andrew Marshall Nov 10 '12 at 16:50
  • No, not personal preference, you are avoiding the correct types, which will cost you a lot of functionality and makes your code unreadable and bloated. We use `true` and `false` in Ruby, not any String. – aef Nov 10 '12 at 17:10
  • Thanks for the insight. Would I then switch my if statement to if @type == "true" or is there something else i have not run across. Thanks much for your help. – Jeff Kyzer Nov 10 '12 at 17:46
  • You should consider using the built-in methods, rather than manually using various loops. See Duncan Beevers answer in the question that Intrepidd referenced, which would be (0..9).to_a.sample(6) in your case. – Justin Ko Nov 10 '12 at 18:05
  • You'll learn a LOT if you post this on http://codereview.stackexchange.com – Mark Thomas Nov 10 '12 at 18:52

0 Answers0