Garey Fleeman
Garey Fleeman

Reputation: 1

Battleship Probability Grid

I'm trying to make a function for my battleship program to create a probability grid of all the places any of the remaining pieces could be in. I would like the grid to loop through the entire array, then check if at that point the object has room to be placed (either horizontally, or vertically) and add one to each point it will cover, showing me which coordinates have the best probability of having a ship on them. BS_GRID_ROWS and BS_GRID_COLS both values holding the size of the battleship board, matrix is the array I would like to display my probability values, and hits is an array with a number (corresponding to each ship) greater than zero if a ship's been hit, -1 if I shot and missed, and zero if the no shot has been made at that coordinate. Here's the code I have so far. It's working but not correctly it misses a few squares towards the end completely which I know isn't possible when I run it before any ships have been placed. Any help would be appreciated. Thanks

void
probabilityGrid(int matrix[BS_GRID_ROWS][BS_GRID_COLS], int hits[BS_GRID_ROWS][BS_GRID_COLS], int shipSize)
{
    bool isValid=true;

   for (int row = 0; row< BS_GRID_ROWS; row++)
   {
       for (int col = 0; (col+shipSize) <BS_GRID_COLS; col++)
       {
           for (int hold = col; hold < shipSize; hold++)
           {
               if (hits[row][hold]!=0)
                isValid=false;
           }
           if (isValid)
           {
               for (int hold = col; hold < shipSize; hold++)
               {
                  matrix[row][hold]++;
               }

           }
           isValid=true;
        }
    }
    //For now I'm just working on the horizontal part of the algorithm.
}

Upvotes: 0

Views: 684

Answers (1)

Anton Savin
Anton Savin

Reputation: 41331

Imagine (or better set and run through debugger) BS_GRID_ROWS == 1, BS_GRID_COLS == 1, and shipSize == 1.

What happens is that the condition (col+shipSize) <BS_GRID_COLS is false even if col == 0 which is probably not what you want, and you should change it to col + shipSize <= BS_GRID_COLS.

For the same reason, you should change row<=BS_GRID_ROWS-shipSize-1 to row + shipSize <= BS_GRID_ROWS.

Upvotes: 1

Related Questions