简体   繁体   English

用于插入char [] [] []数组的索引字符串

[英]Indexing string for insertion into char[][][] array

I'm a little stuck on the arithmetic for this program. 我对此程序的算法有些困惑。 I have a string theString that has a length of x*y*z . 我有一个字符串theString ,其长度为x*y*z x , y , and z are the dimensions of a char[][][] array (lets call it cArr ). xyz是char [] [] []数组的尺寸(我们称其为cArr )。

I want to insert the characters of theString into cArr based on a specific index. 我想基于特定索引将theString的字符插入cArr Here's an example of a 5x4x3 array. 这是一个5x4x3阵列的示例。

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: 我可以找出将字符从长度为20的字符串插入char [5] [4]数组的算法:

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? 对于3维char数组,我应该在charAt()方法中使用哪种算法?

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. 但这使cArr的所有z-index层都相同。

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) . 从最里面的循环开始,然后继续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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM