Skip to content

Instantly share code, notes, and snippets.

@Ino4137
Last active April 12, 2018 20:41
Show Gist options
  • Select an option

  • Save Ino4137/dc598e312664c46a4e7f837662c97231 to your computer and use it in GitHub Desktop.

Select an option

Save Ino4137/dc598e312664c46a4e7f837662c97231 to your computer and use it in GitHub Desktop.
Solution Haskell
import Data.List
import Data.Function
import Control.Monad
import Text.Printf
data Tree a =
Leaf | Unary a | Node (Tree a) a (Tree a)
deriving (Eq, Show)
data From = F | B deriving (Eq, Show)
excerciseTree :: Tree Int
excerciseTree = Node (Node (Node Leaf 9 (Unary 4)) 5 Leaf) 2 (Node (Node (Unary 11) 6 (Unary 5)) 7 (Unary 2))
collectLayers :: Int -> Tree Int -> [(Int, Int)]
collectLayers n Leaf = []
collectLayers n (Unary x) = [(n, x)]
collectLayers n (Node l x r) = [(n, x)] : collectLayers (n+1) l ++ collectLayers (n+1) r
prepareToPrint :: [(Int, Int)] -> [[(Int, Int)]]
prepareToPrint = reorder F . groupBy groupingFoo . sortBy sortingFoo
where
sortingFoo = compare `on` fst
groupingFoo = (==) `on` fst
reorder _ [] = []
reorder F (x:xs) = reverse x : reorder B xs
reorder B xs = last xs : reorder F (init xs)
prepSpiral :: [[(Int, Int)]] -> [Int]
prepSpiral = fmap snd . join
printSpiral :: IO ()
printSpiral = mapM_ (printf "%d ") $
prepSpiral . prepareToPrint $ collectLayers 0 excerciseTree
@Ino4137
Copy link
Author

Ino4137 commented Apr 11, 2018

Ohayo!

  1. My guess is that as the number of elements increases, the more in favor of the single-IO-version. About the $ after mapM_... Yeaaaah it
    could be a . but that would feel off... You've noticed, my intent with that was to separate IO from processing visually.

  2. OwO spooked

For it to reach 37/37 it would have to be entirely type-level. (one day I will wield that power.... )

@Antystenes
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment