Brij Raj Kishore - 9 months ago 29

Java Question

I have 3 arrays

a , b ,c

of size n.

a and b arrays are entered by the user and c is calculated as

c[i] = b[i] - a[i] + 1

Sorting the c array is easy. I have done it by

Arrays.sort(c)

but I want to make amends in a and b also such that the a[i] and b[i] corresponds to the new sorted c[i].

For Example -

a[5] ={1 , 3 , 5 , 7 , 9 }

b[5] ={5 , 4 , 7 , 8 , 10 }

Then will be calculated as - c[i] = b[i] - a[i] +1.

c[5] ={5 , 2 , 3 , 2 , 2}

Now sorting the c array, it results in

c[5] = { 2 , 2 , 2 , 3 , 5 }

Now i also want a and b as

a[5]={ 3 , 7 , 9 , 5 , 1 }

b[5]={ 4 , 8 , 10 , 7 , 5 }

Answer

Using array will be way too messy. You can keep them in a class:

```
public class Triplets {
public int a;
public int b;
public int c;
}
```

Then we can take input in this class instead of seperate arrays (for example) :

```
int [] a ={1 , 3 , 5 , 7 , 9 };
int [] b ={5 , 4 , 7 , 8 , 10 };
Triplets [] tripletses = new Triplets[5];
for (int i = 0 ; i < tripletses.length ; i++){
tripletses[i] = new Triplets();
tripletses[i].a = a[i];
tripletses[i].b = b[i];
tripletses[i].c = tripletses[i].b - tripletses[i].a + 1;
}
```

Of course you need to use your own input logic there. Now we can sort this array using a Custom Comparator

```
Arrays.sort(tripletses, new TripletsComp());
```

And of course the Comparator:

```
public class TripletsComp implements Comparator<Triplets> {
@Override public int compare(Triplets e1, Triplets e2) {
if(e1.c > e2.c){
return 1;
}else if (e1.c == e2.c){
return 0;
}
else { return -1; }
}
}
```

If you are not familiar with Comarator, have a read about them :)

Source (Stackoverflow)