develooper Front page | perl.beginners | Postings from April 2002

Re: Scripts picks random elements from array , but it repeats som etimes

From:
drieux
Date:
April 29, 2002 19:14
Subject:
Re: Scripts picks random elements from array , but it repeats som etimes
Message ID:
F8092B60-5BDF-11D6-8162-0030654D3CAE@wetware.com

On Monday, April 29, 2002, at 02:34 , Nikola Janceski wrote:

> what about?
>
>  my @numbers = 1..100;
>  while($#numbers >= 0) {
>       my $index = rand $numofques;
>       my $element = $numbers[$index];
>       $numbers[$index] = pop @numbers; # replace the number we used with 
> the
> last element and shrink array
>       printf "%-3d ", $element;
>   }
>   printf "\n"
>
> Wouldn't this run faster?

i found a few defects in it, and replaced them

sub nikolaPopper {
	my @retarray =();
	my @numbers = @array;
  	while($#numbers >= 0) {
       my $index = rand $#numbers;
    	  push(@retarray, $numbers[$index]);
	  # otherwise we never close the while loop....
       if ($#numbers > 0 ) {
       	$numbers[$index] = pop @numbers; # replace the number we used with 
the
       								# last element and shrink array
       } else {
       	my $junk = pop @numbers;
       }
   	}
     @retarray;

} # end of nikolaPopper


the ballscores look like:

perl ran*
running with array size 2500
Benchmark: timing 500 iterations of consume, decLoop, nikolaPopper, 
seenArray...
    consume: 14 wallclock secs (14.32 usr +  0.00 sys = 14.32 CPU) @ 34.92/
s (n=500)
    decLoop: 16 wallclock secs (14.55 usr +  0.00 sys = 14.55 CPU) @ 34.36/
s (n=500)
nikolaPopper: 17 wallclock secs (17.40 usr +  0.00 sys = 17.40 CPU) @ 
28.74/s (n=500)

^C
[jeeves:~/perl/benchmark] drieux% !!
perl ran*
running with array size 250000
Benchmark: timing 50 iterations of consume, decLoop, nikolaPopper, 
seenArray...
    consume: 3196 wallclock secs (3149.69 usr +  0.00 sys = 3149.69 CPU) @ 
  0.02/s (n=50)
    decLoop: 180 wallclock secs (179.24 usr +  0.00 sys = 179.24 CPU) @  0.
28/s (n=50)
nikolaPopper: 229 wallclock secs (226.87 usr +  0.00 sys = 226.87 CPU) @  
0.22/s (n=50)




ciao
drieux

---




nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About