Each vector element is a row and each character is a column.
Assume the matrix is square (N*N) and N is < 10.
I have some code to do it but it doesn't look great and would love some feedback on how to make it better. You can use any function of the C++ standard library. The only constraint is it can't be in-place. I'm looking to improve it in style and any optimisations needed.
enum DIRECTION
{
DIR_RIGHT = 0,
DIR_LEFT = 1
};
vector<string> rotate(const vector<string>& original, DIRECTION direction)
{
vector<string> rotated(original);
for (vector<string>::const_iterator irow = original.begin(); irow != original.end(); ++irow) {
int new_col = direction == DIR_RIGHT ? (original.size() - 1) - (irow - original.begin())
: (irow - original.begin());
for (string::const_iterator icol = (*irow).begin(); icol != (*irow).end(); ++icol) {
int new_row = direction == DIR_RIGHT ? (icol - (*irow).begin())
: ((*irow).size() - 1) - (icol - (*irow).begin());
rotated[new_row][new_col] = *icol;
}
}
return rotated;
}
Example input:
"###"
"oho"
"ooo"
Rotating right should output:
"oo#"
"oh#"
"oo#"
P.s. For convenience I've included using namespace std;
, the final code uses the namespace explicitly E.g. std::vector
.