Skip to content

Instantly share code, notes, and snippets.

@blaisepascal
Created May 22, 2020 20:57
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 blaisepascal/d1a5043e178f982f4484d3c188b4a634 to your computer and use it in GitHub Desktop.
Save blaisepascal/d1a5043e178f982f4484d3c188b4a634 to your computer and use it in GitHub Desktop.
Subway Trees
{-# LANGUAGE OverloadedStrings #-}
import Control.Arrow
import Data.List
import Data.Maybe
import Control.Applicative
import Data.Attoparsec.ByteString.Char8
import qualified Data.ByteString.Char8 as C
import qualified ScannerBS as S
data Subway = Subway [Subway]
deriving (Show,Ord,Eq)
cannonical :: Subway -> Subway
cannonical (Subway xs) = Subway $ sort (map cannonical xs)
parseSubway :: Parser Subway
parseSubway = Subway <$> (string "0" *> many parseSubway <* string "1")
str2sub :: C.ByteString -> Subway
str2sub s = fromJust $ maybeResult $ parse parseSubway (C.cons '0' (C.snoc s '1'))
main :: IO ()
main = C.interact $
S.runScanner (S.numberOf (S.two S.str))
>>> map solve >>> C.unlines
solve :: [C.ByteString] -> C.ByteString
solve = (["","same","different"] !!) . length . group . map (cannonical . str2sub)
@m4dc4p
Copy link

m4dc4p commented May 22, 2020

This was based on the observation that the in-order traversal of the subway tree will always have a "0" when entering a list of sub-trees, and a "1" when it is done with a list of sub-trees. It has the same structure as the Dyck Language, except using "0" and "1" instead of parenthesis.

Great insight. Thank you!

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