The fact that you needed to visit each element once is why I think your shuffle-and-shift approach is best, as opposed to the integrated thrust approach which has come up a couple times in this thread. The shuffle out of List:Util will scale the same as your implementation, but will likely have a lower constant and use less memory since it uses map in place of a for loop. I've also gotten admonished on using C-style for loops - maybe swap to for my $i (0 .. $#$arrayref) to reduce the bug risk.

If you do dig the the idea of picking weighted ships in place of the shuffle approach, you can swap it to O(n) (or actually O(n*m^2), where m is # of bins) by sorting and caching bounds, so you don't have to count up each ship. Maybe something like this:

my %shipToActBins = (); foreach my $ship (@shipsInCombat) { # Add ship to initiative hash if (not exists $shipToActBins{$ship->{thruster}}) { $shipToActBins{$ship->{thruster}} = []; } push @{$shipToActBins{$ship->{thruster}}}, $ship; } my %weights = (); for (keys %shipToActBins) { $weights{$_} = 2 * $_ + 1; } SHIP: for (0 .. $#shipsInCombat) { my $ship; my $sum = 0; my @bounds = (); for (sort keys %shipToActBins) { if (@{$shipToActBins{$_}} == 0) { delete ($shipToActBins{$_}); } else { $sum += $weights{$_}*@{$shipToActBins{$_}}; push @bounds, $sum; } } my $roll = int(rand($sum)); CHOOSE: for (sort keys %shipToActBins) { if ($bounds[0] >= $roll) { $roll = int(($bounds[0] - $roll - 1)/$weights{$_}); $ship = splice(@{$shipToActBins{$_}},$roll,1); last CHOOSE; } else { shift @bounds; } } #... #Simulated mayhem #... }

In reply to Re^3: Rolling For Initiative by kennethk
in thread Rolling For Initiative by SuicideJunkie

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.