Reputation: 23
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
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
Reputation: 618
Use a HashSet!
This approach is very efficient as search, insert, and remove are all O(1) in a HashSet.
Upvotes: 1