Function to generate random row/column position in 2d array

Hey all, So currently, I am trying to create a bool function, passing in two-dimensional array and the size. This function will generate a random row/ column position and then attempt to place an enum at that row-column position on the board. However, I am really stuck on what to do. I have my arrays and my random number generator, but I don't know how to go about combining them to place data inside random arrays without repeating them.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

// How do I generate a random position here and add data, then 
//return (true or false) so that if it is false (There is already data in that position),
// randomize location again and try to place data on that position

//numberOfMines is user input so that it will only try to put data x amount of time 
//(between 5-10)

bool checkMine(Symbols symbolArr[][COLS], int size, int numberOfMines);
{
      srand(time(NULL));


}



Any help would be appreciated. I am completely lost.
Last edited on
To choose a random location in an NROWSxNCOLS grid, either:
a. randomly choose a row in [ 0, NROWS-1 ] and a column in [ 0, NCOLS-1 ] or
b. choose a single random position from [ 0, NROWS*NCOLS-1 ] (and compute its row and col)

Favour using facilities in <random> http://en.cppreference.com/w/cpp/numeric/random

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <random>
#include <tuple>

// return a random position - pair (row,col) - in an NROWSxNCOLS matrix
std::pair< std::size_t, std::size_t > random_location( std::size_t NROWS, std::size_t NCOLS )
{
    static std::mt19937 rng( std::random_device{}() ) ;

    // if( NCOLS == 0 ) throw std::invalid_argument ...
    std::size_t pos = std::uniform_int_distribution<std::size_t>{ 0, NROWS*NCOLS-1 }(rng) ;
    return { pos/NCOLS, pos%NCOLS } ;

    // or alternatively
    using distrib = std::uniform_int_distribution<std::size_t> ;
    return { distrib{0,NROWS-1}(rng), distrib{0,NCOLS-1}(rng) } ;
}

http://coliru.stacked-crooked.com/a/b369d6eeb616baef
I am new to c plus plus so idon't understand most of whats going on in that code. I am trying to create a bool function, passing in two-dimensional array and the size. This function will generate a random row/ column position and then attempt to place an enum at that row-column position on the board.

How would I do that?
Topic archived. No new replies allowed.