Page 1 of 1

generate random numbers without repeat

Posted: Tue Dec 11, 2012 1:42 pm
by tolkien
I want to generate some random number but without repeating.
I have a table where store the new number and compare if it is used. Know the theory but It doesn't work.
Any help friends?

Re: generate random numbers without repeat

Posted: Tue Dec 11, 2012 7:52 pm
by PEB
I suppose this is one way you can do it (if I understand your question correctly).

Code: Select all

TotalNumbers=25
NumbersTable$={}

For Local x=1 to TotalNumbers
	NumbersTable$[x-1]=x
Next

Function p_ShowRandom()
	Local RemainingVar=TotalNumbers
	TempTable$=CopyTable(NumbersTable$)
	For Local x=1 to TotalNumbers
		Local n=Rnd(RemainingVar)
		DebugPrint(RemoveItem(TempTable$, n))
	Next
EndFunction

p_ShowRandom

Re: generate random numbers without repeat

Posted: Wed Dec 12, 2012 7:30 am
by tolkien
Hey PEB. Thanks so much. I'll try your code this evening.
I revised my idea and found an incredible stupid error that makes me feel asshole. three days in such simple question.

Thanks again.

Re: generate random numbers without repeat

Posted: Fri Dec 14, 2012 6:21 am
by PEB
Ooooops! I just noticed that I left a line out. This is what the function should look like:

Code: Select all

Function p_ShowRandom()
	Local RemainingVar=TotalNumbers
	TempTable$=CopyTable(NumbersTable$)
	For Local x=1 to TotalNumbers
		Local n=Rnd(RemainingVar)
		DebugPrint(RemoveItem(TempTable$, n))
		RemainingVar=RemainingVar-1; (This was the line I left out.)
	Next
EndFunction

Re: generate random numbers without repeat

Posted: Fri Dec 14, 2012 5:47 pm
by PEB
This may be a more useful function (one that returns a new, shuffled table):

Code: Select all

NumbersTable$={}
TotalNumbers=25
For Local x=1 to TotalNumbers
	NumbersTable$[x-1]=x
Next

Function p_ShuffleTable(StartTable$)
	Local RemainingVar=ListItems(StartTable$)
	Local TotalItems=RemainingVar
	Local TempTable$=CopyTable(StartTable$)
	Local NewTable$={}
	For Local x=1 to TotalItems
		Local n=Rnd(RemainingVar)
		NewTable$[x-1]=RemoveItem(TempTable$, n)
		RemainingVar=RemainingVar-1
	Next
	Return(NewTable$)
EndFunction

RandomTable$=p_ShuffleTable(NumbersTable$)

DebugPrint(Unpack(NumbersTable$))
DebugPrint(Unpack(RandomTable$))
It might be nice to have a built in function---Shuffle()---as a kind of opposite to Sort().

Re: generate random numbers without repeat

Posted: Fri Dec 14, 2012 6:50 pm
by tolkien
I think I´ll use one of them. Very useful! Thanks again!