【发布时间】:2021-08-07 19:09:57
【问题描述】:
我得到一个方阵大小n 和矩阵包含的字符。
例如:
3
one
two
row
我必须将矩阵旋转 45 度。
| | |o| | |
|o|n|e| | |t| |n| |
|t|w|o| -> |r| |w| |e|
|r|o|w| | |o| |o| |
| | |w| | |
我明白了
| | |o| | |
|o|n|e| | |t| |n| |
|t|w|o| -> |r| |w| |e|
|r|o|w| | |o|w|o| |
| | | | | |
这是由于四舍五入造成的。
我写了代码。我的解决方案非常有限,我仅代表它来展示想法和我的错误。
我不明白的主要事情是如何将字符存储在数组中,以便在将浮点值舍入为整数值后它们具有正确的位置(坐标 x,y)。有正确的做法吗?
有什么建议或意见吗?
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cmath>
struct Coordinates
{
int x, y;
};
int main()
{
int n;
std::ifstream fin("U3.txt");
fin >> n;
fin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::vector<std::vector<char>> matrix;
for (int i = 0; i < n; i++)
{
std::string temp_s;
std::vector<char> temp_v(n);
std::getline(fin, temp_s, '\n');
for (int j = 0; j < n; j++)
{
temp_v[j] = temp_s[j];
}
matrix.push_back(temp_v);
}
fin.close();
std::vector<Coordinates> cord(n * n); // Store coordinates after rotation
int index = 0;
for (int y = 0; y < n; y++)
{
for (int x = 0; x < n; x++)
{
// Multiplying two matrices
/*
[ cos(45) -sin(45) ] [ x ]
[ sin(45) con(45) ] [ y ]
=
[ sqrt(2)/2 -sqrt(2)/2 ] [ x ]
[ sqrt(2)/2 sqrt(2)/2 ] [ y ]
=
[ sqrt(2)/2 * (x - y) ]
[ sqrt(2)/2 * (x + y) ]
*/
double new_x = (std::sqrt(2) / 2 * (x - y));
double new_y = (std::sqrt(2) / 2 * (x + y));
// Trying to round value to int because the index of array is int
cord[index].x = (new_x >= 0.0 ? std::ceil(new_x) : std::floor(new_x));
cord[index].y = (new_y >= 0.0 ? std::ceil(new_y) : std::floor(new_y));
index++;
}
}
/*
Finding the min_x and min_y to know how much should I add to
the new x and y coordinates to keep the coordinates positive,
as I have to store them in array.
*/
int min_x = std::numeric_limits<int>::max();
int min_y = std::numeric_limits<int>::max();
for (int i = 0; i < n * n; i++)
{
if (min_x > cord[i].x) { min_x = cord[i].x; }
if (min_y > cord[i].y) { min_y = cord[i].y; }
}
// If there are no negative coordinates then there is nothing to add
// So I initialize min_x and min_y to 0
if (min_x >= 0) { min_x = 0; }
if (min_y >= 0) { min_y = 0; }
std::vector<std::vector<char>> new_matrix(10, std::vector<char>(10, ' '));
int row = 0, column = 0;
for (int i = 0; i < cord.size(); i++)
{
new_matrix[cord[i].y + min_y * (-1)][cord[i].x + min_x * (-1)] = matrix[row][column];
if ((i + 1) % n == 0) { row++; column = 0; continue; }
column++;
}
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
std::cout << new_matrix[i][j];
}
std::cout << std::endl;
}
return 0;
}
【问题讨论】:
-
我不明白的主要是如何将字符存储在数组中,以便它们有正确的位置 -- 我建议你先在纸上计划一下而不是写可能会让您目瞪口呆的 C++ 代码。一旦你在纸上解决了这个问题,然后你就可以编写代码了。然后要么代码遵循您的计划(因此有效),或者它有一个遵循您的计划的错误并且您修复了错误,或者您确定该计划是错误的并且您重新开始一个新计划。
标签: c++ matrix multidimensional-array