The algorithm in the picture describes how to pick a region without picking same region multiple times. It achieves that using:
- region array containing all possible regions
- integer variable keeping track of number of unpicked regions
- region variable which holds the randomly selected region
The algorithm can be described as:
- Let variable maxIndex represent the number of unpicked regions. At the start of the game maxIndex will be equal to number of regions in regions array
- Let num be random number between 1 and maxIndex
- Set region variable reg to region at num position in the regions array (i.e. regions[num])
- reg is your randomly picked region
To prevent same region from being picked again, the algorithm takes the following steps:
- switch position of region at num position with region at maxIndex position (=last unpicked region) in the regions array.
- decrease maxIndex by one, since you have one less region that was not yet picked
As an example, if you had 20 unpicked regions, then
maxIndex would be 20. If the random number
num was 6, then your randomly picked region would be region[6], which would be for example "Forest Area 1" region.
Now you swap region[6] with whatever is at region[maxIndex] = region[20]. Let's say that is region "Lake Area 3".
Finally, you decrease the
maxIndex by one.
So you got from:
JASS:
maxIndex = 20
region[6] = "Forest Area 1"
region[20] = "Lake Area 3"
to
JASS:
maxIndex = 19
region[6] = "Lake Area 3"
region[20] = "Forest Area 1"
Because maxIndex is now 19, then the next time the trigger is executed, it will pick random number between 1 and 19, not 20. Because the random number won't ever be 20, it will never pick "Forest Area 1" again.
On the other hand, if the random number was 6 again, then neither that would be a problem, because previously region[6] was "Forest Area 1", but now region[6] is "Lake Area 3"