This is the forty seventh part of the ILP series. For your convenience you can find other parts in the table of contents in Part 1 – Boolean algebra

Today we are going to solve Battleship puzzle. It is very similar to nonograms which we already solved so let’s start with the code:

Application is pretty obvious. First, we create collections of numbers representing how many fields are occupied in row or column. Next, we crate tuples describing ships: first tuple element indicates ship length (or type), second element indicates how many ships of that type we need to place on the board.

Next, for every field we create a binary variable indicating whether that field is occupied or not.

Next, we want to place each type of ships on the board. We iterate over types, over rows, and over columns. For every field we check whether it is theoretically possible to place ship horizontally (so leftmost piece of ship is in the current field). We simply sum variables which would create the ship and make sure that neighboring variables are zero. For vertical assignment we perform similar checks. Finally, we make sure that there are enough ships of the type on the board.

Next, we add two loops to make sure that number of marked fields matches board requirements (defined at the beginning). Finally, we solve the problem and print the result. That’s all.