0

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.

8
  • Is your question how to create a 2-D array here, or how to iterate through it? Commented Mar 24, 2018 at 4:25
  • @CoffeehouseCoder Hi sorry for the confusion. I would like to iterate through a 2D array. Commented Mar 24, 2018 at 4:26
  • So have you already created the array? Commented Mar 24, 2018 at 4:26
  • @CoffeehouseCoder yes I have. Commented Mar 24, 2018 at 4:29
  • 1
    Here is not the place you find this solution Commented Mar 24, 2018 at 5:44

2 Answers 2

1

You need to have an outer loop which will iterate no of rows times... Then for each of that iteration increment i and j both and get the value S[i][j] Outer loop can be like while(k< noOfRows).. i am leaving the program for you to practise...

Sign up to request clarification or add additional context in comments.

Comments

0
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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.