Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: A script with a loop is running my computer Out of memory

by JavaFan (Canon)
on Feb 02, 2011 at 23:40 UTC ( [id://885872]=note: print w/replies, xml ) Need Help??


in reply to A script with a loop is running my computer Out of memory

Your problem is that for each generation, you create an array that for each child, holds the number of children it gets in the next generation.

There's no need for that. Far easier is:

my $people = ...; # First generation. my $generations = ...; for (2 .. $generations) { $people += int rand 6 for 1 .. $people; }
It can be made faster (by using a formula to calculate the number of children in each generation without the inner loop), but the above is simple, and most of all, won't run out of memory (assuming there's a few Mb available to start perl).

Replies are listed 'Best First'.
Re^2: A script with a loop is running my computer Out of memory
by Lady_Aleena (Priest) on Feb 13, 2011 at 18:49 UTC

    Thanks for that tip, JavaFan. I used it, and you are so right. It is much faster and my memory doesn't run out! Unfortunately, I did come against another error "Range iterator outside integer range". I haven't quite got that figured just yet.

    I didn't use your exact fragment, but I think it is close enough.

    #!/usr/bin/perl -l use strict; use warnings; use feature qw(say); use List::Util qw(sum max); use lib 'lib'; use Base::Nifty qw(commify); say "How many children are in the first generation?"; my $generation = <>; say "How many generations do you want to generate?"; my $generations = <>; chomp($generation,$generations); my %generations = ( 1 => $generation, ); my @distribution = (0,0,0,1,1,1,2,2,2,3,3,4,5,6); for my $gen (1..$generations) { my $children = 0; for (1..$generation) { $children += $distribution[rand(@distribution)]; } $generation = $children; last if ($children == 0); $generations{$gen + 1} = $generation; } my $max_length_generation = length(commify(max(keys %generations))); my $max_length_children = length(commify(max(values %generations))); for (sort {$a <=> $b} keys %generations) { printf "%${max_length_generation}s: %${max_length_children}s\n",$_,c +ommify($generations{$_}); }

    The += did a whole lot of good! I haven't used that construction much in the past, so I don't automatically think of it. Hopefully one day it will sink in.

    Have a cookie and a very nice day!
    Lady Aleena

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://885872]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2024-03-28 13:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found