A
A
Alexander2020-11-17 22:12:33
C++ / C#
Alexander, 2020-11-17 22:12:33

How to fill a matrix (two-dimensional array)?

Task: fill the matrix (two-dimensional array) with the values ​​of the vector b1, b2,...,b81 from the center in a spiral (left-down-right-up).
5fb41e73e077b011196362.png
Note: the figure shows the index values!
I wrote a code that just fills the matrix in the normal way:

#include <iostream>
using namespace std;

int main()
{
  const int rows = 9;
  const int cols = 9;
  int ARR[rows][cols];

  for (int i = 0; i < rows; i++)
  {
    for (int j = 0; j < cols; j++)
    {
      ARR[i][j] = rand() % 10;
    }
  }

  for (int i = 0; i < rows; i++)
  {
    for (int j = 0; j < cols; j++)
    {
      cout << ARR[i][j] << "  ";
    }
    cout << endl;
  }
}

How can I make the indexes of the elements increase from the center in a spiral (as shown in the figure)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ananiev, 2020-11-18
@SaNNy32

Find the index - the center of the matrix. Shift the index to the left by one. Then down one. Then right one. Then up two. Then left two. Etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question