Potholes
May 11, 2021
Today’s exercise comes from one of those online code exercises, via Stack Overflow:
There is a machine that can fix all potholes along a road 3 units in length. A unit of road will be represented by a period in a string. For example, “…” is one section of road 3 units in length. Potholes are marked with an “X” in the road, and also count as 1 unit of length. The task is to take a road of length N and fix all potholes with the fewest possible sections repaired by the machine.
The city where I live needs one of those machines.
Here are some examples:
.X. 1 .X...X 2 XXX.XXXX 3 .X.XX.XX.X 3
Your task is to write a program that takes a string representing a road and returns the smallest number of fixes that will remove all the potholes. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
potholes = go 0
where
go n (‘X’:rest) = go (n+1) (drop 2 rest)
go n (_:rest) = go n rest
go n [] = n
My first solution was almost identical to the one by
@programmingpraxis so I omit it here and instead include, mostly for
chuckles, a “one-liner” using that often-used and -misused hammer,
regular expressions, in particular as implemented in the irregex
library.
A solution in Racket.
Here’s a solution in C.
Example usage: