Created
August 22, 2023 00:24
-
-
Save hhefesto/45ad9d8fa8ed7bff40353507ffcf4c37 to your computer and use it in GitHub Desktop.
Simple text editor hackerrank problem: https://www.hackerrank.com/challenges/one-week-preparation-kit-simple-text-editor/problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Telomare.Cesar where | |
import Data.Char (ord, chr, isLetter, isLower) | |
import Text.Read (Lexeme(Char)) | |
input = unlines $ [ "11" | |
, "middle-Outz" | |
, "2" | |
] | |
rotate :: Int -> Char -> Char | |
rotate i c = if isLetter c | |
then if isLower c | |
then chr $ 97 + ((i + ord c - 97) `mod` 26) | |
else chr $ 65 + ((i + ord c - 65) `mod` 26) | |
else c | |
solve str = | |
let aux = lines str | |
unciphered = aux !! 1 | |
rotation :: Int | |
rotation = read $ aux !! 2 | |
in | |
rotate rotation <$> unciphered | |
main = interact solve |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE LambdaCase #-} | |
module Telomare.SimpleTextEditor where | |
import Control.Monad.State (MonadIO (liftIO), MonadState (get, put), StateT, | |
evalStateT) | |
input = unlines [ "8" | |
, "1 abc" | |
, "3 3" | |
, "2 3" | |
, "1 xy" | |
, "3 2" | |
, "4" | |
, "4" | |
, "3 1" | |
] | |
data Action | |
= Append String | |
| Delete Int | |
| Print Int | |
| Undo | |
deriving (Show) | |
parse :: String -> Action | |
parse str = | |
case head str of | |
'1' -> Append . drop 2 $ str | |
'2' -> Delete . read . drop 2 $ str | |
'3' -> Print . read . drop 2 $ str | |
'4' -> Undo | |
runActions :: [Action] -> StateT ([(Action, String)], String) IO () | |
runActions = \case | |
[] -> pure () | |
(Append str : xs) -> do | |
(actions, buffer) <- get | |
put ((Append str, buffer) : actions, buffer <> str) | |
runActions xs | |
(Delete i : xs) -> do | |
(actions, buffer) <- get | |
put ((Delete i, buffer) : actions, reverse $ drop i (reverse buffer)) | |
runActions xs | |
(Print i : xs) -> do | |
(_, buffer) <- get | |
liftIO . putStrLn $ [buffer !! (i-1)] | |
runActions xs | |
(Undo : xs) -> do | |
(a:actions, buffer) <- get | |
put (actions, snd a) | |
runActions xs | |
solve :: String -> IO () | |
solve str = | |
let actions = parse <$> (tail . lines $ str) | |
in evalStateT (runActions actions) ([],"") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment