Reputation:
There is a two dimensional array with 9 rows and 9 columns (81 elements). The task is to fill this array in a spiral way: from center to the left, then down, then to the right, then up. Just like shown here. Notice: the numbers on the picture are indexes of elements!
How to do that? I only know how to fill an array in this way (first fill all columns of the first row, then all columns of the second row and so on):
#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;
}
}
So how can I do this task: to fill an array in a spiral way?
Upvotes: 2
Views: 317
Reputation: 148880
There is no simple way. Here is an algorithm that changes the direction as soon as possible, starting left, and stops when going out of the array:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
// use constexpr to have true constants
constexpr const int rows = 9;
constexpr const int cols = 9;
int ARR[rows][cols];
// Initialize the array to 0 values to detect unmodified slots
for (int (&row)[cols]: ARR) {
for (auto &val: row) {
val = 0;
}
}
// Use symbols for directions
enum Dir {
left = 0,
down,
up,
right,
} dir = left;
// Define the starting point and starting value
int x = rows / 2;
int y = cols / 2;
int val = 1;
// A flag to know when to stop
bool stop = false;
// Let's go...
for (;;) {
ARR[x][y] = val++;
switch (dir) {
case left:
y -= 1;
if (y < 0) stop = true;
else if (ARR[x+1][y] == 0) dir = down;
break;
case down:
x += 1;
if (x > rows) stop = true;
else if (ARR[x][y+1] == 0) dir = right;
break;
case right:
y += 1;
if (y >= rows) stop = true;
else if (ARR[x-1][y] == 0) dir = up;
break;
case up:
x -= 1;
if (x < 0) stop = true;
else if (ARR[x][y-1] == 0) dir = left;
}
if (stop) break;
}
// Display the values
for (int (&row)[cols]: ARR) {
for (auto val: row) {
cout << setw(3) << val;
}
cout << '\n';
}
return 0;
}
Upvotes: 1