1
0
Fork 0

fix: remove out-of-bound/Maybe from day 2 part 2

This commit is contained in:
Sloane Perrault 2022-09-21 09:19:52 -04:00
parent 86e396d56c
commit f604270ea9
2 changed files with 7 additions and 12 deletions

View file

@ -3,3 +3,7 @@
## Part 1
Spent some time reading up on how to define a custom instance of `Read`. Pretty simple otherwise. Surprised `countElem` isn't in Prelude.
## Part 2
Off-by-one errors were called out in the puzzle but I still made them. ~Solution can be simplified if I don't need to check for out-of-bounds issues.~ I did this.

View file

@ -25,21 +25,12 @@ solve = show . length . filter (isValidPasswordEntry . readPasswordEntry) . line
readPasswordEntry :: String -> PasswordEntry
readPasswordEntry = read
(!!?) :: [a] -> Int -> Maybe a
[] !!? _ = Nothing
(x:xs) !!? 0 = Just x
(_:xs) !!? idx = xs !!? (idx - 1)
maybeToBool (Just a) = a
maybeToBool Nothing = False
xor :: Bool -> Bool -> Bool
xor l r = l /= r
isValidPasswordEntry (PasswordEntry pos1 pos2 char pass) =
(maybeToBool $ fmap (==char) char1) `xor`
(maybeToBool $ fmap (==char) char2)
(charAtPos1 == char) `xor` (charAtPos2 == char)
where
char1 = pass !!? (pos1 - 1)
char2 = pass !!? (pos2 - 1)
charAtPos1 = pass !! (pos1 - 1)
charAtPos2 = pass !! (pos2 - 1)