# How to check if all elements in an array are the same?

**URL:** https://discourse.processing.org/t/how-to-check-if-all-elements-in-an-array-are-the-same/32044
**Category:** Coding Questions
**Created:** [September 1, 2021, 5:02am UTC](https://discourse.processing.org/t/how-to-check-if-all-elements-in-an-array-are-the-same/32044 "2021-09-01T05:02:32Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![lucaswoah](https://avatars.discourse-cdn.com/v4/letter/l/b38774/32.png) [@lucaswoah](https://discourse.processing.org/u/lucaswoah)
#### Post date: [September 1, 2021, 5:02am UTC](https://discourse.processing.org/t/how-to-check-if-all-elements-in-an-array-are-the-same/32044/1 "2021-09-01T05:02:32Z")

</div>

I made this game for my exam where I have this two dimensional (int [] [] M = new int [30][30]) array that has 3 possible values: 0 (black tile), 1 (white tile) and 2 (fruits). The player can click with the left mouse button to create walls and then press Enter to start playing.

What I want is to display a game over message with a black background once all fruits are eaten. I can’t get this to work, though.

I think I could do it if I could check if all elements on M are different than 2, but I haven’t been able to do that right. Does anybody have any idea how to do this?

---

<div class="post-metadata">

### Author: ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)
#### Post date: [September 1, 2021, 5:31am UTC](https://discourse.processing.org/t/how-to-check-if-all-elements-in-an-array-are-the-same/32044/2 "2021-09-01T05:31:05Z")

</div>

> [@lucaswoah](#):
>
> What I want is to display a game over message with a black background once all fruits are eaten.

Given the value `2` means fruit we just need to check for its presence within your 2D array.

If we don’t find that value it means all fruits have been eaten.

The function below returns `true` if a 2D array **contains()** a specified value otherwise `false`:

```auto
static final boolean contains(final int val, final int[][] arr2d) {
  for (final int[] arr1d : arr2d) for (final int v : arr1d)
    if (v == val) return true;
  return false;
}

```

Invoke it passing the value `2` as 1st argument and your _M_ 2D array as 2nd argument.

Then if it returns `false` you know all fruits are gone and you can display your game over message.

---

<div class="post-metadata">

### Author: ![lucaswoah](https://avatars.discourse-cdn.com/v4/letter/l/b38774/32.png) [@lucaswoah](https://discourse.processing.org/u/lucaswoah)
#### Post date: [September 1, 2021, 5:59am UTC](https://discourse.processing.org/t/how-to-check-if-all-elements-in-an-array-are-the-same/32044/3 "2021-09-01T05:59:50Z")

</div>

This worked, thank you so much!!
