PLEASE HELP 2D ARRAY

Hey everyone, I have this problem:
I should divide a 2D array into square regions with a given parameter(d), find the maxes of each region and then their sum.
All I have done up now is this code here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>

using namespace std;

int main()
   
{
    static int array1[200][200];
    int i, j, m, n,d;
    cin>>m>>n>>d;
    for (i = 0; i < m; ++i)
    {
        for (j = 0; j < n; ++j)
        {
            cin>>array1[i][j];
        }
    }
     
     
     for (i = 0; i < d; ++i)
    {
        for (j = 0; j < d; ++j)
        {
            cout<<array1[i][j];
        }
        cout<<"\n";
    }
     
     
     for (i = d; i < m; ++i)
    {
        for (j = 0; j < d; ++j)
        {
            cout<<array1[i][j];
        }
        cout<<"\n";
    }
 for (i = 0; i < d; ++i)
    {
        for (j = d; j < n; ++j)
        {
            cout<<array1[i][j];
        }
        cout<<"\n";
    }
    for (i = d; i < m; ++i)
    {
        for (j = d; j < n; ++j)
        {
            cout<<array1[i][j];
        }
        cout<<"\n";
    }
    }




But the problem is that this solution only works with this input:
5 6 3
0 8 1 1 10 6
6 8 7 0 3 9
0 7 6 8 6 5
4 0 2 7 2 0
4 4 5 7 5 1

Because lets say if there are 11 columns, it takes the first three and then it takes up until the end of the columns and it doesn't divide it three by three(where three is the parameter the user enters)
Can you please help me out and give me a general solution for this code?
Thank youuuuu
Consider this loop: for ( foo = 0; foo < bar; ++foo ) (which you have in your code).

Lets reword one piece of it: for ( foo = 0; foo < bar; foo += 1 )
And then a little more:
1
2
int stride = 1;
for ( foo = 0; foo < bar; foo += stride )

Nothing has changed. The loops still repeats for bar times.

Now do the change:
1
2
int stride = bar / d;
for ( foo = 0; foo < bar; foo += stride )

That loop does less iterations. One per "region"?
The only special case is the last region, if bar is not a multiple of d.
Thanks for the reply but actually I couldnt quite understand what you meant..
To be more precise, starting from the first loop of dividing it in regions, it prints these regions:
0 8 1
6 8 7

4 0 2
4 4 5

1 10 6
0 3 9
8 6 5

7 2 0
7 5 1

and if the matrix would be lets say 6x11, the rows would continue up to 11 and not divide it by 3..i hope you understand what i am saying
Last edited on
Let me put it differently:
1
2
3
4
5
6
7
int vstride = rows / d;
int hstride = cols / d;
for ( int row = 0; row < rows; row += vstride ) {
  for ( int col = 0; col < cols; col += hstride ) {
    // print region [row..row+vstride)[col..col+hstride)
  }
}
Topic archived. No new replies allowed.