Skip to content

Instantly share code, notes, and snippets.

@tfausak
Created June 16, 2014 02:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tfausak/4401ef0b43b5c1db0570 to your computer and use it in GitHub Desktop.
Save tfausak/4401ef0b43b5c1db0570 to your computer and use it in GitHub Desktop.
Difference between blog post and Hs2048.
import Data.List (group)
import Data.Maybe (isJust)
import Data.Monoid ((<>))
empty :: Int -> [Maybe Int]
empty = flip replicate Nothing
shift :: [Maybe Int] -> [Maybe Int]
shift v = take n (v' <> empty n)
where
n = length v
v' = group (filter isJust v) >>= go
go (Just a : Just b : ts) = Just (a + b) : go ts
go ts = ts
main :: IO ()
main = print $ shift $ replicate 4 $ Just 2
-- [Just 4,Just 4,Nothing,Nothing]
import Data.Maybe (catMaybes)
import Data.List (group)
add :: [Int] -> [Int]
add (x : y : rest) = x + y : rest
add ts = ts
pad :: [a] -> a -> Int -> [a]
pad xs x n = take n (xs ++ repeat x)
shift :: [Maybe Int] -> [Maybe Int]
shift v = pad ts Nothing (length v)
where
ts = map Just (concatMap add (group (catMaybes v)))
main :: IO ()
main = print $ shift $ replicate 4 $ Just 2
-- [Just 4,Just 2,Just 2,Nothing]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment