Michael Lam
asked on
how to find out if an array contains all true or all false or partially true
Just a general programming question, i am looking for the most elegant way to solve this. Ideally if it's partially true and partially false, I want to break out of the loop before the entire array is looped thru. Thanks.
All programing languages provide some way of breaking out of a loop before it finishes. Most often it's done with the keyword break;.
Example:
Example:
for (var i = 0; i < someArray.length; i++) {
if (someCondition) {
break; // exit the loop before it completes
}
// do something else when the condition if false
}
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Since the OP did ask for the most elegant solution, dare we go into Java 8?
boolean[] array ;
long same = IntStream.range(0, array.length-1).
filter(i -> array[i] == array[i+1]).
count();
System.out.println(same == array.length-1 ? "All " + array[0] : "Mixed") ;
>> dare we go into Java 8?
Well, looking at the author's history of Java questions, I didn't think so; but then again, looking further back, there are many C# questions, so maybe yes.
Well, looking at the author's history of Java questions, I didn't think so; but then again, looking further back, there are many C# questions, so maybe yes.
Open in new window