1

Let's say I have a php array that could be all 1s, all 2s or all 1s and 2s. For example I could have array(1, 1, 1, 1, 1, 1), or array(2, 2, 2, 2, 2, 2) or array(2, 2, 1, 1, 2, 1).

How do I check if my array actually is an array of all 1s, all 2s or if my array actually contains both 1s and 2s?

4
  • Why did you tag your question with three unrelated languages? And which one does your inquiry pertain to? Commented Oct 13, 2011 at 2:23
  • You have this tagged for 3 different languages? Commented Oct 13, 2011 at 2:23
  • Sorry, this is a php question. See edit Commented Oct 13, 2011 at 2:30
  • @user765368: Please select one of the answers or leave a comment why this is not solved. Thanks. Commented Oct 18, 2011 at 1:46

10 Answers 10

5

In case you wanted to know for PHP, you can use array_unique() to probe which distinct values exist:

 if (count(array_unique($array)) == 1) {
     // It's either full of 1s or 0s.
     // Then just probe the first entry.
 }
Sign up to request clarification or add additional context in comments.

Comments

2

You could add all the values in the array together. If they equal the length of the array or they equal 0 they are all 1s or all 0s.

2 Comments

The array values are not necessarily 0s and 1s. It could be 12s and 74s for examples. The point is I wanna check if my array actually contains 2 different values or not (see edit)
You can extend my answer by taking the sum and dividing it by the first number in the array. If it equals the length of the array it is all the same. The zero scenario does not change.
1

The simplest way is to just count the number of ones and zeroes. For example (in python):

ones = zeroes = 0;
for i in range(len(my_array)):
    if my_array[i] == 1: ones = ones + 1
    else zeroes = zeroes + 1

You can also multiply each element together (1 if all ones) and add each element in the array (0 if all elements are zero)

Comments

1

In Java ...

public static void allTheSame(int[] array) {
  for (int i = 1; i < array.length; i++) {
    if (array[i] != array[i - 1]) {
       return false;
    }
  }
  return true;
}

This algorithm can be transcribed into the other listed languages, though their may be neater ways to do it in some. (But watch out for the efficiency of the neat solutions ... if that matters to your application.)

Note that this approach will deliver a false result faster than any neat solution that involves collating or summing the array elements, and it makes no assumption about what the element values are.


Note: this answer was written when the tagging indicated that the OP wanted solutions in Java, Javascript and PHP. Check the Question's edit history ...

Comments

0

You can do it with a simple if-statement. Here's some JavaScript:

if (myArray.indexOf(1) > -1) {
  // there are 1s, are there 0s?
  if (myArray.indexOf(0) > -1) {
    console.log("1s and 0!");
  } else {
    console.log("Only 1s.");
  }
} else {
  console.log("Only 0s.");
}

Working example: http://jsfiddle.net/daNEH/

Comments

0

Try this code:

    int[] intArray = new int[5];

    boolean hasZero, hasOne, hasBoth;

    for(int integer : intArray)
    {
        switch(integer)
        {
        case 0:
            hasZero = true;
            break;
        case 1:
            hasOne = true;
            break;
        }
    }

    hasBoth = hasZero && hasOne;

Comments

0
function allElementsEqual(array){
    var start = array[0],
        same = true;
    for(i = 1;i < array.length;i++){
       same &= (start === array[1]);
    }
    return same;
}

This function should do the job fine http://jsfiddle.net/WNxg4/

Comments

0

Another way would be to use array_diff, provided you only had two different numbers. Just compare the haystack of numbers to an array with a single number (pick one of the ones in the haystacks).

For example:

$haystack_mixed = array(2,2,2,1,1);
$haystack_1 = array(1,1,1,1);
$haystack_2 = array(2,2,2,2);

print_r(array_diff($haystack_mixed, array(1))); 
// The result is not the same as the $haystack since there are 1's in it.
// Array ( [0] => 2 [1] => 2 [2] => 2 )

print_r(array_diff($haystack_1, array(1)));
// This one is made up of all 1's
// Array ( )

print_r(array_diff($haystack_2, array(1))); 
// This one is made up of all 2's (same length as $haystack_2)
// Array ( [0] => 2 [1] => 2 [2] => 2 [3] => 2 )

So you can test the length of the resulting array.

Comments

0

I think you could use the array_sum or array_filter functions for this.

Comments

0

I have read the 9 answers and they're all pretty fancy, I think just go with the simplest way.

is_mixed($array){
    $count = count($array);
    //we go trough every element in the array
    for($i=1;$i<$count;$i++){
        //if the element n is distinct from the n-1
        //then return true (is_mixed)
        if ($array[$i] != $array[$i-1]) return true;
    }
    //if it didn't return anything yet, it means
    //all the elements are the same. Then, just
    //return the first one, as they're all the same
    // (either 1 or 2)
    return $array[0];
}

this second one I actually like the most:

function what_they_are($array){
    $total = array_sum($array);
    $count = count($array);

    if ($total == 0) {
        return "they're all 0";
    }else if ($total/$count == 2){
        return "they're all 2";
    }else if ($total == $count){
        return "they're all 1";
    }else{
        return "they're mixed";
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.