Kevin Reid (kpreid) wrote,
Kevin Reid

Tile flipping in Haskell

I wanted a little bit of assistance with a tile-flipping puzzle, so I wrote this little bit of almost-Haskell code.

let zero = replicate 4 $ replicate 4 $ False
let gshow g = putStrLn $ unlines [[if v then '#' else '.' | v <- r] | r <- g]
let flips = [(-1,0),(0,0),(1,0),(0,-1),(0,1)]
let gflip (x,y) g = [ [ ((vi-x,ri-y) `elem` flips) /= v | (v,vi) <- zip r [0..]] | (r,ri) <- zip g [0..]]
let grid l = foldr gflip zero l

It doesn't compute solutions given a puzzle; rather, it shows the result of a series of flips.

Prelude> gshow $ grid [(1,1)]

Prelude> gshow $ grid [(2,0),(1,2),(2,3)]

I tried a version using 2-dimensional arrays instead of lists, but gshow and gflip turned out uglier than they already are. Suggestions welcome.

Tags: haskell, programming, programs
  • Post a new comment


    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.