Finished day 6

This commit is contained in:
2022-12-06 17:01:11 -05:00
parent b53a8a48ee
commit 37ca7ee1c3
8 changed files with 125 additions and 4 deletions

View File

@@ -1,4 +1,7 @@
module Day5Lib where
module Day5Lib
( day5,
day5Alternate
) where
import Data.List (transpose)
import Data.List.Split

49
src/Day6Lib.hs Normal file
View File

@@ -0,0 +1,49 @@
module Day6Lib where
-- ( day6,
-- day6'
-- ) where
import Data.List (nub, elemIndex)
import Data.Maybe (fromJust)
-- Using windows of 4 characters to solve this problem
type Window = [Char]
-- For start of packet markers
splitStringIntoWindows :: String -> [Window]
splitStringIntoWindows "" = []
splitStringIntoWindows (a:[]) = []
splitStringIntoWindows (a:b:[]) = []
splitStringIntoWindows (a:b:c:[]) = []
splitStringIntoWindows (a:b:c:d:[]) = [[a,b,c,d]]
splitStringIntoWindows string@(a:b:c:d:rest) = [a,b,c,d] : (splitStringIntoWindows $ tail string)
-- For start of message markers
-- This is non-exhaustive but there is no need to write all this out :/
splitStringIntoWindows' :: String -> [Window]
splitStringIntoWindows' "" = []
splitStringIntoWindows' (a:b:c:d:e:f:g:h:i:j:k:l:m:n:[]) = [[a,b,c,d,e,f,g,h,i,j,k,l,m,n]]
splitStringIntoWindows' string@(a:b:c:d:e:f:g:h:i:j:k:l:m:n:rest) =
[a,b,c,d,e,f,g,h,i,j,k,l,m,n] : (splitStringIntoWindows' $ tail string)
-- Use the nub function to eliminate duplicate elements and check lenght before/after
findAllUniqueWindow :: Window -> Bool
findAllUniqueWindow w = (length w) == (length $ nub w)
day6 :: String -> Int
day6 input = indexAdjustedForOffset
where
windows = splitStringIntoWindows input
uniqueWindows = filter findAllUniqueWindow windows
firstUniqueWindow = head uniqueWindows
index = fromJust $ elemIndex firstUniqueWindow windows
indexAdjustedForOffset = index + 4
day6' :: String -> Int
day6' input = indexAdjustedForOffset
where
windows = splitStringIntoWindows' input
uniqueWindows = filter findAllUniqueWindow windows
firstUniqueWindow = head uniqueWindows
index = fromJust $ elemIndex firstUniqueWindow windows
indexAdjustedForOffset = index + 14