Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get true if all the array elements in the same position are true

I'm working with n boolean arrays like the following ones:

A  = [1, 1, 0, 1]
A1 = [0, 1, 0, 1]
A2 = [0, 1, 0, 0]

B  = [1, 1, 0, 1]
B1 = [0, 0, 0, 1]
B2 = [0, 1, 0, 0]

I'm working on a function that return true if exists at least one column of 1 (e.g. in the three A arrays I'll got true because A[1] = A1[1] = A2[1] = true) In the B arrays I'll get false instead.

I know that I can make a result boolean array and obtain the output with loops but I'm asking if there is a more elegant way to obtain this result without using too many loops.

like image 326
Rowandish Avatar asked Dec 18 '22 20:12

Rowandish


1 Answers

Something like this would do the trick:

bool[] A = ...;
bool[] A1 = ...;
bool[] A2 = ...;

var length = Math.Min(Math.Min(A.Length, A1.Length), A2.Length);
var result = Enumerable.Range(0, length).Any(i => A[i] && A1[i] && A2[i]);

You can skip the length calculation if you know in advance what the length is, that will take a line off.

like image 189
Maarten Avatar answered May 18 '23 12:05

Maarten