Check if an array has at least two elements with a specific value
Suppose I have an array with the following values: 0,1,0,0,0,1,0,1,1
I am now iterating over my array and replacing 1 with 0. However, I would get out of this loop if there are 2 1 left in my array. Actually, I am not very good at code, but this is the fact that I was 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 distinguish between 0 and 1, and so I am completely confused on how to get this to work. Any ideas would be appreciated.
source to share
One possible solution is to start by writing a utility method to check if a given value at a particular position is unique from each subsequent position in the array, for example
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 over the array from left to right, checking if each value is unique, for example
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));
}
This is false
. Also, it may be easier for you if you sort your array first.
source to share
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 Lukas, try this, Sorry if I didn't understand your requirement properly.
source to share