Reputation: 1581
I am working on a school homework problem. I need to create 2 int[]
arrays. The first array int[10]
is filled with random integers
. The second array has the same numbers as in the first array, but without any duplicates.
For example, assume my first array is 1,2,2,3,1,5,5,7,9,9
. My second array would then be 1,2,3,5,7,9
.
Could someone please point me in the right direction to solving this problem.
Upvotes: 1
Views: 284
Reputation: 62439
@WATTO Studios has a good approach. Sorting is always useful when duplicates are involved.
I will suggest an alternative method using hash tables:
Let's see a practical case:
4 5 6 4 1 1 3
First pass will create the following table:
1 -> 2
3 -> 1
4 -> 2
5 -> 1
6 -> 1
Second pass step by step:
4 5 6 4 1 1 3
^
4 has a counter of 2 -> remove and decrement:
1 -> 2
3 -> 1
4 -> 1
5 -> 1
6 -> 1
5 6 4 1 1 3
^
5 has a counter of 1 -> ignore
6 has a counter of 1 -> ignore
4 has a counter of 1 -> ignore
1 has a counter of 2 -> remove and decrement
1 -> 1
3 -> 1
4 -> 1
5 -> 1
6 -> 1
5 6 4 1 3
^
1 has a counter of 1 -> ignore
3 has a counter of 1 -> ignore
Final array:
5 6 4 1 3
There are, of course, more efficient ways to handle the removal (since using an array implies shifting), like inserting the items into a linked list for example. I'll let you decide that. :)
Edit: An even faster approach, requiring a single pass:
Upvotes: 0
Reputation: 15389
I recommend using a Set , but here's a way to do it without using a Set. (Note: This will work, but don't ask me about the efficiency of this!)
Have a function like this -
public static boolean isNumberInArray(int[] array, int number)
{
for(int i=0; i<array.length; i++)
{
if(number == array[i])
return true;
}
return false;
}
Now use this function before you make an insert into the new array. I leave you to figure out that part. It's homework after all!
Upvotes: 1
Reputation: 18008
Hints(WATTO explains it better):
a = sorted first array
lastItem = a[0]
append lastItem into new array
for i in 1 to length(a):
if a[i] != lastItem:
append a[i] into new array
lastItem = a[i]
Upvotes: 0
Reputation: 15389
Put the numbers into a Set. Then retrieve numbers from the Set. Simple! Duplicates will automatically be removed!
Upvotes: 4
Reputation: 8764
I would do the following (assuming that it is homework and you shouldn't be doing anything too complicated)...
java.util.Arrays.sort(myArray);
- this will order the numbers, and make sure that all repeating numbers are next to each other.int[]
array to the correct size (from point 2)This should be enough to get you moving in the right direction. When you have some code, if you still have questions, come back to us and ask.
Upvotes: 2