Corne14
Corne14

Reputation: 41

Rotate a matrix (2d-std::vector) by 90°

I'm programming an IQ puzzle game for a project at college in C++, and I have the forms of the pieces stored in vector matrices. I need to be able to rotate them clockwise and counterclockwise but so far I haven't found any information on how to do this.

As an example I have a purple piece stored like this:

vector<vector<int>> cherry = {{0,4},
                              {4,4},
                              {4,0}};

How can I rotate it in order to have the piece stored like this?

4 4 0
0 4 4

Upvotes: 0

Views: 753

Answers (2)

Dr. Gut
Dr. Gut

Reputation: 2836

Rotating clockwise:

vector<vector<int>> rotateClockwise90(const vector<vector<int>>& x)
{
    vector<vector<int>> result;

    for (unsigned i = 0; i < x[0].size(); i++) {
        vector<int> row;
        for (int j = x.size() - 1; j >= 0; j--) {
            row.push_back(x[j][i]);
        }
        result.push_back(row);
    }

    return result;
}

Rotating counterclockwise:

vector<vector<int>> rotateCounterclockwise90(const vector<vector<int>>& x)
{
    vector<vector<int>> result;

    for (int i = x[0].size() - 1; i >= 0; i--) {
        vector<int> row;
        for (int j = 0; j < x.size(); j++) {
            row.push_back(x[j][i]);
        }
        result.push_back(row);
    }

    return result;
}

Live demo

Upvotes: 1

asmmo
asmmo

Reputation: 7090

By looking to it well, you can conclude that it's similar to the ordinary transpose with rows in a reverse order, hence you can use something like what follows

#include <vector>
#include <iostream>

auto rotate(const std::vector<std::vector<int>>& mat){
    std::vector<std::vector<int>> toBeReturned (mat[0].size(), std::vector<int>(mat.size()));
    for(size_t i{}; i < toBeReturned .size(); ++i){
        for(size_t j{}; j < toBeReturned[0].size(); ++j){
            toBeReturned[i][j] = mat[j][mat[0].size()-1-i];
        }
    }
    return toBeReturned;
}

int main() {
    std::vector<std::vector<int>> cherry = {{0,4},
                                  {4,4},
                                  {4,0}};
    auto rotated = rotate(cherry);
    for(size_t i{}; i < rotated.size(); ++i){
        for(size_t j{}; j < rotated[0].size(); ++j){
            std::cout << rotated[i][j] << " ";
        }
        std::cout << "\n";
    }

}

Live

Upvotes: 1

Related Questions