Move the area
Mar 27, 2021 at 9:44am UTC
I want to move the areas : N -> E, E -> S, S -> V, V -> N
The problem is that my code moves only one element in the matrix and not all the elements in the area.
EX:
4
11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44
The correct output:
11 31 21 14
42 22 23 12
43 32 33 13
41 34 24 44
My ouput:
11 12 31 14
21 22 23 24
43 32 33 13
41 42 34 44
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
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream fin("date.in" );
int N, mt[51][51], areaN[51][51], areaE[51][51], areaS[51][51], areaV[51][51];
fin >> N;
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
fin >> mt[i][j];
}
}
int lineN, colN, lineS, colS, lineE, colE, lineV, colV;
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
if (i < j && i + j < N + 1) {
lineN = i;
colN = j;
areaN[i][j] = mt[i][j];
}
if (i > j && i + j < N + 1) {
areaV[i][j] = mt[i][j];
lineV = i;
colV = j;
}
if (i > j && i + j > N + 1) {
areaS[i][j] = mt[i][j];
lineS = i;
colS = j;
}
if (i < j && i + j > N + 1) {
areaE[i][j] = mt[i][j];
lineE = i;
colE = j;
}
}
}
mt[lineE][colE] = areaN[lineN][colN];
mt[lineS][colS] = areaE[lineE][colE];;
mt[lineV][colV] = areaS[lineS][colS];
mt[lineN][colN] = areaV[lineV][colV];
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
cout <<mt[i][j] << " " ;
}
cout << "\n" ;
}
}
Mar 27, 2021 at 10:57am UTC
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
#include <iostream>
#include <iomanip>
#include <sstream>
#include <fstream>
using namespace std;
istringstream fin( // data file
"4 \n"
"11 12 13 14 \n"
"21 22 23 24 \n"
"31 32 33 34 \n"
"41 42 43 44 \n"
);
int main()
{
const int MX = 1 + 50;
// ifstream fin( "date.in" );
int N, mt[MX][MX];
// Read
fin >> N;
for ( int i = 1; i <= N; i++ )
{
for ( int j = 1; j <= N; j++ ) fin >> mt[i][j];
}
// Rotate
for ( int p = 2; p <= N - 1; p++ )
{
int temp = mt[N-p+1][1];
mt[N-p+1][1 ] = mt[N][N-p+1];
mt[N ][N-p+1] = mt[p][N ];
mt[p ][N ] = mt[1][p ];
mt[1 ][p ] = temp;
}
// Write
for ( int i = 1; i <= N; i++ )
{
for ( int j = 1; j <= N; j++ ) cout << setw( 2 ) << mt[i][j] << ' ' ;
cout << '\n' ;
}
}
11 31 21 14
42 22 23 12
43 32 33 13
41 34 24 44
Last edited on Mar 27, 2021 at 10:22pm UTC
Topic archived. No new replies allowed.