ArrayList size specified at runtime

Suppose I have an algorithm that can play chess on a chessboard that nis {1,...,8}^n n-dimensional using -dimensional squares.

The algorithm itself has no problems with working in measurements n, given the n-dimensional array or ArrayList to represent the chessboard. The problem is what nneeds to be specified at runtime.

Is there an elegant way to create and use such a ndimensional chessboard?

What I thought was a recursive function to create a n-dimensional ArrayList that returns an ArrayList from integers if n == 1, and returns an ArrayList from ArrayLists, where each ArrayList of the second set of ArrayLists has a dimension n-1.

But this does not seem to be very elegant ...

[edit]

The answer, which seems to have been deleted before I could comment, suggested creating one List containing other lists of size 8. If I use a 8 ^ numberOfDimensionslist from a list in the first list, this will probably work, but it will force me to manually track sizes.

+4
source share
2 answers

, Map. , List n :

Map<List<Integer>, BoardCell> chessboard;

BoardCell, , , , ..:

class BoardCell {
   private final List<Integer> index;
   private final Figure figure;
}

, , ( ) , .

, List of List of List ..


Viliam Búr , Map, . .

+3

, , :

List makeBoard(int dim) {
    List res = new ArrayList(8);
    for (int i = 0 ; i != 8 ; i++) {
        if (dim != 1) {
            res.add(makeBoard(dim-1));
        } else {
            res.add(0);
        }
    }
    return res;
}

, . dim - 1, ; dim-1.

+1

All Articles