Thank you for the idea of distribution, I toyed with the idea while writing it, but thought int(rand(6)) was easier. You are right though, it should be weighted towards fewer children per person of the previous generation. However, I found a situation where I have had to stop the loop. In the first few iterations of the main loop, a generation could end up with 0 children in it. At that point, going any further would be pointless. So while I could still push the generation with 0 children to an array instead of adding another key to the hash, max(keys %generations) != $generations. I am still working the array versus hash idea, I still have to figure out everything I would have to change. I am just more comfortable dealing with hashes than arrays. Meanwhile, here is the updated script.
#!/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 (1..$generations) {
my @generation;
for (1..$generation) {
my $children = $distribution[rand(@distribution)];
push @generation, $children;
}
$generation = sum(@generation);
last if sum(@generation == 0);
$generations{$_ + 1} = $generation;
@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{$_});
}
Have a cookie and a very nice day!
Lady Aleena
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.