//
// data structures definitions
//
constint FLEET_SIZE=5; // number of battleships
constint FIELD_SIZE=5; // the field (ocean) is FIELD_SIZExFIELD_SIZE
// coordinates (location) of the ship and shots
struct location{
int x; // 1 through FIELD_SIZE
char y; // 'a' through FIELD_SIZE
};
// contains ship's coordinates (location) and whether is was sunk
struct ship{
location loc;
bool sunk;
};
//
// initialization functions
//
void initialize(ship[]); // places all ships in -1 X location to signify
// that the ship is not deployed
location pick(void); // generates a random location
bool match(ship, location); // returns true if this location matches
// the location of the ship
// returns false otherwise
int check(const ship[], location); // returns the index of the element
// of the ship[] array that matches
// location. Returns -1 if none match
// uses match()
void deploy(ship[]); // places an array of battleships in
// random locations in the ocean
void deploy(ship s[])
{
int e = 0;
int i = 0;
ship temp;
temp.loc = pick();
s[i].loc = temp.loc;
i++;
while (i < FLEET_SIZE)
{
temp.loc = pick();
e = check(s, temp.loc);
if (e == -1)
{
s[i].loc = temp.loc;
i++;
}
}
}
Line 26: will always be true.
code you probably want:
1 2 3 4 5 6 7 8 9
void deploy(ship s[])
{
location l = pick()
for(int i = 0; i < FLEET_SIZE; ++i){
while(check(s, l) != -1)//Make sure that chosen
l = pick(); //location will be free
s[i].loc = l;
}
}