Skip to content

Commit a65ff47

Browse files
authored
Add Transpose Matrix in C++ (#5094)
1 parent 1acc7d6 commit a65ff47

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#include <iostream>
2+
#include <sstream>
3+
#include <vector>
4+
#include <string>
5+
6+
#define MAX_MATRIX_SIZE 100
7+
8+
void transpose_matrix(int *matrix, int rows, int cols, int *transposed) {
9+
for (int i = 0; i < rows; i++) {
10+
for (int j = 0; j < cols; j++) {
11+
transposed[j * rows + i] = matrix[i * cols + j];
12+
}
13+
}
14+
}
15+
16+
int main(int argc, char *argv[]) {
17+
if (argc != 4) {
18+
std::cout << "Usage: please enter the dimension of the matrix and the serialized matrix" << std::endl;
19+
return 1;
20+
}
21+
22+
int cols = std::atoi(argv[1]);
23+
int rows = std::atoi(argv[2]);
24+
std::string input = argv[3];
25+
26+
if (cols <= 0 || rows <= 0 || input.empty()) {
27+
std::cout << "Usage: please enter the dimension of the matrix and the serialized matrix" << std::endl;
28+
return 1;
29+
}
30+
31+
int matrix[MAX_MATRIX_SIZE];
32+
int transposed[MAX_MATRIX_SIZE];
33+
int count = 0;
34+
35+
std::stringstream ss(input);
36+
std::string token;
37+
38+
while (std::getline(ss, token, ',') && count < rows * cols) {
39+
// Trim leading spaces
40+
size_t start = token.find_first_not_of(" ");
41+
if (start != std::string::npos) {
42+
token = token.substr(start);
43+
}
44+
matrix[count++] = std::atoi(token.c_str());
45+
}
46+
47+
if (count != rows * cols) {
48+
std::cout << "Usage: please enter the dimension of the matrix and the serialized matrix" << std::endl;
49+
return 1;
50+
}
51+
52+
transpose_matrix(matrix, rows, cols, transposed);
53+
54+
for (int i = 0; i < cols * rows; i++) {
55+
std::cout << transposed[i];
56+
if (i < cols * rows - 1) {
57+
std::cout << ", ";
58+
}
59+
}
60+
std::cout << std::endl;
61+
62+
return 0;
63+
}

0 commit comments

Comments
 (0)