I have a task which is creating an Dungeon Escape game, based on a 4x4 array. I first have to create 3 different postion for E(Exit),K(Key) and P(Player). How can I random those 3 in 3 different position in an array ? EDIT: I meant I need to find a way to random 3 DIFFERENT POSITION the neatest way. I already know about the rand() and srand thing.
Asked
Active
Viewed 122 times
-5
-
4Please do some research before asking questions here. You can simply google these kind of things and get your results. – Amrit Singh Jun 17 '18 at 11:42
-
you can read about rand function in c++ and as you working with array you know the range of index of array So simply generate random index of row and column for array values. – sitaram chhimpa Jun 17 '18 at 13:23
1 Answers
0
Try to use rand
function which is used to generate random number.
First of all you need to initialize random seed with srand(time(NULL))
.
myRandomNum = rand() % 4;
generate number between 0 and 3.
So, you can generate two number which would represent row index and column index and repeat that three times for: E
(exit), K
(key) and P
(Player).

Nenad
- 119
- 1
- 12
-
3Initializing seed from current time is bad idea, because it's only updated once a second. Cleaner approach is to use [C++11 random](https://stackoverflow.com/a/19666713/767632). – yeputons Jun 17 '18 at 11:48
-
A) You probably want `rand() % 4;`, since OP has 4x4 array. B) You should say something about making sure the positions you get from `rand()` are *different*. – HolyBlackCat Jun 17 '18 at 11:54
-
myRandomNum = rand() % 3; generate number between 0 and 3. Is it typo or wrong concept as this will only give number in range from 0 to 2 – sitaram chhimpa Jun 17 '18 at 13:25
-
You should use the things provided in the C++ `
` header, instead of using outdated and bad C functions. – eesiraed Jun 17 '18 at 18:44 -
wait I meant I need to find a way to random 3 DIFFERENT POSITION the neatest way. I already know about the rand() and srand thing. – Vũ Nguyễn Jun 19 '18 at 03:34