I'm having difficulty using the array.All<>
function.
private bool noBricksLeft() {
bool[] dead = new bool[brick.Length];
for (int i = 0; i < brick.GetLength(0); i++) {
if (brickLocation[i, 2] == 0)
dead[i] = true;
else
continue; // move onto the next brick
}
if (dead.All(dead[] == true)) // IF ALL OF THE ELEMENTS ARE TRUE
return true;
else
return false;
}
I'm wondering how I can achieve if (dead.All(dead[] == true))
?
To check if all values in an array are truthy, use the every() method to iterate over the array and return each value straight away. If all values in the array are truthy, the every method will return true , otherwise it returns false .
The boolean array can be used to store boolean datatype values only and the default value of the boolean array is false. An array of booleans are initialized to false and arrays of reference types are initialized to null.
To check if all values in an array are falsy, use the every() method to iterate over the array, convert each value to boolean, negate it, and return the result. If all values in the array are falsy, the every method will return true .
Python all() Function The all() function returns True if all items in an iterable are true, otherwise it returns False. If the iterable object is empty, the all() function also returns True.
You can simply use a lambda-expression:
if (dead.All(x => x))
Given you using System.Linq
's IEnumerable<T>.All
method.
will do the trick. Furthermore an if
statement that returns the answer is useless, so you can rewrite it to:
private bool noBricksLeft() {
bool[] dead = new bool[brick.Length];
for (int i = 0; i < brick.GetLength(0); i++) {
if (brickLocation[i, 2] == 0)
dead[i] = true;
else
continue; //move onto the next brick
}
return dead.All(x => x);
}
Another idea, partly borrowed from @royhowie is the following:
private bool noBricksLeft() {
return Enumerable.Range(0,brick.Length).All(i => brickLocation[i,2] == 0);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With