Skip to content

Instantly share code, notes, and snippets.

@skejeton
Created December 12, 2020 12:46
Show Gist options
  • Save skejeton/cdc196cfa17141f0725b58f43577e58b to your computer and use it in GitHub Desktop.
Save skejeton/cdc196cfa17141f0725b58f43577e58b to your computer and use it in GitHub Desktop.
testData = {- Your data, split by newline -}
data CellType = Seat | Occupied | Floor deriving(Show, Eq)
cellFrom 'L' = Seat
cellFrom '#' = Occupied
cellFrom '.' = Floor
fromJust (Just x) = x
fromJust Nothing = error "unwrapped nothing"
transformData dat = do
xs <- dat
return $ cellFrom <$> xs
maybeGetCell x y dat = if all (==True) $ [x >= 0, y >= 0, y < (length dat), x < (length (dat!!0))] then Just $ (dat !! y) !! x else Nothing
getCell x y dat = if all (==True) $ [x >= 0, y >= 0, y < (length dat), x < (length (dat!!0))] then (dat !! y) !! x else Floor
traverseDir px py dx dy dat acc = if cell == Nothing || cell /= (Just Floor) then if cell == Nothing then [] else [fromJust cell] else (fromJust cell):(traverseDir (px+dx) (py+dy) dx dy dat acc) where cell = maybeGetCell (px+dx) (py+dy) dat
adj = [(0, -1), (0, 1), (-1, 0), (1, 0), (1, 1), (-1, 1), (1, -1), (-1, -1)];
checkAdjacent x y dat = if getCell x y dat == Floor then Floor else if all (/=Occupied) check then Occupied else if (length $ filter (==Occupied) check) >= 4 then Seat else getCell x y dat where check = (\idx -> getCell (x+(snd idx)) (y+(fst idx)) dat) <$> adj
checkDirected x y dat = if ccell == Floor then Floor else if ccell == Seat && (all (/=Occupied) directed) then Occupied else if ccell == Occupied && (length $ filter (==Occupied) directed) >= 5 then Seat else ccell where check = (\idx -> getCell (x+(fst idx)) (y+(snd idx)) dat) <$> adj; directed = concat $ (\(dx, dy) -> traverseDir x y dx dy dat []) <$> adj; ccell = getCell x y dat
iteration dat = do
y <- [0..((length testData)-1)]
return $ do x <- [0..((length (testData !! 0))-1)]
return $ checkDirected x y dat
stabilize :: Eq a => (a -> a) -> a -> a
stabilize f = go []
where
go ps a | a `elem` ps = a
| otherwise = go (a : ps) (f a)
simulate dat = stabilize iteration dat
floorsChanged datd dat = all (==True) [a == b | as <- datd, bs <- dat, a <- as, b <- bs, a == Floor]
mapshow dat = do
ds <- dat
return $ ((\d -> case d of
Seat -> 'L'
Occupied -> '#'
Floor -> '.') <$> ds)
main :: IO()
main = do
let d = (transformData testData)
let x = iteration d
putStrLn $ foldl (\x y -> x++"\n"++y) "" $ mapshow x
let x = iteration $ iteration d
putStrLn $ foldl (\x y -> x++"\n"++y) "" $ mapshow x
if floorsChanged d x then print "Haha" else print "hoho"
print $ length $ filter (==Occupied) $ concat $ simulate d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment