
Kanji
User
Oct 4, 2000, 7:46 PM
Post #2 of 3
(1189 views)
|
Re: Randomizing numbers in an array
[In reply to]
|
Can't Post
|
|
For starters, I don't see anywhere in your code where you insert numbers into @RandNums. Is that really how it is or a typo on your part in the code? You also have an exit() inside your while(), so no matter what you do, you're always going to exit() after the first number is generated. ( As an aside, there's no reason to set $match to "true" or "false" when 1 or 0 will do. ) I suspect you meant something like ... <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> $numstds = 10; for ($count = 1; $count <= $numstds; ++$count) { $match = 1; while ( $match ) { $RanNum = int rand (10) + 1; $match = &do_compare; } push @RandNums, $RanNum; } sub do_compare { foreach $num (@RandNums) { return 1 if ($RandNum == $num); } return 0; }</pre><HR></BLOCKQUOTE> The trouble with that is it's going to take overly long getting the last few numbers as chances are much higher that the number is already in @RandNums and it'll have to look for another number. A better way would be to take the found number out of the pool of numbers to randomly shuffle. ie, <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> @ordered = ( 1 .. 10 ); push @random, splice( @ordered, int(rand @ordered), 1 ) while @ordered;</pre><HR></BLOCKQUOTE> Yeah, I know that's ugly as sin, but it works and is just to illustrate the idea. If you can't decipher that ... While there are elements in @ordered, int(rand @ordered) selects a random array index, which splice() then extracts (so the array shrinks!) and gives as an argument to push @random. [This message has been edited by Kanji (edited 10-04-2000).]
|