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
|
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <cmath>
using namespace std;
using matrix = vector< vector<int> >;
//----------------------------------------------------------
void output( string title, matrix M )
{
if ( title != "" ) cout << title << '\n';
for ( auto &row : M )
{
for ( auto e : row ) cout << setw( 2 ) << e << " ";
cout << '\n';
}
cout << '\n';
}
//----------------------------------------------------------
int main()
{
const int N = 4;
int rootN = sqrt( N );
matrix M = { { 0, 1, 2, 3 },
{ 4, 5, 6, 7 },
{ 8, 9, 10, 11 },
{ 12, 13, 14, 15 } };
output( "Initial matrix:", M );
for ( int sub = 0; sub < N; sub++ )
{
matrix m( rootN, vector<int>( rootN, 0 ) ); // submatrix (initialised to 0)
int i0 = ( sub / rootN ) * rootN; // (i0,j0) = top-left position in original matrix
int j0 = ( sub % rootN ) * rootN;
for ( int i = 0; i < rootN; i++ ) // (i,j) = index in submatrix
{
for ( int j = 0; j < rootN; j++ ) m[i][j] = M[i0+i][j0+j]; // (i0+i,j0+j) = index in original matrix
}
output( "Submatrix " + to_string( sub ) + ":", m );
}
}
|