new: Solved problems 11 to 20

This commit is contained in:
Sayantan Santra 2024-05-24 18:50:16 -05:00
parent 861ab7da03
commit a6e4866f22
Signed by: SinTan1729
GPG Key ID: EB3E68BFBA25C85F
10 changed files with 74 additions and 0 deletions

View File

@ -0,0 +1,20 @@
data ListItem a = Single a | Multiple Int a deriving (Show)
getListItem :: (Int, a) -> ListItem a
getListItem (1, x) = Single x
getListItem (n, x) = Multiple n x
encode :: (Eq a) => [a] -> [(Int, a)]
encode =
foldr
( \x acc -> case acc of
[] -> [(1, x)]
(hd@(hd_n, hd_a) : tl) ->
if x == hd_a
then (hd_n + 1, hd_a) : tl
else (1, x) : hd : tl
)
[]
encodeModified :: (Eq a) => [a] -> [ListItem a]
encodeModified = map getListItem <$> encode

View File

@ -0,0 +1,8 @@
data ListItem a = Single a | Multiple Int a deriving (Read)
fromListItem :: ListItem a -> [a]
fromListItem (Single x) = [x]
fromListItem (Multiple n x) = replicate n x
decodeModified :: [ListItem a] -> [a]
decodeModified = concatMap fromListItem

View File

@ -0,0 +1,21 @@
-- This is the same solution as in Problem 11
data ListItem a = Single a | Multiple Int a deriving (Show)
getListItem :: (Int, a) -> ListItem a
getListItem (1, x) = Single x
getListItem (n, x) = Multiple n x
encode :: (Eq a) => [a] -> [(Int, a)]
encode =
foldr
( \x acc -> case acc of
[] -> [(1, x)]
(hd@(hd_n, hd_a) : tl) ->
if x == hd_a
then (hd_n + 1, hd_a) : tl
else (1, x) : hd : tl
)
[]
encodeModified :: (Eq a) => [a] -> [ListItem a]
encodeModified = map getListItem <$> encode

View File

@ -0,0 +1,2 @@
dupli :: [a] -> [a]
dupli x = concat $ [replicate 2] <*> x

View File

@ -0,0 +1,2 @@
repli :: [a] -> Int -> [a]
repli x n = concat $ [replicate n] <*> x

View File

@ -0,0 +1,2 @@
dropEvery :: [a] -> Int -> [a]
dropEvery l n = map snd . filter ((0 /=) . (`mod` n) . fst) $ zip [1 ..] l

View File

@ -0,0 +1,5 @@
split :: [a] -> Int -> ([a], [a])
split x 0 = ([], x)
split (hd : tl) n = (hd : next_hd, next_tl)
where
(next_hd, next_tl) = split tl (n - 1)

View File

@ -0,0 +1,4 @@
slice :: [a] -> Int -> Int -> [a]
slice [] _ _ = error "Invalid indices"
slice l 1 n = take n l
slice (_ : tl) m n = slice tl (m - 1) (n - 1)

View File

@ -0,0 +1,5 @@
rotate :: [a] -> Int -> [a]
rotate l n =
if n >= 0
then (\(x, y) -> y ++ x) $ splitAt n l
else rotate l (length l + n)

View File

@ -0,0 +1,5 @@
removeAt :: Int -> [a] -> (a, [a])
removeAt n ls = (last l, take m l ++ r)
where
(l, r) = splitAt n ls
m = length l - 1