Randomly fill 2D array with numbers

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.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
  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;
}
Last edited on
using std::generate() with the (newer) random library:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <random>
#include <vector>
#include <chrono>
#include <algorithm>

constexpr auto SIZE = 3;
constexpr auto low_bound = 1;
constexpr auto up_bound = 9;

int main()
{
    auto seed = std::chrono::system_clock::now().time_since_epoch().count();//seed
    std::default_random_engine dre(seed);//engine
    std::uniform_int_distribution<int> di(low_bound,up_bound);//distribution

    int myArray [SIZE][SIZE];
    for (size_t i = 0; i < SIZE; ++i)
    {
        std::generate(myArray[i], myArray[i] + SIZE, [&]{ return di(dre);} );
    }
    //http://en.cppreference.com/w/cpp/algorithm/generate
    for (size_t i = 0; i < SIZE; ++i)
    {
        for (size_t j = 0; j < SIZE; ++j)
        {
            std::cout << myArray[i][j] << " ";
        }
        std::cout << "\n";
    }
}
@schmiischmoo,

Change your lines 11 and 12 from
1
2
			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.
Topic archived. No new replies allowed.