I have a list of Attackers
and Targets
. I want each attacker to target at least 1 target.
If there are 4 Attackers and 4 Targets, then Attacker[0]
would attack Target[0]
and so on...
However if there are more attackers than the targets. For example
Attackers Targets
Attacker[0] Target[0]
Attacker[1] Target[1]
Attacker[2]
Attacker[0] would attack Target[0], Attacker[1] would attack Target[1]. How would I make it that Attacker[2] would attack Target[0] again? Like it would just go back at the top of the list and iterate again for the remaining Attackers?
CodePudding user response:
This is a great use of modulus division. Take this psudo code:
target_index = attacker_index mod total_targets
Putting it into code
var totalTargets = 4; // get from your list length
var attackerIndex = 0; // get from some for loop
var targetIndex = attackerIndex % totalTargets;
Putting this into a loop gives you:
Attacker 0 attacks 0
Attacker 1 attacks 1
Attacker 2 attacks 0
Attacker 3 attacks 1
Attacker 4 attacks 0
Attacker 5 attacks 1
Attacker 6 attacks 0
Say you had 3 total targets instead. Change out totalTargets
and you'd get:
Attacker 0 attacks 0
Attacker 1 attacks 1
Attacker 2 attacks 2
Attacker 3 attacks 0
Attacker 4 attacks 1
Attacker 5 attacks 2
Attacker 6 attacks 0