How to generate 5 random numbers without repeating?

Find quick help here to get you started with Hollywood
marko
Posts: 56
Joined: Wed Dec 15, 2010 5:19 pm
Contact:

Re: How to generate 5 random numbers without repeating?

Post by marko »

This generates 5 random numbers between 0 and 9 without repeating any number:

Code: Select all

found_i = 0
Dim numbers[4] ; array of size 5

For i = 0 To 4 
	Repeat
		r = Rnd(10)   ; Random number between 0 and 9
		isRepeat = False
		numbers[found_i] = r

		For j = 0 To found_i   ; Search all saved numbers
			If j<>found_i And r=numbers[j]   ; Is it a repeat number?
				isRepeat = True
			EndIf
		Next
	Until isRepeat = False   ; Redo number until no repeat found
	
	found_i = found_i + 1
Next

; Print the found numbers
For i = 0 To 4 
	DebugPrint(numbers[i])
Next
AmigaOS 4.1 on Sam440ep-flex@800MHz
http://www.m4rko.com/amiga
marko
Posts: 56
Joined: Wed Dec 15, 2010 5:19 pm
Contact:

Re: How to generate 5 random numbers without repeating?

Post by marko »

Oops, first line should read:

Code: Select all

Dim numbers[5] ; array of size 5
AmigaOS 4.1 on Sam440ep-flex@800MHz
http://www.m4rko.com/amiga
marko
Posts: 56
Joined: Wed Dec 15, 2010 5:19 pm
Contact:

Re: How to generate 5 random numbers without repeating?

Post by marko »

The code snipped above is more appropriate if you want just some random numbers within a range (but no repeating numbers)...

But if you want an even range, say 10 numbers from 0 to 9 but random, then this snippet below is much better (faster) :)

Code: Select all

Dim numbers[10]

For i = 0 To 9
	numbers[i] = i
Next

For i = 0 To 9
	tempVar = numbers[i]
	r = Rnd(10)   ; Random number between 0 and 9
	numbers[i] = numbers[r]
	numbers[r] = tempVar
Next

; Print the found numbers
For i = 0 To 9
	DebugPrint(numbers[i])
Next
AmigaOS 4.1 on Sam440ep-flex@800MHz
http://www.m4rko.com/amiga
User avatar
Juan Carlos
Posts: 891
Joined: Mon Sep 06, 2010 1:02 pm

Re: How to generate 5 random numbers without repeating?

Post by Juan Carlos »

Thanks Marko for the code its work perfect I tested with 52 numbers and it works fine too, perfect to make a game of cards.
Again thanks for your help.
marko
Posts: 56
Joined: Wed Dec 15, 2010 5:19 pm
Contact:

Re: How to generate 5 random numbers without repeating?

Post by marko »

@Juan Carlos

You are welcome, glad I could help :)
AmigaOS 4.1 on Sam440ep-flex@800MHz
http://www.m4rko.com/amiga
Post Reply