I'm very new to C++ and have a pretty daunting assignment due this week. I won't get into too much detail about it as I don't want work done for me, but can anyone point me in the right direction as to how I would go about picking random characters from a multi-dimensional string array?
The goal is to print out a 4x4 board of these characters, picking one random character from each array at the start of every game so not one board is the same.
Any advice/tips on how to do this would be greatly appreciated-- thank you!
Generate a random number from 0-15 for the outer array.
Generate a random number from 0-5 for the inner array.
Select the character at that array index.
#include <iostream>
#include <random>
#include <ctime>
int main()
{
constexprint outer_size = 16;
constexprint inner_size = 6;
char game[outer_size][inner_size] = { /* ... */ };
// filling with 'A' just for example
for (int i = 0; i < outer_size; i++)
for (int j = 0; j < inner_size; j++)
game[i][j] = 'A';
std::mt19937 gen(time(nullptr)); // random number generator, seeded based on current time
// Used to generate a random number in specific range [a, b]:
std::uniform_int_distribution<int> random_outer(0, outer_size - 1); // inclusive range!
std::uniform_int_distribution<int> random_inner(0, inner_size - 1);
int index_outer = random_outer(gen); // generate the random outer index
int index_inner = random_inner(gen); // generate the random inner index
// print the value
std::cout << game[index_outer][index_inner] << '\n';
}
This worked and now picks a random character from the arrays-- thank you!
I'm assuming some funky for loop has to come into play, but I'm having trouble working out a solution to now print one of these characters from EACH of the 16 arrays. I essentially need to take one random character from all 16 and implement them into a word game.
Would I have to put the generators (random_outer & random_inner) in a loop to generate 16 different indices?
It looks to me like you trying to simulate the game Boggle.
The suggestions above show you how to get random numbers. For a beginner, I'm not sure they provide any benefit over srand() and rand().
If this is the Boggle game, the issue you have is that each die must be used 1 time. So, you need to do the following:
Randomize the order of the die indices (0 - 15). So you will have an array like :
i[0]= 12
i[1] = 0
i[2] = 7
etc.
Each array element is the outer index into the gameZero array.
Now you want to map the i array onto your game board. Each element of i now points to a die from gameZero. Randomize the side of the die, and place the resultant letter into your game board.
Something like this (not tested):
1 2 3 4 5 6 7 8 9
for (row = 0; row < 4; ++row)
{
for (col = 0; col < 4; ++col)
{
int side = rand() % 6;
int dieIndex = i[(row * 4) + col];
game[row][col] = gameZero[dieIndex][side];
}
}