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.")
> (potholes ".X...X")
> (potholes "XXX.XXXX")
> (potholes ".X.XX.XX.X")

You can run the program at https://ideone.com/XueE9y.

Pages: 1 2

3 Responses to “Potholes”

  1. Iulia said

    potholes = go 0
    go n (‘X’:rest) = go (n+1) (drop 2 rest)
    go n (_:rest) = go n rest
    go n [] = n

  2. chaw said

    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

    (import (scheme base)
            (scheme write)
            (chibi irregex))
    (define samples ; ((input . output) ...)
      '((".X." . 1)
        (".X...X" . 2)
        ("XXX.XXXX" . 3)
        (".X.XX.XX.X" . 3)
        ("" . 0)
        (".........." . 0)
        (".........X" . 1)))
    (define (pothole-filling-sections/re str)
      (length (irregex-extract '(seq "X" (** 0 2 any)) str)))
    (display (equal? (map cdr samples)
                     (map pothole-filling-sections/re (map car samples))))

  3. r. clayton said

    A solution in Racket.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: