This is an interesting one. I added the following PlayMode test to Hacker.cs to show that the code works as is:
[UnityTest]
public IEnumerator TestRandomRangeArrayNotOutOfBounds() {
int numIterations = 1000;
Debug.Log("Level 1 Passwords Length:" + level1Passwords.Length);
Debug.Log("Test runs: " + numIterations);
int[] results = {0, 0, 0, 0, 0, 0, 0};
for (int i = 0; i < numIterations; i++) {
int randResult = Random.Range(0, level1Passwords.Length);
Assert.AreNotEqual(randResult, level1Passwords.Length);
results[randResult]++;
}
Debug.Log("Results: " + String.Join(",", results.Select(x => x.ToString()).ToArray()));
yield return null;
}
Which returns as follows in the TestRunner:
TestRandomRangeArrayNotOutOfBounds (0.045s)
Level 1 Passwords Length:6
Test runs: 1000
Results: 179,168,178,168,139,168,0
So you can see that 6 is never returned from Random.Range(0, level1Passwords.Length)
even though the Length is 6.
Now I thought this was curious, as the API docs state that the min and max of Random.Range are inclusive, so the result should be 0…6.
Returns a random float number between and min [inclusive] and max [inclusive] (Read Only).
HOWEVER ![:slight_smile: :slight_smile:](https://sjc3.discourse-cdn.com/business5/images/emoji/twitter/slight_smile.png?v=5)
If you scroll further down the page, you can see that Random.Range is overloaded for ints, and when you use ints instead of floats, the max is exclusive:
Returns a random integer number between min [inclusive] and max [exclusive] (Read Only).
Mystery solved ![:slight_smile: :slight_smile:](https://sjc3.discourse-cdn.com/business5/images/emoji/twitter/slight_smile.png?v=5)