Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re^3: mem usage

by BrowserUk (Pope)
on May 26, 2010 at 19:17 UTC ( #841792=note: print w/replies, xml ) Need Help??


in reply to Re^2: mem usage
in thread mem usage

You can trim your shuffle a little by omitting the line:         next if $i==$j;.

Swapping an item with itself doesn't affect the algorithm's fairness, and doing it once costs less, than testing n times and avoiding it once.

And you save a little more by avoiding the list assignment:

my $tmp = $array[ $i ]; $array[ $i ] = $array[ $j ]; $array[ $j ] = $tmp;

Doesn't look as nice though.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

Replies are listed 'Best First'.
Re^4: mem usage
by ikegami (Pope) on May 26, 2010 at 19:46 UTC
    Including cleaning up the counter,
    sub shuffle { my $array = shift; my $i = @$array; while ($i) { my $j = int rand($i--); my $t = $array->[$i]; $array->[$i] = $array->[$j]; $array->[$j] = $t; } }
Re^4: mem usage
by halfcountplus (Hermit) on May 26, 2010 at 19:36 UTC
    You can trim your shuffle a little by omitting the line: next if $i==$j;

    Good point!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://841792]
help
Chatterbox?
[stevieb]: ffs... an hour I've been trying to get a Pi to communicate I2C to an Arduino. Had to slow down the communication channel. Sigh

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2017-06-22 22:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How many monitors do you use while coding?















    Results (531 votes). Check out past polls.