Created
May 31, 2018 16:03
-
-
Save hedgehog1024/8ebbd63418ab1110b750df3d79b776b2 to your computer and use it in GitHub Desktop.
An efficient (I guess) way to create a spiral in haskell as list of lists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cons = (:) | |
baseSeed = | |
[[1, 1, 1, 1, 1] | |
,[0, 0, 0, 0, 1] | |
,[1, 1, 1, 0, 1] | |
,[1, 0, 0, 0, 1] | |
,[1, 1, 1, 1, 1]] | |
baseSpiral = map (foldr (.) id) . map (map cons) $ baseSeed | |
spiralize :: Int -> [[Int]] | |
spiralize n = map ($ ([] :: [Int])) . map (spiralRow n) $ [1..n] | |
where | |
atEnd n i = i == 1 || i == n | |
spiralRow size row | |
| size < 5 = error "spiralize: size is too small" | |
| size `rem` 2 == 0 = error "spiralize: size is even" | |
| size == 5 = baseSpiral !! (row - 1) | |
| otherwise = | |
if atEnd size row | |
then foldr (.) id $ replicate size (cons 1) | |
else | |
if row == 2 | |
then (foldr (.) id $ replicate (size - 1) (cons 0)) . cons 1 | |
else | |
if row == size - 1 | |
then cons 1 . (foldr (.) id $ replicate (size - 2) (cons 0)) . cons 1 | |
else cons 1 . cons corner . spiralRow (size - 4) (row - 2) . cons 0 . cons 1 | |
where | |
corner = if row == 3 then 1 else 0 | |
charify i = case i of | |
1 -> '#' | |
0 -> ' ' | |
_ -> error "Impossible!" | |
pretty = unlines . map (map charify) | |
main = putStrLn . pretty $ spiralize 205 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment