Files
TD4_DEV51_felix-vi_raban/TriND.java
2025-10-15 10:23:42 +02:00

72 lines
2.2 KiB
Java

import java.util.Arrays;
import java.util.Comparator;
public class TriND {
public static void main(String[] args) {
// Exemple de tableau à 3 dimensions
Integer[][][] tableau3D = {
{ {3, 1, 2}, {9, 0, 8} },
{ {4, 5, 1}, {2, 2, 2} }
};
// Appel de la fonction de tri
trierND(tableau3D);
// Affichage du tableau trié
System.out.println("Tableau trié : ");
System.out.println(Arrays.deepToString(tableau3D));
}
/**
* Fonction qui trie un tableau de n'importe quelle dimension.
* Si c'est un tableau d'entiers, on le trie directement.
* Sinon, on trie les sous-tableaux récursivement, puis le tableau actuel
* selon la somme des sous-tableaux.
*/
public static void trierND(Object tableau) {
if (tableau instanceof int[]) {
// Si on est au dernier niveau (tableau d'entiers)
Arrays.sort((int[]) tableau);
} else if (tableau instanceof Object[]) {
Object[] tab = (Object[]) tableau;
// On trie d'abord les sous-tableaux (appel récursif)
for (Object sousTab : tab) {
trierND(sousTab);
}
// Puis on trie le tableau courant selon la somme de ses sous-tableaux
Arrays.sort(tab, new Comparator<Object>() {
@Override
public int compare(Object a, Object b) {
int sommeA = sommeRecursive(a);
int sommeB = sommeRecursive(b);
return Integer.compare(sommeA, sommeB);
}
});
}
}
/**
* Fonction qui calcule récursivement la somme d'un tableau à N dimensions.
*/
public static int sommeRecursive(Object tableau) {
if (tableau instanceof int[]) {
int somme = 0;
for (int valeur : (int[]) tableau) {
somme += valeur;
}
return somme;
} else if (tableau instanceof Object[]) {
int sommeTotale = 0;
for (Object sousTab : (Object[]) tableau) {
sommeTotale += sommeRecursive(sousTab);
}
return sommeTotale;
} else {
return 0;
}
}
}