Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If all elements in bool array are true?

Tags:

arrays

c#

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))?

like image 400
EnglischerZauberer Avatar asked Dec 11 '15 00:12

EnglischerZauberer


People also ask

How do you check if all values in a boolean array are 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 .

Are boolean arrays automatically 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.

How do you check if every element in an array is false?

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 .

How do I check if all elements in an array are true in Python?

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.


1 Answers

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);
}
like image 79
Willem Van Onsem Avatar answered Oct 01 '22 12:10

Willem Van Onsem