in reply to Re: How can I print all the numbers from 1 to n in random order?
in thread How can I print all the numbers from 1 to n in random order?
Here is a better way to do it:
As the array becomes longer, the probablility of your routine finding an unused space becomes smaller and smaller. With a 1..10 shuffle the probablility of finding the right element for the last space is one in ten - which means you will need 10 tries (on the average). Not too bad. But with a 1..100000 array, you will need 100_000 tries to fill in the last element. and 99_999 to find the next to last, and... you get the idea. It will take a LOOONG time.sub RandomiseArray { my @a=@_; my @b=(); while (scalar @a) { push(@b,splice(@a,int(rand @a))); } return(@b); }
Yeah, I could do it inplace (without the second copy of the array), but I'm going to save that for another time.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Answer: How can I print all the numbers from 1 to n in random order?
by ysth (Canon) on Apr 22, 2004 at 10:07 UTC | |
by halley (Prior) on Apr 23, 2004 at 14:50 UTC | |
by ysth (Canon) on Apr 23, 2004 at 16:30 UTC |