Thread: Removing duplicates from double Arrays

1. Member
Join Date
Oct 2010
Posts
2
Rep Power
0

Removing duplicates from double Arrays

Hello,

I'm trying to write a program with a method that takes an array of various double type numbers of any size, then return only the unique numbers (return an array without the duplicates) while maintaining the order.

So input {5, 3, 5, 5, 3, 2, 1, 3, 4} should return {5, 3, 2, 1, 4}.

Here's the code:
Java Code:
```public double[] uniqueNumbers(double[] Numbers) {
double[] u = new double[Numbers.length];
double num = Numbers[0];
u[0] = num;
int ii = 1;
for (int i = 0; i < u.length; i++){
if (Numbers[i] != num){
num = Numbers[i];
u[ii] = num;
ii++;
}
}
/*this is the part where I try to make an array u with only the duplicates, then leave the rest with 0s*/

double[] un;
int x = 0;
for (int z = 0; z < u.length; z++){
if (u[z] == 0){
x = z + 1;
}
}
un = new double[x];
for (int y = 0; y < u.length; y++){
if (u[y] != 0){
[B]un[y] = u[y];[/B] // this is where the error occurs apparently
}
}
return un;
/* here I tried to create a new array un that would have the values from u moved over except the 0s */

}```
But when I run it I get this: :(

java.lang.ArrayIndexOutOfBoundsException: 0
at xxxxxx.uniqueNumbers(xxxxxx.java:77)
Any idea why?

EDIT: Per Fubarable's suggestion, I put in a few println statements here and there, and the 1st part of the code where I create array u, it seems like the input array Numbers just gets copied over to u... :(
Last edited by jhong253; 10-30-2010 at 10:05 PM. Reason: Details

2. What line in your code above causes this error to occur? Have you added println statements to see the state of your variables at the time or just before the error occurs?

3. Member
Join Date
Oct 2010
Posts
2
Rep Power
0

I'm going to edit the original post to reflect on what's where... one sec.

4. If I'm not mistaken:

Java Code:
```    double[] un;
int x = 0;
for (int z = 0; z < u.length; z++){
if (u[z] == 0){
x = z + 1;
}
}
un = new double[x];```

What if "u" has 25 values and number [3] and [24] had zeros. "X" would then be equal to... I'm not sure I really understand the use of this statement and then using "X" to declare the size of your next array?

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•