LostPuppy
LostPuppy

Reputation: 55

Is it possible to check this way, that all elements in 2d Array are the same?

So I googled this question. And only this link from StackOF came up. The question is ~4 years old.

I find my solution to be rather simple, but nobody wrote about it, does it make sense?

Here's the code:

public boolean areAllTheSame(int[][] image) {

    // Create a new set, so we can store our unique elems there.
    Set<Integer> set = new HashSet<>();

    //Iterate through all elements, add to our HashSet set
    for (int[] ints : image) {
        for (int anInt : ints) {
            set.add(anInt);
        }
    }
    // Because set has only unique elements, if all are the same => size should be 1

    return set.size() == 1;
} // end of areAllTheSame

Upvotes: 1

Views: 1144

Answers (3)

ljleb
ljleb

Reputation: 312

How about:

public boolean areAllTheSame(int[][] image) {
  // assuming `image` >= 1x1 pixels

  int expectedPixel = image[0][0];

  for (int[] pixels: image)
    for (int pixel: pixels)
      if(pixel != expectedPixel)
        return false;

  return true;
}

It stops looping as soon as it knows the array is not uniform, and it doesn't require the allocation of a HashSet<Integer>.

Upvotes: 1

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59960

I think there are more ways, one of them, by using java streaming :

public boolean areAllTheSame(int[][] image) {
    return Arrays.stream(image)
            .flatMapToInt(Arrays::stream)
            .distinct()
            .count() == 1;
}

Upvotes: 1

Merthan Erdem
Merthan Erdem

Reputation: 6058

Seems very inefficient, if you want to check if a multidimensional array only contains one element you can just take the first element and then compare it to all other numbers, if a single one doesn't match you return false

Upvotes: 0

Related Questions