Code Optimization-- Can I do this better? 
Author Message
 Code Optimization-- Can I do this better?


Quote:

># Random Number Generator Engine
>sub rndengine{
>  srand(time|$$);
>  $i = int(rand($limit));
>  $i;
>}

You should never, ever, ever call `srand' more than once in your
entire program.  If you call it every time you generate a number, as
you do here, you substantially reduce the amound of randomness in the
generator.  Also, the global variable $i is superfluous here.  Do it
like this:

        sub rndengine { int rand $limit }

That said, I might write the generator like this:

# generate(n): generate n distinct random numbers and return list of them
sub generate {
  my $n = shift;
  my %r;
  while (keys %r < $n) {
    $r{randengine()} = 1;
  }
  keys %r;

Quote:
}

Now `generate(3)' returns a list of three distinct random numbers.
The principle at work here it Tom's Pavlovian Conditioning Rule:
``When you hear the word `unique', say `hash'. ''

Of course, your random numbers are between 0 and 3, so the fastest and
easiest way to generate three of them is by simply choosing which of
the four possibilities you're going to *omit*, like this:

sub generate {



Quote:
}



Thu, 08 Feb 2001 03:00:00 GMT  
 
 [ 1 post ] 

 Relevant Pages 

1. Code Optimization-- Can I do this better?

2. Optimization of Perl code

3. code optimization and readability

4. Optimization of the code - suggestions?

5. Code optimization request and i18n issues

6. Code optimization: Anyone got a few spare minutes?

7. Optimization of date calculation code

8. good code vs code that works

9. optimization help

10. Optimization help...

11. Large Project optimization

12. Question about regular expression optimization

 

 
Powered by phpBB® Forum Software