Random number generation

Discussion in 'Rebol' started by MaxV, Aug 9, 2010.

  1. MaxV

    MaxV Member

    Hello,
    I have a problem, I need to extract 10 different random numbers from 1 to 20.
    Ok, it seems simple, but I can't get 10 different numbers; I need an extraction like:
    1 - 3 - 4 - 7 - 8 -12 -15 - 16 - 17 - 18

    but my script goes in forever loop:

    Code:
    random/seed now
    extrac: copy [] ;extraction
    counter: 0
    until [
       counter: counter + 1
       verify: true
       clear extrac
       extrac: head extrac
       loop 10 [ insert extrac random 20 ]
       sort extrac
       forall  extrac [
          if  (index? extrac) = 10 [break]
          if (( first extrac ) = ( second extrac))  [ verify: false ]
          ]
      print remold ["Tentative number:" counter]
       verify
       ]
    print extrac
    
    1-20 it's a very close range and PC has troubles to get 10 different numbers...
  2. MaxV

    MaxV Member

    OK, I found another way:
    Code:
    random/seed now
    a: copy []
    until [
    	b: random 20
    	check: true
    	foreach temp a [
    		if temp = b [ check: false]
    		]
    	if check = true [ append a b ]
    	(length? a) = 10
    	]
    print a
    
    What do you think?
  3. Graham

    Graham Developer Staff Member

    No need to do 'foreach

    You can do something like this (untested)

    Code:
    if not check: find a b [ append a b ]
    
  4. notchent

    notchent Member

    Max, it's just another 1 liner for us REBOLers :)

    a: copy/part random [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20] 10
  5. notchent

    notchent Member

    Oops, actually 2 lines, since we need random/seed now ... but, of course we can just do:

    random/seed now a: copy/part random [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20] 10

    (DO NOT use this line in production code, or you will get some duplicates. Put random/seed now on a separate line, and run the previous example multiple times, when needed).
  6. MaxV

    MaxV Member

    wow!!!! :eek: Great example!!!!

Share This Page