victiMusPrime
victiMusPrime

Reputation: 53

How to check if all array values but one are the same?

I currently have the following array:

int[] gameState = {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2};

I set 2 as "unplayed" on start and when a user does something, it calls a method and changes that array value to 1 like this:

int tappedCounter = Integer.parseInt(counter.getTag().toString());

    if (gameState[tappedCounter] == 2) {

        gameState[tappedCounter] = 1;

Now what I want to do is check after the users action if the array has one and one only different member and do something (output a text for example).

So if the array is:

int[] gameState = {1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1};

And the user does the above so one of these changes to one and the array becomes like this:

int[] gameState = {1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};

It should display the output. I doing this in Android Studio if that's important.

Upvotes: 0

Views: 83

Answers (3)

Ian Mc
Ian Mc

Reputation: 5829

I would change your approach. It is preferable to detect a change up front, rather than try to determine after the fact if a state change occured.

Current code:

int tappedCounter = Integer.parseInt(counter.getTag().toString());
if (gameState[tappedCounter] == 2) {
    gameState[tappedCounter] = 1;

// Now you must check for state change and react if state has changed

New code:

int tappedCounter = Integer.parseInt(counter.getTag().toString());
setGameState(tappedCounter);

With the helper method setGameState:

public void setGameState(int stateVariable) {
    if (gameState[stateVariable] == 2) {
        // Do something based on stateVariable (show text, etc)
    }
    gameState[stateVariable] = 1;
}

Upvotes: 0

Kinshuk
Kinshuk

Reputation: 15

The simplest way I can think of is to keep a static counter, initialize it with a value equal to size of array, and decrement it every time the game state is changed. Once your static counter reaches 1, you can trigger the desired output.

Is there a reason this wouldn't work in your scenario?

Upvotes: 0

Eran
Eran

Reputation: 393811

A brute force approach would iterate over the entire array and count the occurrences of 2's (it can short circuit only if it finds a second 2).

A better approach (especially if the length of the array is large) would be to maintain a counter of 2's (initialized to the array's length), and decrement it each time an element of the array is changed from 2 to 1. This way all you have to do is check if the counter is equal to 1.

Upvotes: 1

Related Questions