The algorithm is to generate random x, y coordinates, choose the length you need, randomize direction (0 for horizontal, 1 for vertical or vice versa) and if you can, place the ship at the chosen location. If you can't keep randomizing x,y and dir until you succeed.
If you try to place many ships on a small board, you would need a smarter algorithm though. Make sure that the board is large enough so that the ships can be placed anywhere.
Lets say your grid is 10*10
int grid[100];
Now you need the following functions:
1 2
|
bool is_valid_location(int x, int y, int length, int direction, int grid[]);
void place_ship(int x, int y, int length, int direction, int grid[]);
|
The first one doesn't modify grid, only tells you whether you can place a ship at that location. This function should have a for loop that checks the tiles form [x][y] to either [x+length][y] or [x][y+length] depending on direction.
The second one has the same loop, but this time actually sets the grid values to something.
You'll have some problems with preventing adjacent ships (I think there is a rule about that..?). To solve it, make place_ship mark all the tiles around a ship with a special value that would be recognized by is_valid_location as unavailable.
Note that these two functions will be needed by both human and computer players.