Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Random (Rnd) question... 1

Status
Not open for further replies.

snayjay

Programmer
Oct 23, 2001
116
US
I need to choose 20 randoms numbers from 1-30 and put them in a string joined by ",". I'm using the code:

Code:
    Dim x, y
    x = 1
    y = ""
    Do Until x = 31
        y = y & Int((30 - 1 + 1) * Rnd + 1) & ","
        x = x + 1
    Loop
    y = Left(y, Len(y) - 1)

    [green]'example result[/green]
    22,17,18,9,10,24,1,23,25,22,2,13,26,24,12,29,27,2,29,11,16,24,2,18,15,9,19,20,8,11

Problem is I can't have duplicates... anyone know the fix?
 
Do you mean twenty of thirty? You say twenty but show thirty. If you mean twenty:

Code:
    Dim x, y
    x = 1
    y = ""
    Do Until Len(y) - Len(Replace(y, ",", "")) = 20
        x = Int((30 - 1 + 1) * Rnd + 1)
        Debug.Print x
        y = y & IIf(InStr(y, x) > 0, "", x & ",")
    Loop
    y = Left(y, Len(y) - 1)

If you mean thirty, I suggest you order a table of thirty numbers by a random number.
 
Remou,

Thanks for responding so quickly. You were right I meant 20. The code you gave is great, it solved the duplicate issue... well kinda. It does give 20 numbers 1-30 and none duplicate. But if I run it 20 times it gives me the same 20 numbers. Is there a way to make it give me 20 different numbers each time? Thanks in advance,

Snayjay
 
You need Randomize:

Code:
    Dim x, y
    Randomize
    x = 1
    y = ""
    Do Until Len(y) - Len(Replace(y, ",", "")) = 20
        x = Int((30 - 1 + 1) * Rnd + 1)
        'Debug.Print x
        y = y & IIf(InStr(y, x) > 0, "", x & ",")
    Loop
    y = Left(y, Len(y) - 1)
 
You rock!... Now I just wish I could make heads or tails of your code, so I could reuse it for other scenarios.
 
It does a count of commas (len(y)-Replace etc) and a check as to whether the number has been added or not (instr etc).

The line:
[tt]Int((30 - 1 + 1) * Rnd + 1)[/tt]
Is yours. I have no idea why it has 30-1+1 and not just:
[tt]Int((30 * Rnd) + 1)[/tt]
 
Reason I used 30 - 1 + 1 is because Microsoft Access Help said to use:
Code:
Int((upperbound - lowerbound + 1) * Rnd + lowerbound)
I just filled in the blanks. I didn't quite understand it, I just used it and then looked at the result. Didn't understand how to fix it so I asked.

As for your code, I still don't understand it... works great... but I'm lost. Thanks anyway, maybe one day I'll look back and it will make more sense.
 
I didn't quite understand it
Keep in mind that the Rnd function returns a value >=0 and <1

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top