Embercode
✕
ArraysQuick quiz

Matrix moves

8 questions. Covers Spiral traversal.

Questions 1 to 5 of 8

  1. 1. What does this program print? ``cpp #include <algorithm> #include <iostream> #include <utility> #include <vector> using namespace std; using Matrix = vector<vector<int>>; void transpose(Matrix& m) { size_t n = m.size(); for (size_t i = 0; i < n; ++i) { for (size_t j = i + 1; j < n; ++j) { swap(m[i][j], m[j][i]); } } } void reverse_each_row(Matrix& m) { for (auto& row : m) { ranges::reverse(row); } } int main() { Matrix m = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; reverse_each_row(m); transpose(m); cout << m[0][0] << " " << m[0][1] << " " << m[0][2] << " " << m[0][3] << "\n"; } ``
  2. 2. What does this program print? ``cpp #include <iostream> #include <utility> #include <vector> using namespace std; int main() { vector<vector<int>> m = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; for (size_t i = 0; i < 3; ++i) { for (size_t j = i + 1; j < 3; ++j) { swap(m[i][j], m[j][i]); } } cout << m[0][1] << " " << m[1][2] << " " << m[2][0] << "\n"; } ``
  3. 3. What does this program print? ``cpp #include <iostream> #include <vector> using namespace std; vector<int> spiral(const vector<vector<int>>& g) { vector<int> out; int top = 0; int bottom = static_cast<int>(g.size()) - 1; int left = 0; int right = static_cast<int>(g[0].size()) - 1; while (top <= bottom && left <= right) { for (int c = left; c <= right; c++) { out.push_back(g[top][c]); } top++; for (int r = top; r <= bottom; r++) { out.push_back(g[r][right]); } right--; if (top <= bottom) { for (int c = right; c >= left; c--) { out.push_back(g[bottom][c]); } bottom--; } if (left <= right) { for (int r = bottom; r >= top; r--) { out.push_back(g[r][left]); } left++; } } return out; } int main() { vector<vector<int>> g = {{1, 2, 3}, {4, 5, 6}}; vector<int> v = spiral(g); cout << v[3] << " " << v[4] << " " << v[5] << "\n"; } ``
  4. 4. Put the steps of a clockwise turn of a square grid in the order the code runs them.

    Use the arrows to put the steps in order.

    1. 1.Swap m[i][j] with m[j][i] for every j greater than i
    2. 2.Reverse the values in each row
    3. 3.Check that every row has as many values as there are rows
  5. 5. Put the steps of one pass of the spiral walk in order, when all four sides are still unvisited.

    Use the arrows to put the steps in order.

    1. 1.Walk the right side from top to bottom, then move right left by one
    2. 2.If left <= right, walk the left side from bottom to top, then move left right by one
    3. 3.If top <= bottom, walk the bottom side from right to left, then move bottom up by one
    4. 4.Walk the top side from left to right, then move top down by one

3 question(s) left on this page.