Your question doesn't go into much detail about the requirements about how agility influences your attack order, but I assume that you meant one of these two:
- If one unit has higher agility than another, it always attacks first.
- If one unit has higher agility than another, it usually attacks first.
If the first of these is true (units with higher agility always attack first), then what you're looking for is a way of permuting the array subject to the restriction that units with higher agility always end up before units of lower agility, but with everything else done randomly. One way to do this is as follows:
- If you have N units, assign the numbers 1 ... N to the units at random. Don't assign the same number twice.
- Sort the units into ascending order as follows:
- Any unit with higher agility than another unit comes first.
- Of two untis that are tied, whichever has the higher random number comes first.
You can show that this approach will arrange the units so that all units of a certain agility are randomly permuted relative to one another, but always come before lower-agility units. This takes time O(n log n) and can be done using
Collections.shuffle, and an appropriate
If, on the other hand, you want the ordering to be random but influenced by the agility, you may want to think about using some sort of random distribution that can be controlled by some parameter. For example, you might assign each unit a priority drawn from a normal distribution whose mean is the agility and whose standard deviation is some reasonably large number (say, 20). This would mean that units with more agility are more likely to move before units with less agility, though there is a large amount of randomness. The advantage of this approach is that by tweaking the underlying distribution and its parameters (mean and variance in the case of a normal distribution), you can fine-tune to what extent the agility measure factors in.
As an example of a very simple approach, you might model unit speed as
priority = e(agility / 100) + random(1, 2)
Here, the more agility you have, the greater that your priority is. Increasing the amount of randomness changes the extent to which agility matters. Of course, this might be a bit skewed because each marginal increase in agility has more meaning, so you may want to replace the exponential with something like a logistic function.
Hope this helps!