generate random numbers without repeat

Discuss any general programming issues here
Post Reply
tolkien
Posts: 190
Joined: Sun Oct 17, 2010 10:40 pm
Location: Spain

generate random numbers without repeat

Post 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?
PEB
Posts: 569
Joined: Sun Feb 21, 2010 1:28 am

Re: generate random numbers without repeat

Post 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
tolkien
Posts: 190
Joined: Sun Oct 17, 2010 10:40 pm
Location: Spain

Re: generate random numbers without repeat

Post 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.
PEB
Posts: 569
Joined: Sun Feb 21, 2010 1:28 am

Re: generate random numbers without repeat

Post 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
PEB
Posts: 569
Joined: Sun Feb 21, 2010 1:28 am

Re: generate random numbers without repeat

Post 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().
tolkien
Posts: 190
Joined: Sun Oct 17, 2010 10:40 pm
Location: Spain

Re: generate random numbers without repeat

Post by tolkien »

I think I´ll use one of them. Very useful! Thanks again!
Post Reply