Lukasz Medza
Lukasz Medza

Reputation: 499

Check if array has at least two elements with specific value

Assume that I have an array with the following values: 0,1,0,0,0,1,0,1,1

I am currently looping over my array and replacing 1's with 0's. However I would to break out of this loop if there are 2 1's left in my array. I don't really have much in terms of code but this is a stub of what I've been working on

if(//There are more than 2 1s ){
        return true; //carry on looping
    }

    return false; //break the loop

I have no idea how to differentiate between the 0's and the 1's and so I am quite confused with how to get this to work. Any ideas would be appreciated.

Upvotes: 3

Views: 2321

Answers (2)

mady
mady

Reputation: 119

public int[] testDuplicatesofOne(int[] arr)
{
    int count=0;
    for(int i=0;i<arr.length-1;i++)
    {
        count+=(arr[i]>0?1:0);
    }

    if(count>=2)
    {
    for(int j=0;j<arr.length-1;j++)
    {
        if(count>2) 
        {
            if(arr[j]==1)
            {
                arr[j]=0;
                count--;
            }
        }else
        {
            break;
        }

    }
    }
}

Hi Lukasz try this, Sorry if I have not understood your requirement properly.

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201437

One possible solution is to start by writing a utility method to test if a given value at a specific position is unique from every subsequent position in the array like,

private static boolean testUnique(int[] arr, int i) {
    int t = arr[i];
    for (int j = i + 1; j < arr.length; j++) {
        if (arr[j] == t) {
            return false;
        }
    }
    return true;
}

Then you can iterate the array from the left to the right, checking if every value is unique like

public static boolean hasDuplicate(int[] arr) {
    for (int i = 0; i < arr.length - 1; i++) {
        if (!testUnique(arr, i)) {
            return false;
        }
    }
    return true;
}

Using your array,

public static void main(String[] args) {
    int[] arr = { 0, 1, 0, 0, 0, 1, 0, 1, 1 };
    System.out.println(hasDuplicate(arr));
}

That is false. Alternatively, you might find it easier if you first sort your array.

Upvotes: 1

Related Questions