Link to home
Start Free TrialLog in
Avatar of Michael Lam
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.
Avatar of dpearson
dpearson

Here's one way:

boolean first = array[0] ;

for (int i = 1 ; i < array.length) {
   if (array[i] != first)
      throw new Exception("Mixed") ;
}

// By here all elements must match first (true or false)
return first ;

Open in new window

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:
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
}

Open in new window

SOLUTION
Avatar of awking00
awking00
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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") ;

Open in new window

>> 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.