|
-
Apr 30th, 2002, 06:12 PM
#1
Thread Starter
New Member
C++help
hi guys,
I'm writing an algorithm that will search a two dimensional array for ships. The array will be a char array initialized with two character values-the value '~' to represent water, and the value 'x' to represent a square occupied by a ship.The code below initializes an array that represents the grid in the diagram. It contains five ships.
const int Size = 6;
char ocean[Size][Size] = {
{‘~’, ‘~’, ‘x’, ‘x’, ‘~’, ‘x’},
{‘x’, ‘~’, ‘~’, ‘~’, ‘~’, ‘x’},
{‘x’, ‘~’, ‘x’, ‘x’, ‘~’, ‘x’},
{‘x’, ‘~’, ‘~’, ‘~’, ‘~’, ‘x’},
{‘~’, ‘~’, ‘~’, ‘~’, ‘~’, ‘~’},
{‘~’, ‘x’, ‘x’, ‘x’, ‘x’, ‘~’},
};
It should print a sentence for each ship it finds. The output should contain the length of the ship.
a.out
Found a ship, its length is 2.
Found a ship, its length is 4.
Found a ship, its length is 3.
Found a ship, its length is 2.
Found a ship, its length is 4.
_________________________________________________
If my program encounters an array that is initialized with data that violates any of the rules it should print "Invalid Ship Placement." and then terminate.
can you please help me with this
i have no clue
int i, j;
int ship, length;
for (i = 0; i < Size; i++)
{
/*
** Check if the ship flag is set, if it
** is it has to be reset becuase otherwise two rows
** like this would count as one ship
** ~~~x~xx
** xx~~~x~
*/
if (ship == -1) {
printf("Found a ship, length %d\n", length);
ship = 0;
length = 0;
}
}
for (j = 0; j < Size; j++) {
/*
** Is it an 'x', if it is we check if the ship flag
** is set and increase length.
*/
if (ocean[j] == 'x') {
if (ship == 0)
ship = -1;
length++;
/*
** If it's not an 'x' and the ship flag is set it
** means that the last array element was an 'x' and
** now we need to reset the ship flag and print the
** ship length
*/
}
}
if (ship == -1) {
printf("Found a ship, length %d\n", length);
ship = 0;
length = 0;
}
}
thanks
bina
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|