Algorithm

Hi all,

I am trying to build a battleship program. However, I couldnt figure out the right way to run my algorithm to randomly place ships on the grid. Here's my code, any kind soul willing to 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 <cstdlib>
#include <iostream>
#include <time.h>
#include "Computer.h"

using namespace std;

void Computer::arrangeShips()
{
    int x, y, dir;
    int shipLength[5] = {5, 4, 3, 3, 2};
    string shipType[5] = {"Aircraft Carrier", "Battleship", "Destroyer", "Submarine", "Patrol Boat"};

    enum position
    {
        OPEN, AIRC, BATT, DEST, SUBM, PATR
    };
    
    position grid[8][8];
    
    //loop to initialize all to zero
    for(int i=0; i<8; i++)
    {
        for(int j=0; j<8; j++)
        {
            grid[i][j] = OPEN;
        }
    }
   
    //loop to load 5 ships
    for(int a=0; a<5; a++)
    {
        srand(time(NULL));
        x = rand() % 8;
        y = rand() % 8;
        dir  = rand() % 4;

        int length = shipLength[a];
        string type = shipType[a];
you need to call srand() only once at the very beginning of your program, otherwise you will get always the same values until time() provides a new second
Hi coder777,

thanks for your tip. I will take not of this.
Topic archived. No new replies allowed.