How to randomly pick a cordinate in a 2D array?

Hi,
I'm trying to make a simplified version of the Battleship game. I have an 2D array with 4x4 coloumms. I wanna randomize a cordinate (like 4:1 or 2:3) in the array so that the user can try and find the right cordinate from guessing. But I can't figure out how to randomly select one cordinate in a array?

plz help!
Are you aware of how to get one random number?
Yeah, at least with srand? But cant get that to work with 2D...
Last edited on
@alext

Just use two variables. One for row, and one for column, and use that for the array position.
1
2
3
int row = rand()%4;
int col = rand()%4;
myarray[row][col]= // whatever goes in your array 

Ok I'm halfway to crazy right now! Can't get this s*%t to work. The thought is to create an 2d vector where something is hidden on a cordinate. The user will then guess on where its hidden. If its wrong the console will display were the user guessed and offer a new try. If the user is right the console while display this and tell the user how many tries it took.

I cant figure how to display the array as :

0 1 2 3 4
1
2
3 *
4 *
in this example the user have guessed on 4/1 and 3/1 wich was wrong.
But I cant find a way to print the 2d array with the positions that have been guessed on?
attaching the code
plz help =(

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
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <ctime>
using namespace std;

int main ()
{
int row = rand()%4;
int col = rand()%4;

while (true)
{
int rounds = 1;

int gameBoard [row][col];


int y;
int x;
cout << "==NEW SHOT!==" << endl;
rounds++;
cout << "Place your shot on the y-axle ";
cin >> y;
cout << "Place your shot in the x-axle: ";
cin >> x;


if (y == row && x == col)
{
	cout << "*HIT*" << endl;
	cout << "It took u " << rounds << " tries. Well done!";
	return false;
}
}
cin.get ();
return 0;

}
Last edited on
do i understand this right?

you want a 2d array with a defined size, you set this size and it's not random. inside this array you randomly pick 1 element and let the user guess which one.
Last edited on
yes exactly!
this wont compile, but should give you an idea

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int main()
{
    int GameBoard[4][4] = {0,0,0,0....,0};
    int row = rand()%4;
    int col = rand()%4;
    GameBoard[row][col] = 1;
    int rounds = 0;

   bool element_found = false;
   
   while(element_found == false)
   {
       rounds++;
       cin >> row;
       cin >> col;
      if(GameBoard[row][col] == 1) {element_found = true;}
   }
}



the problem with your code is:
- the gameboards size is random
- your while loop is always true
Last edited on
ok cool, thanks!
Topic archived. No new replies allowed.