Eliminating if/switch statements by using jagged array

I mentioned the Jagged array in 16_th_cu2, but 17_th_cu2 is a prime example of why jagged arrays are useful. Check this out.

Jagged arrays are the same thing as 2-dimensional arrays in Java. Basically think of an array of arrays. A single array is a row of items, and a jagged array is like a grid of items.

I have 3 levels per password, and 5 passwords per level. I’m gonna store it in a 3x5 grid like this:

public class Hacker : MonoBehaviour
{
    int level;
    string[][] passwordList; // initiate a jagged array
    string currentPassword;
    enum Screen { MainMenu, Password, Win };
    Screen currentScreen;

    // Start is called before the first frame update
    void Start()
    {
          passwordList = new string[3][]; // specify how many rows I have in the jagged array
          // populate each row of jagged array with its own array of passwords
          passwordList[0] = new string[5] { "book", "clown", "level", "jump", "seven"};
          passwordList[1] = new string[5] { "desktop", "velvet", "cupboard", "notepad", "painting" };
          passwordList[2] = new string[5] { "refrigerator", "upstanding", "degeneracy", "quarantine","lumberjack" };
        ShowMainMenu();
    }
...

Now I just call passwordList to get anything out. I don’t need to use “switch” or “if” statments to sift through the arrays by checking the selected level. I just use the (level - 1) as the first index, and a random number generator as the second index:

        System.Random rnd = new System.Random();
        currentPassword = passwordList[level - 1][rnd.Next(0, 4)];

Privacy & Terms