Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Distribute and assign items from one list to another

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading