Re: question unsort(x)

new topic     » goto parent     » topic index » view thread      » older message » newer message

Salix wrote:
> 
> It is not a typical thing but now I need a routine that is simple, fast,
> efficient
> and puts the elements of a sequence into random order. The best I could come
> up with is this.
> 
> }}}
<eucode>
> function unsort(sequence x)
> 	integer lx,px,py
> 	object bx
> 	lx=length(x)
> 	bx=x[1]
> 	x[1]=0
> 	py=1
> 	for i=1 to lx by 1 do
> 		px=rand(lx)
>         	x[py]=x[px]
>         	py=px
> 	end for
> 	x[py]=bx
> 	return x
> end function
> </eucode>
{{{

> 
> Any more efficient code? Any better idea? 
> 
> Thanks in advance!
> 
> Salix

Hello Salix,

When I have had to do this, I have found it more useful to use a function I
call RandSequence().  It returns a sequence of the same size as the original
sequence and which has randomized indexes.  Thus the original sequence is
untouched, but I can use its "randomized shadow" sequence to do what is
needed.  Here is a possible sort of use:

sequence shuffled
shuffled=RandSequence(originalSequence)
for i=1 to length(originalSequence) do
    puts(1,originalSequence[shuffled[i]]&'\n')
end for


--Quark

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu