-1

I'm a little stuck on the arithmetic for this program. I have a string theString that has a length of x*y*z. x, y, and z are the dimensions of a char[][][] array (lets call it cArr).

I want to insert the characters of theString into cArr based on a specific index. Here's an example of a 5x4x3 array.

String theString = someMethod(); //returns a string of length 60
char[][][] cArr = new char[5][4][3];
for (int z = 0; z < 3; z++) {
    for (int y = 0; y < 4; y++) {
        for (int x = 0; x < 5; x++) {
            cArr[x][y][z] = theString.charAt(/*~~~*/);
        }
    }
}

I can figure out the arithmetic to insert characters into a char[5][4] array from a string of length 20:

for (int y = 0; y < 4; y++) {
    for (int x = 0; x < 5; x++) {
        cArr[x][y] = theString.charAt((5*y)+x);
    }
}

What arithmetic should I be using in the charAt() method for a 3-dimensional char array?

My best attempt has been:

char[][][] cArr = new char[5][4][3];
for (int z = 0; z < 3; z++) {
    for (int y = 0; y < 4; y++) {
        for (int x = 0; x < 5; x++) {
            cArr[x][y][z] = theString.charAt(((3^2)*z)+(4*y)+x);
        }
    }
}

But this makes all z-index layers of cArr the same.

gator
  • 3,465
  • 8
  • 36
  • 76
  • Using [this terminology](http://i.ytimg.com/vi/mIJXeNWIE1E/hqdefault.jpg): number of full panes times cubes in a pane + number of full columns (in a partial pane) times cubes in a column + number of cubes in a partial column. – PM 77-1 Jul 07 '15 at 03:06

1 Answers1

3

The rule is simple for problems like this. You start from the innermost loop and proceed up with x + y*(length of x) + z*(length of y)*(length of x).

In this example, it would be,

cArr[x][y][z] = theString.charAt(x + y*5 + z*4*5);
Codebender
  • 14,221
  • 7
  • 48
  • 85