ILP Part 91 — Golf

This is the ninetieth first 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 the Golf riddle. We are playing golf on a piece of paper. We have numbers indicating fields where we start putts. A number tells us how long the shot was. It cannot end on a blocked field (indicated as blue water). If the putt didn’t get to the final point then we carry on with a shot of a length decreased by one. The next shot cannot go backwards.

Let’s start with our board representation:

Letters D indicate destinations. Letters X indicate water. Digits shows starting points.

The solution is:

We will solve this by emulating shots.

First, we assign three state variables to each field (lines 4-6): whether a field was used in any shot, whether it is a final destination, and whether it is blocked (water>

Next, we iterate over the board and when we find a starting point (line 11) we do the magic.

We start with initializing the state. We’ll get a random direction for the putt and then mark all fields as used. So our initial direction (lines 12-13) is null. We’ll also keep a flag if we continue or not (line 14).

We also need to keep a track of where we are (lines 16-18).

We start making shots. As long as we can take a shot (line 21) we calculate new direction lines 22-27) and also make a chocie whether we move or not (line 28).

Next, we make sure that the shot goes either horizontal or vertical (30-36) and also that it doesn’t go backwards (37-45).

Now, we take fields one by one (lines 47-53) and mark them as used. We first get the existing flag of the field (line 55-58) and make sure it was set to “not used” previously. Next, we update it to “used” (lines 60-64).

The shot cannot land in the water so we make sure of that in lines 67-70.

Finally, after all shots we make sure that we ended in the final position (78-81).

Output: