I have a simple strategy game I've been writing in perl, and although 90% of the execution time is spent doing disk I/O after the processing is done, there are some things that I feel could be done better.

One thing that is bugging me is the way I'm rolling for initiative in combat.

Currently:

Each ship gets a number of ballots equal to their initiative value, which are randomly mixed into an array. Ships then act the first time one of their ballots is seen. The rest of the ship's ballots are wasted space and time.

While this algorithm is more than fast enough, and does the job, there is surely a better way.

A snippet from the combat routine:
foreach my $ship (@shipsInCombat) { # Add ship to initiative hash push @shipsToAct, (($ship) x ($ship->{thruster}*2+1)); } shuffle(\@shipsToAct); SHIP: foreach my $ship (@shipsToAct) { next SHIP if exists($shipsAlreadyDone{$ship}); $shipsAlreadyDone{$ship} = "yes"; #... #Simulated mayhem #... }
Note: strict and warnings are on, and the variables are declared. This is just a snippet of the node's focus.
Note2: Shuffle() is a simple loop in which each element is swapped with a random element.

As far as the question part of this node:
What would you suggest as a better algorithm for rolling initiative in this situation?

In reply to 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.