I have a 2D array which is a square matrix 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'
I would like to iterate through a 2D array and sum every 4 elements with the following fashion:
The row-index follow the fixed pattern 1234,1234,1234.
The column-index is pulled from the permuted string.
input 2D Array which is a 4x4 matrix:
{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.
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,....
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.