I'm trying to fill the array horizontally alternately such as:
My default ArrayFill function is :
void fillArray(std::array<std::array<int, maxColumns>, maxRows> & array, size_t rows, size_t columns)
{
if (rows == 0 || rows > maxRows || columns == 0 || columns > maxColumns)
throw std::invalid_argument("Invalid array size.");
int value = 1;
for (size_t row = 0; row < rows; row)
for (size_t column = 0; column < columns; column)
array[row][column] = value ;
}
How can I change the implementation that will fill the array horizontally?
- UPDATE -
I tried the suggested solution and here is the result:
-- FINAL -- ( IT WORKS PERFECTLY )
CodePudding user response:
there are two properties which you should obey:
- start filling not from top (row=0) but bottom (row=rows-1)
- each row (from bottom to top) changes the order of columns
so, finally it can look like this:
int value = 1;
int colOrder = 1; // 1 means from left to right, 0 from right to left
for (size_t row = 0; row < rows; row) {
for (size_t column = 0; column < columns; column)
array[rows - 1 - row][colOrder ? column : (columns - 1 - column)] = value ;
colOrder ^= 1; // change column order
}