0

I'm just a beginner and I'm trying to write a method returning only unique elements from Java array. What's wrong with this code? Could you please point my mistakes and help me correct them? I've got no idea what to do with it.

P.S. I know I could use packages, but it has to be done in the simplest way.

public static void main(String[] args) {

    int[] arr = {1, 1, 2, 3};
    int[] items = returnNonRepeated(arr);
    System.out.print(items);


}

public static int[] returnNonRepeated(int[] arr) {

    int[] temp = new int[0];
    int n = 0;
    for (int i = 0; i < arr.length; i++) {
        if (i == 0) {
            temp[i] = arr[i];
        } else {
            if (arr[i] != arr[i - 1]) {
                temp[numbersCount] = arr[i];
                numbersCount++;
            }
        }
    }

    return temp;



}

}

Victor
  • 1
  • 2
  • 1
    Is your array sorted? Are you allowed to use `Set` collection? – PM 77-1 Mar 08 '22 at 21:36
  • 1
    To start, the variable `temp` is declared as to be an array of `int` with size `0` (meaning no element) and is never resized, meaning you can't add elements to it. – Matteo NNZ Mar 08 '22 at 21:37
  • Second, the variable `numbersCount` is not declared so your code shouldn't even compile. – Matteo NNZ Mar 08 '22 at 21:38
  • Third, you're comparing the element `i` with the element `i-1` of the input array and if they're not equals, you're adding this element. However, you have no guarantee that the repeated element must be the previous one, unless the array is sorted and in this case you're missing an important specification to your question. – Matteo NNZ Mar 08 '22 at 21:39
  • I'm not allowed to use Set collection. – Victor Mar 08 '22 at 21:40
  • 2
    To conclude, you're saying that your code doesn't work but you're not saying why. By a quick guess (for what I see without testing) your code in the state shouldn't compile because `numbersCount` not declared. When you declare it, the code will fail at runtime as soon as you try to add one element in your 0-size `temp` array. But all these details should come from you in the question. – Matteo NNZ Mar 08 '22 at 21:40
  • Thank you for the comments. How should I declare the temp variable then to make it work? And how to declare numbersCount properly. I've got no idea how to correct it TBH. Can you help? – Victor Mar 08 '22 at 21:44

3 Answers3

2

I know it's not code golf here, but:

if you want to keep only unique values (like a Set would do), you can use a "one-liner". You don't have to implement loops.

public static void main(String[] args) {
  int[] dupes = {0, 1, 2, 1, 3, 2, 3};
  int[] uniques = Arrays.stream(dupes) // stream ints
      .boxed()                         // make Integer of int
      .collect(Collectors.toSet())     // collect into set to remove duplicates
      .stream()                        // stream Integers
      .mapToInt(Integer::intValue)     // make int of Integer
      .toArray();                      // and back into an array

  System.out.println(Arrays.toString(uniques));
}

Please not that you have to use java.util.Arrays.toString() to get useful output in the last statement. With your variant it will print only something like "[I@531be3c5" which denotes that it is an array of int, but says nothing about the contents.

Nevertheless - if you want to understand, how arrays and loops work, the looping solution is better!

cyberbrain
  • 3,433
  • 1
  • 12
  • 22
  • Be aware this actually uses a `Set` somewhere in the middle. I split up the code into multiple lines now and added comments so you can see what's going on. – cyberbrain Mar 08 '22 at 22:38
1

I'm not sure if you mean non-repeat or unique

But here is a method for checking for duplicates:

public static int[] returnUniqueArray(int[] arr) {
    int dupes = new int[arr.length]; // The most dupes you could have is the length of the input
    int numberOfDupes = 0;
    for (int i = 0; i < arr.length; i++) {
         for (int j = 0; j < arr.length; j++) {
             if(arr[i] == arr[j]) {
                 dupes[numberOfDupes] = arr[i];
                 numberOfDupes++;
             }
        }
    }
    return dupes;
}

This loops round the arr array twice, therefore comparing every variable in arr to every other variable. If they are the same, it adds that value to a new array.

You could also do similar for non-repeat:

public static int[] returnNonRepeatArray(int[] arr) {
    int dupes = new int[arr.length]; 
    int numberOfDupes = 0;
    for (int i = 0; i < arr.length - 1; i++) {
         
             if(arr[i] == arr[i+1]) {
                 dupes[numberOfDupes] = arr[i];
                 numberOfDupes++;
             }

    }
    return dupes;
}

This loops round the arr array once, but does not check the last item (-1 in the for loop). It then compares the item against the next item, if they are the same it adds that to the dupes.

Blundell
  • 75,855
  • 30
  • 208
  • 233
  • I just threw these together, you might want to double check with some unit tests :-) – Blundell Mar 08 '22 at 21:54
  • @Victor remember to mark it answered: https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Blundell Mar 13 '22 at 21:24
1
  public static void main(String[] args) {

    int[] arr = {1, 1, 2, 2, 3, 4, 5, 5, 5, 6};
    int[] items = returnNonRepeated(arr);
    System.out.print(Arrays.toString(items));
  }

  public static int[] returnNonRepeated(int[] arr) {
    
    int[] temp = new int[arr.length];
    int numbersCount = 1;
    for (int i = 0; i < arr.length; i++) {
      if (i == 0) {
        uniques[numbersCount] = arr[i];
        numbersCount++;
      } else {
        if (arr[i] != arr[i - 1]) {
          uniques[numbersCount] = arr[i];
          numbersCount++;
        }
      }
    }
    
    return uniques;
  }
neildo
  • 2,206
  • 15
  • 12