DEV Community

loading...

Discussion on: Daily Challenge #127 - Playing with Passphrases

Collapse
jvanbruegge profile image
Jan van Brügge

Haskell solution, will happily answer questions:

import Data.Maybe (fromMaybe)
import Data.List (elemIndex)
import Data.Char (digitToInt, intToDigit, toUpper, toLower)

solve :: Int -> String -> String
solve n = reverse . fmapEvenOdd toUpper toLower . fmap (complement . shift n)

fmapEvenOdd :: (a -> b) -> (a -> b) -> [a] -> [b]
fmapEvenOdd f g (x:y:xs) = f x:g y:fmapEvenOdd f g xs
fmapEvenOdd f _ [x] = [f x]
fmapEvenOdd _ _ [] = []

complement :: Char -> Char
complement c
    | isDigit c = intToDigit $ 9 - (digitToInt c)
    | otherwise = c

shift :: Int -> Char -> Char
shift n c = fromMaybe c $ fmap ((chars !!) . (`mod` length chars) . (+n)) $ elemIndex c chars
    where chars = ['A'..'Z']