istrikeanywhere
istrikeanywhere

Reputation: 23

Trying to display the ints in an array that only occur once

I have an array I have created that is a length of 25 and and has randomly generated numbers in it 1 to 25. The array will pretty much always have duplicate numbers in it and all i want to do is display the numbers that occur only once in the array. The code I have so far seems to work as long as the numbers that are repeated only repeat an even number of times. My question is how do I make this work so I only get numbers that occur once added to my string.

I can not use hash or set or anything like that this is part of an assignment.

int count2 = 0;

for (int d = 0; d < copy.length-1; d++) 
{
    int num = copy[d];

    if (num != copy[d+1]) 
    {
        s = s + "," + num;
    } 
    else 
    {
        d++;
    }    
}

Upvotes: 2

Views: 1747

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201467

I would start by writing a separate method to count the number of occurrences of a value in the given array so you can count how many occurrences there are for each value using a For-Each Loop like

private static int count(int[] arr, int value) {
    int count = 0;
    for (int item : arr) {
        if (item == value) {
            count++;
        }
    }
    return count;
}

Then you can leverage that like

public static String toUniqueString(int[] arr) {
    StringBuilder sb = new StringBuilder();
    for (int value : arr) {
        if (count(arr, value) == 1) {
            if (sb.length() != 0) {
                sb.append(", ");
            }
            sb.append(value);
        }
    }
    return sb.toString();
}

Finally, to test it

public static void main(String[] args) {
    Random rand = new Random();
    int[] arr = new int[25];
    for (int i = 0; i < arr.length; i++) {
        arr[i] = rand.nextInt(arr.length) + 1;
    }
    System.out.println(toUniqueString(arr));
}

Upvotes: 1

Michael Goldstein
Michael Goldstein

Reputation: 618

Use a HashSet!

  1. Construct two new HashSets, one for the elements appearing just once and one for the duplicates
  2. Iterate through your array
  3. For each value in the array check if it's already in the set of duplicates. If so, do nothing else and continue to the next iteration
  4. Check if the value is already in the set of elements appearing just once
  5. If it's not, add it. If it is, remove it and add it to a list of duplicates
  6. Call hashSet.toArray() and then you will have an array of all the elements appearing only once
  7. You can convert the array to a string or use it however you wish

This approach is very efficient as search, insert, and remove are all O(1) in a HashSet.

Upvotes: 1

Related Questions