Hey guys, I'm trying to make a function that fills a 2D array of 3 rows and 3 cols with random numbers from 1 - 9.
I thought I had the right idea however when I run my code, nothing appears in the console.
I've tried removing the statement "repeat = true" after the while loop ends, and it will randomly add the number 1 to a random position. I want to do this for the numbers 1 - 9.
void fillArr(int arr[][3])
{
srand(time(0));
bool repeat = true;
for (int i = 0; i < 9; i++)
{
//keep generating a random position until it is found to be blank i.e. = 0
while (repeat)
{
int row = rand() % 3 + 1;
int col = rand() % 3 + 1;
//if the position is free, make the position = the index (1-9)
if (arr[row][col] == 0)
{
arr[row][col] = i + 1;
repeat = false; //exit while loop
}
}
//make repeat = true so once the for loop iterates again (to i = 1, i = 2 etc) //the while loop will occur
repeat = true;
}
}
void printArr(int arr[][3])
{
for (int row = 0; row < 3; row++)
{
for (int col = 0; col < 3; col++)
{
std::cout << arr[row][col] << " ";
}
std::cout << "\n";
}
}
int main()
{
int data[3][3] = { 0 }; //initialising all components of array to zero
fillArr(data);
printArr(data);
return 0;
}
int row = rand() % 3 + 1;
int col = rand() % 3 + 1;
to
1 2
int row = rand() % 3;
int col = rand() % 3;
Each row or column index goes from 0 to 2, not 1 to 3 as you have at present. If you write beyond array bounds you will experience truly 'random' behaviour!
Just a thought: if you are filling 9 slots with 9 numbers you might like to consider the algorithm shuffle instead.