1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| import java.util.Arrays;
public class NDimArray<T> {
private int dim;
private Object[] array;
public NDimArray(int length, int...lengths) {
dim = 1+lengths.length;
array = new Object[length];
create(array, 0, lengths); // création par récursivité
}
private void create(Object[] array, int n, int[] lengths) {
if ( n<lengths.length ) {
for(int i=0; i<array.length; i++) {
array[i]=new Object[lengths[n]];
create((Object[])array[i], n+1, lengths); // appel récursif
}
}
}
private NDimArray(T[] array, int dim) {
this.dim=dim;
this.array=array;
}
public NDimArray<T> getSubArray(int i) {
if ( dim>1 ) {
return new NDimArray<T>((T[])array[i], dim-1);
}
else {
throw new IllegalStateException();
}
}
public int getDimensions() {
return dim;
}
public void fill(T value) {
fill(array, 0, value);
}
private void fill(Object[] array, int n, T value) {
if ( n<dim-1 ) {
for(Object subarray : array) {
fill((Object[])subarray, n+1, value); // récursivité
}
}
else {
Arrays.fill(array, value);
}
}
public void setValue(T value, int...x) {
if ( x.length!=dim ) throw new IllegalArgumentException();
setValue(value, array, 0, x);
}
private void setValue(T value, Object[] array, int n, int...x) {
if ( n<dim-1 ) {
setValue(value, (Object[])array[x[n]], n+1, x); // récursivité
}
else {
array[x[n]]= value;
}
}
@Override
public String toString() {
return Arrays.deepToString(array);
}
public static void main(String[] args) {
NDimArray<Integer> array = new NDimArray<>(3, 2, 4); // tableau de 3 x 2 x 4
System.out.println("Dimensions : " + array.getDimensions());
array.fill(0);
System.out.println(array);
array.setValue(1, 0, 0, 0); // mettre 1 dans [0][0][0]
array.setValue(2, 1, 1, 1); // mettre 2 dans [1][1][1]
array.setValue(42, 0, 1, 3); // mettre 42 dans [0][1][3]
System.out.println(array);
System.out.println(array.getSubArray(1).getSubArray(1));
NDimArray<String> stringArray = new NDimArray<>(2, 2, 2, 2, 2); // tableau de 2 x 2 x 2 x 2 String
System.out.println("Dimensions : " + stringArray.getDimensions());
stringArray.fill(".");
stringArray.setValue("X", 1, 1, 1, 1, 1); // mettre X dans [1][1][1][1][1]
System.out.println(stringArray);
}
} |