Day 6 done
[advent-of-code-22.git] / advent06 / Main.hs
diff --git a/advent06/Main.hs b/advent06/Main.hs
new file mode 100644 (file)
index 0000000..02dd902
--- /dev/null
@@ -0,0 +1,40 @@
+-- Writeup at https://work.njae.me.uk/2022/12/06/advent-of-code-2022-day-6/
+
+import System.Environment
+import Data.List
+
+-- test = "mjqjpqmgbljsphdztnvjfqwrcgsmlb"
+
+main :: IO ()
+main = 
+  do  dataFileName <- getDataFileName
+      text <- readFile dataFileName
+      -- print $ part1 test
+      -- print $ part2 test
+      print $ part1 text
+      print $ part2 text
+
+getDataFileName :: IO String
+getDataFileName =
+  do args <- getArgs
+     progName <- getProgName
+     let baseDataName =  if null args
+                         then progName
+                         else head args 
+     let dataFileName = "data/" ++ baseDataName ++ ".txt"
+     return dataFileName
+
+part1 :: String -> Int
+part1 = interestingPosition 4
+
+part2 :: String -> Int
+part2 = interestingPosition 14
+
+interestingPosition :: Int -> String -> Int
+interestingPosition n text = n + (fst packetPos)
+  where candidates = zip [0..] $ fmap (take n) $ tails text
+        packetPos = head $ dropWhile (hasSame . snd) candidates
+
+allDifferent, hasSame :: String -> Bool
+allDifferent cs = nub cs == cs
+hasSame = not . allDifferent