由于这对我来说是一个非常有趣的话题,所以我也一直在寻找答案。我认为您可能会幸运地使用Mark Byers 的方法:
Mark 没有将其存储在 3D 数组中,而是在如何使用 1D 数组方面提供了一种非常好的方法。
经过一番尝试,我想出了完整的立方体,希望它适合你:
public class Cube {
int w, h, d;
int[] cube;
public Cube(int w, int h, int d) {
this.w = w;
this.h = h;
this.d = d;
System.out.println("cube: w" + w + ", h" + h + ", d" + d + " = " + (w * h * d));
cube = new int[w * h * d];
}
int getCubeValue(int x, int y, int z) {
return cube[x * h * d + y * d + z];
}
void setCubeValue(int x, int y, int z, int value) {
System.out.println("value " + (x * h * d + y * d + z) + ": x" + x + ", y" + y + ", z" + z + " = " + value);
cube[x * h * d + y * d + z] = value;
}
int[] xSlice(int x) {
int[] slice = new int[h * d];
for(int y = 0; y < h; y++) {
for(int z = 0; z < d; z++) {
slice[y * d + z] = getCubeValue(x, y, z);
}
}
return slice;
}
int xSliceValue(int[] slice, int y, int z) {
return slice[y * d + z];
}
int[] ySlice(int y) {
int[] slice = new int[d * w];
for(int z = 0; z < d; z++) {
for(int x = 0; x < w; x++) {
slice[z * w + x] = getCubeValue(x, y, z);
}
}
return slice;
}
int ySliceValue(int[] slice, int x, int z) {
return slice[z * w + x];
}
int[] zSlice(int z) {
int[] slice = new int[w * h];
for(int x = 0; x < w; x++) {
for(int y = 0; y < h; y++) {
slice[x * h + y] = getCubeValue(x, y, z);
}
}
return slice;
}
int zSliceValue(int[] slice, int x, int y) {
return slice[x * h + y];
}
}
假设你制作了一个像 new Cube(3, 3, 3) 这样的 Cube,cube.getCubeValue(2, 2, 2) 可以接近最后一个值,因为它从零开始。