Problem
Transpose an integer array
Solution
#include <iostream>
using namespace std;
int** create_matrix(int row, int col)
{
int **m = new int* [row];
for(int i = 0; i < row; i++){
m[i] = new int[col];
}
return m;
}
void delete_matrix(int** m, int row)
{
for(int i = 0; i < row; i ++){
delete[] m[i];
}
delete []m;
}
void print_matrix(int** m, int row, int col)
{
for(int i = 0; i < row; i ++){
for(int j = 0; j < col; j++){
cout << m[i][j] << " ";
}
cout << endl;
}
}
void initial_matrix(int **m, int row, int col)
{
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j ++){
m[i][j] = rand() % 100;
}
}
}
void transpose_matrix(int **mat, int row, int col)
{
int i, j;
for(i= 0; i< row; i++){
for(j=i+1; j< col; j++){
int tmp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = tmp;
}
}
}
int main(int argc, char* argv[])
{
int size = 6;
int **m = create_matrix(size, size);
int i,j;
initial_matrix(m, size, size);
cout << "before transposing" << endl;
print_matrix(m, size, size);
transpose_matrix(m, size, size);
cout << "after transposing" << endl;
print_matrix(m, size, size);
return 0;
}
Output
before transposing
41 67 34 0 69 24
78 58 62 64 5 45
81 27 61 91 95 42
27 36 91 4 2 53
92 82 21 16 18 95
47 26 71 38 69 12
after transposing
41 78 81 27 92 47
67 58 27 36 82 26
34 62 61 91 21 71
0 64 91 4 16 38
69 5 95 2 18 69
24 45 42 53 95 12