1

Say i've got an array:

int[] numbersArray = new int[]{10, 20, 20, 10, 10, 30, 50, 10, 20};

I'd like to return the count of pair of the numbers that are the same and remove them from my array.

Result of the method when numbersArray is passed should be 3. I'm stuck with my solution.

n - the number of elements in array

ar - given int[] array

public static int myMethod(int n, int[] ar) {
    int pairs=0;
    List<Integer> myList = new ArrayList<>();
    for(int i : ar) {
        myList.add(i);
        System.out.println(i);
    }

    for(int i=0; i<n-1; i++) {
        for(int j=i+1; j<n-2; j++) {
            if (myList.get(i) == myList.get(j)) {
                pairs++;
                System.out.println(pairs);
                myList.remove(i);
                myList.remove(j);

            }
        }
    }

    return pairs;
}

edit:

im getting IndexOutOfBoundsException even though I deducted 1 while looping + the problem seems to be occuring when I'm trying to remove j element (the one that matches i). I'd like to remove both of them from my array which should increase my pairs variable by 1.

Andrew Tobilko
  • 44,067
  • 12
  • 74
  • 128
bengal
  • 39
  • 5
  • And what is wrong with your attempt? Wrong output? Compile error? Runtime error? – achAmháin Oct 09 '18 at 12:45
  • I've got an error that says: index out of bounds exception at line: myList.remove(j); – bengal Oct 09 '18 at 12:46
  • "stuck with your solution" ... so it is in fact a solution? – Stultuske Oct 09 '18 at 12:47
  • @bengal you have to be careful with lists when removing. you probably remove some elements and so the list gets shorter. So at a later point the index where you want to remove the element is out of bounds – elPolloLoco Oct 09 '18 at 12:50
  • The error is due to you checking for the initial length of your list, while shortening it on the go. – IcedLance Oct 09 '18 at 12:51
  • how can i fix my code so this actually works ? – bengal Oct 09 '18 at 12:53
  • Add the duplicate check to the very first pass of `ar[]`: `if(myList.contains(i)){myList.remove(myList.indexOf(i));pairs++;}else{myList.add(i);}` – IcedLance Oct 09 '18 at 12:57
  • still not sure what you are trying to achieve. why would the output be 3? – elPolloLoco Oct 09 '18 at 12:57
  • @elPolloLoco element at index 0 is 10, element at index 3 is also 10. I want to remove both elements and increase count by 1 etc. – bengal Oct 09 '18 at 12:59
  • So do you want to increase the count each time you find a duplicate, or eacht time you have a double element? (count = 2 because 10 and 20 have duplicates, or count = 5 because 10 has 3 and 20 has 2 duplicates?) – elPolloLoco Oct 09 '18 at 13:07
  • wait, you want to remove both? so if an element has an odd number of occurences it will be in the resulting array and if it has an even number of occurences it will not? – elPolloLoco Oct 09 '18 at 13:25

0 Answers0