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 #... }