Timesaving tricks

Here’s a couple of efficiency tricks that might be worth it if less code is more important than clarity in a particular context.

It’s possible to have an array with more than one dimension - think of it like a grid of values rather than a list. so I can have all of my possible passwords inside a single variable, then find them by first giving the index of the level that I’m using, then the password I want:

string[,] passwords = new string[3, 5] { {"chum", "pint", "football", "rain", "ascot" },
    { "vodka", "kremlin", "makarov", "caviar", "borscht"  },
    { "benghazi", "phosphorus", "predator", "washington", "obamacare" } };

You can also combine your index expression with the actual array addressing, and so eliminate the need for an extra variable:

currentPassword = passwords[level - 1, Random.Range(0, passwords.GetLength(1))];

Here, I’m using the number of the level minus one as the first index, then setting the second index by generating a random integer with the length of the array’s second dimension as the maximum value. The downside of this approach is that you can’t have different numbers of passwords in each level - since you set the length of the array at creation, all of them in the same dimension must contain the same number of elements.

2 Likes

Thanks for the tip. After watching this lesson I was wondering how to do that myself. Seems similar to how matlab does it

Privacy & Terms