in reply to Re^2: Rolling For Initiative
in thread Rolling For Initiative
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 #... }
|
|---|