Potholes
May 11, 2021
It is wrong to predefine the three-unit lengths of road where the pothole fixing machine can set up. Our solution scans until it finds a pothole, fixes that pothole plus any potholes in the next two units of road, then begins rescanning at the third subsequent unit of road:
(define (potholes str) (let ((len (string-length str))) (let loop ((i 0) (fixes 0)) (cond ((<= len i) fixes) ((char=? (string-ref str i) #\X) (loop (+ i 3) (+ fixes 1))) (else (loop (+ i 1) fixes))))))
> (potholes ".X.") 1 > (potholes ".X...X") 2 > (potholes "XXX.XXXX") 3 > (potholes ".X.XX.XX.X")
You can run the program at https://ideone.com/XueE9y.
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: