kuroky
kuroky

Reputation: 33

Exchange values of two arrays, make another array without repeats and sort from highest to lowest

I know I have to do it with a while or do while loop, but I can't get it working. I also tried with a for loop, but it always gives me an error because I don't know the exact length of the vectors because they are random.

int a = (int)(Math.random() * 3 + 1);
int b = (int)(Math.random() * 3 + 1);
int c = a + b;
int[] arrA = new int[a];
int[] arrB = new int[b];
int[] arrC = new int[c];
for (int i = 0; i < a; i ++) {
    arrA[i] = (int)(Math.random() * 10 + 1);
    for (int j = 0; j < b; j ++) {
        arrB[j] = (int)(Math.random() * 10 + 1);
    }
}

Arrays.sort(arrA);
Arrays.sort(arrB);
System.out.println(Arrays.toString(arrA));
System.out.println(Arrays.toString(arrB));
System.out.println(Arrays.toString(arrC));

Upvotes: 1

Views: 60

Answers (1)

Prince Vegeta
Prince Vegeta

Reputation: 719

Take values from arrays arrA and arrB, and insert to arrC

int index = arrA.length;
for (int i = 0; i < arrA.length; i++) {
    arrC[i] = arrA[i];
}
for (int i = 0; i < arrB.length; i++) {
    arrC[i + index] = arrB[i];    
}

Sort arrC

Arrays.sort(arrC);

Reverse the order and store in arrD

for(int l = 0; l < arrC.length; l++) {
    arrD[l] = arrC[arrC.length - (l+1)];
}

Remove duplicate (simplified)

Set<Integer> remove=new LinkedHashSet<Integer>();
for(int i = 0;i < arrD.length;i++){
    remove.add(arrD[i]);
}

Remove duplicate (usual)

int index2 = 0;
for (int i = 0; i < arrD.length; i++) {
    for (int k = 0; k < arrD.length; k++) {
        if (arrD[i] != arrD[k]) {
            arrE[index2] = arrD[i];
            index2++;
        }
    }
}

Upvotes: 1

Related Questions