I offer one last solution, which addresses an issue raised in
Re: Functional perl please: "(we exclude "solutions" which must store the entire sequence in a large array and the like)". My previous solutions did store the array, because they returned it as one piece.
This sub is an iterator, returning the next in the sequence on each call. It maintains only the portion of the output stream that it needs to continue generating.
I used Math::BigInt so I could get into interesting numbers. It takes several minutes to find the 100000th or so in the series. But if you're interested, #100001 through 100005 are
290237644800000000000000000000000000000
290420756304773155911401472000000000000
290469810882260083566182400000000000000
290565366750000000000000000000000000000
290748685015200298451950845000000000000
with 5446 elements in the queue.
use strict;
use warnings;
use Math::BigInt;
{
my @history = (Math::BigInt->new('1'));
my @streams = map {base => $_, index => 0}, (2, 3, 5);
sub print_status {
print "$_->{base}: $_->{index}\n" for @streams;
print "History is " . @history . " elements\n";
}
sub ham_iter {
# Make sure all stream indexes are > 0
while ($streams[2]{index} == 0) {
# Find the next lowest value to push onto history
my @peeks = map {
$history[$_->{index}]->copy()->bmul($_->{base})
} @streams;
my ($lowest) = sort {$a->bcmp($b)} @peeks;
$peeks[$_]->bcmp($lowest) or $streams[$_]{index}++ for 0..
+$#streams;
push(@history, $lowest);
}
# Now adjust all the indexes for the element being removed
$_->{index}-- for @streams;
shift @history;
}
}
# Skipping however many
ham_iter() for (1..10);
# Then print the next five
print ham_iter->bstr(), "\n" for (1..5);
# Then tell us about what's stored
print_status();
Caution: Contents may have been coded under pressure.
-
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.