Home > Mobile >  Finding repeating values in array
Finding repeating values in array

Time:11-13

I have an array with 4 integers and I need to find if there any repeating values and what are those repeating values. I have tried to use nested loops but it counts each integer in array twice:

for (int f = 0; f < bonusGame.length;   f) {
    for (int j = 0; j < bonusGame.length;   j) {
        if (f == j & f == 10) {
            System.out.println("You won 10 Euro");
        }
    }
}

CodePudding user response:

for (int i= array.lenght;i >0;i--){
      if (array[i]==array[i-1]){
         system.out.print("you won ")
}
 }

// i think it will work

CodePudding user response:

You should take a look at HashSet. This way you can create a O(n) algorithm, but you have to use Integer instead of int, which can be a problem in some case :

for (int num : bonusGame) {
     if (!hashSet.add(num) ) { // unauto-boxing
        // num is duplicate
     }

Or, you can call Arrays.sort(bonusGame) and compare the elements with only one loop :

Arrays.sort(bonusGame);
for(int i=0 ; i<bonusGame.length - 1; i  ) {
    if(bonusGame[i] == bonusGame[i 1]) {
         // bonusGame[i] is duplicate
    }
}

CodePudding user response:

something like this

for (int f = 0; f < bonusGame.length - 1;   f) {
    for (int j = f   1; j < bonusGame.length;   j) {
        if (bonusGame[f] == bonusGame[j]) {
            System.out.println("Duplicate "   bonusGame[f]);
        }
    }
}
  • Related