forked from menault/TD4_DEV51_Qualite_Algo
TD4
This commit is contained in:
70
Algo.java
Normal file
70
Algo.java
Normal file
@@ -0,0 +1,70 @@
|
||||
import java.util.*;
|
||||
|
||||
public class Algo {
|
||||
|
||||
public static Object sortNDArray(Object array) {
|
||||
if (array instanceof int[]) {
|
||||
int[] arr = (int[]) array;
|
||||
Arrays.sort(arr);
|
||||
return arr;
|
||||
} else if (array instanceof Object[]) {
|
||||
Object[] arr = (Object[]) array;
|
||||
|
||||
for (int i = 0; i < arr.length; i++) {
|
||||
arr[i] = sortNDArray(arr[i]);
|
||||
}
|
||||
|
||||
Arrays.sort(arr, new Comparator<Object>() {
|
||||
@Override
|
||||
public int compare(Object o1, Object o2) {
|
||||
int sum1 = getSum(o1);
|
||||
int sum2 = getSum(o2);
|
||||
return Integer.compare(sum1, sum2);
|
||||
}
|
||||
});
|
||||
|
||||
return arr;
|
||||
}
|
||||
|
||||
return array;
|
||||
}
|
||||
|
||||
public static int getSum(Object array) {
|
||||
if (array instanceof int[]) {
|
||||
int sum = 0;
|
||||
for (int val : (int[]) array) {
|
||||
sum += val;
|
||||
}
|
||||
return sum;
|
||||
} else if (array instanceof Object[]) {
|
||||
int sum = 0;
|
||||
for (Object sub : (Object[]) array) {
|
||||
sum += getSum(sub);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static void printArray(Object array) {
|
||||
if (array instanceof int[]) {
|
||||
System.out.println(Arrays.toString((int[]) array));
|
||||
} else if (array instanceof Object[]) {
|
||||
for (Object sub : (Object[]) array) {
|
||||
printArray(sub);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Object[] array2D = new Object[] {
|
||||
new int[] {0, 3, 2},
|
||||
new int[] {9, 4, 5},
|
||||
new int[] {4, 1, 3},
|
||||
new int[] {4, 1, 3}
|
||||
};
|
||||
|
||||
Object sorted = sortNDArray(array2D);
|
||||
printArray(sorted);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user