[英]How to iterate through a 2D Array with a string of permutations?
I have a 2D array which is a square matrix 4x4. 我有一个2D数组,它是一个方阵4x4。
First I generated the permutation of '1234' S = "1234124313241423........."
(in fact it should be '0123', Let's ignore that for now.) if it's 5x5 it would be '12345' 首先,我生成了'1234
S = "1234124313241423........."
的排列(实际上它应该是'0123',让我们S = "1234124313241423........."
忽略它。)如果它是5x5,它将是'12345'
I would like to iterate through a 2D array and sum every 4 elements with the following fashion: 我想遍历2D数组并以以下方式对每4个元素求和:
The row-index follow the fixed pattern 1234,1234,1234. 行索引遵循固定模式1234,1234,1234。
The column-index is pulled from the permuted string. 列索引是从置换后的字符串中提取的。
input 2D Array which is a 4x4 matrix: 输入2D数组,它是4x4矩阵:
{9,2,7,8},
{6,4,3,7},
{5,8,1,8},
{7,6,9,4}
the 2D array can be represented as a[i][j], i for rows and j for columns, columns are pulled from S = "1234124313241423" chop every 4 digits from the string. 2D数组可以表示为a [i] [j],i表示行,j表示列,从字符串中每4位从S =“ 1234124313241423”截取列。
index index
Read from left to right
a11+a22+a33+a44 => 9+4+1+4=18 rows: 1 2 3 4 columns: 1 2 3 4
a11+a22+a34+a43 => 9+4+8+9=30 rows: 1 2 3 4 columns: 1 2 4 3
a11+a23+a32+a44 => 9+3+8+4=24 rows: 1 2 3 4 columns: 1 3 2 4
a11+a24+a32+a43 ...........
.
.
.
output:18,30,24,.... 输出:18,30,24,....
It seems like a standard nested loop won't do the job. 似乎标准的嵌套循环无法完成任务。
您需要有一个外部循环,该循环将不重复任何行时间...然后对于每个迭代,递增i和j并获得值S [i] [j]外循环可以像while(k <noOfRows) ..我要离开程序供您练习...
String s = "123412431324...";
while(s.length() != 0){
int sum=0;
for(int j=0, i=0; j<n; j++, i++){
sum += arr[i][Integer.parseInt(s.charAt(j))-1];
}
System.out.println(sum);
s = s.substring(n);
}
Your can perform like this. 您可以像这样表演。 You need a outer loop which can slice up your string by dimension of your array and another loop for iterating through your array so that you can sum up the elements.[Check the for loop carefully]
您需要一个外部循环,该循环可以按数组的维数对字符串进行切片,而另一个循环则需要遍历数组,以便可以对元素进行求和。[仔细检查for循环]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.