Difference between revisions of "99 questions/11 to 20"

From HaskellWiki
Jump to navigation Jump to search
(Added a solution to Problem 18)
m
 
(10 intermediate revisions by 5 users not shown)
Line 2: Line 2:
   
 
This is part of [[H-99:_Ninety-Nine_Haskell_Problems|Ninety-Nine Haskell Problems]], based on [https://prof.ti.bfh.ch/hew1/informatik3/prolog/p-99/ Ninety-Nine Prolog Problems] and [http://www.ic.unicamp.br/~meidanis/courses/mc336/2006s2/funcional/L-99_Ninety-Nine_Lisp_Problems.html Ninety-Nine Lisp Problems].
 
This is part of [[H-99:_Ninety-Nine_Haskell_Problems|Ninety-Nine Haskell Problems]], based on [https://prof.ti.bfh.ch/hew1/informatik3/prolog/p-99/ Ninety-Nine Prolog Problems] and [http://www.ic.unicamp.br/~meidanis/courses/mc336/2006s2/funcional/L-99_Ninety-Nine_Lisp_Problems.html Ninety-Nine Lisp Problems].
  +
 
 
== Problem 11 ==
 
== Problem 11 ==
  +
<div style="border-bottom:1px solid #eee">(*) Modified run-length encoding. <span style="float:right"><small>[[99 questions/Solutions/11|Solutions]]</small></span>
  +
</div>
  +
&nbsp;<br>
   
(*) Modified run-length encoding.
 
 
Modify the result of problem 10 in such a way that if an element has no duplicates it is simply copied into the result list. Only elements with duplicates are transferred as (N E) lists.
 
Modify the result of problem 10 in such a way that if an element has no duplicates it is simply copied into the result list. Only elements with duplicates are transferred as (N E) lists.
  +
  +
Example:
   
 
<pre>
 
<pre>
Example:
 
 
* (encode-modified '(a a a a b c c a a d e e e e))
 
* (encode-modified '(a a a a b c c a a d e e e e))
 
((4 A) B (2 C) (2 A) D (4 E))
 
((4 A) B (2 C) (2 A) D (4 E))
  +
</pre>
   
 
Example in Haskell:
 
Example in Haskell:
P11> encodeModified "aaaabccaadeeee"
 
[Multiple 4 'a',Single 'b',Multiple 2 'c',Multiple 2 'a',Single 'd',Multiple 4 'e']
 
</pre>
 
   
Solution:
 
 
<haskell>
 
<haskell>
  +
λ> encodeModified "aaaabccaadeeee"
data ListItem a = Single a | Multiple Int a
 
  +
[Multiple 4 'a',Single 'b',Multiple 2 'c',
deriving (Show)
 
  +
Multiple 2 'a',Single 'd',Multiple 4 'e']
 
encodeModified :: Eq a => [a] -> [ListItem a]
 
encodeModified = map encodeHelper . encode
 
where
 
encodeHelper (1,x) = Single x
 
encodeHelper (n,x) = Multiple n x
 
 
</haskell>
 
</haskell>
   
Again, like in problem 7, we need a utility type because lists in haskell are homogeneous. Afterwards we use the <hask>encode</hask> function from problem 10 and map single instances of a list item to <hask>Single</hask> and multiple ones to <hask>Multiple</hask>.
 
   
The ListItem definition contains 'deriving (Show)' so that we can get interactive output.
 
 
 
== Problem 12 ==
 
== Problem 12 ==
  +
<div style="border-bottom:1px solid #eee">(**) Decode a run-length encoded list. <span style="float:right"><small>[[99 questions/Solutions/12|Solutions]]</small></span>
  +
</div>
  +
&nbsp;<br>
   
(**) Decode a run-length encoded list.
 
 
Given a run-length code list generated as specified in problem 11. Construct its uncompressed version.
 
Given a run-length code list generated as specified in problem 11. Construct its uncompressed version.
   
<pre>
 
 
Example in Haskell:
 
Example in Haskell:
P12> decodeModified [Multiple 4 'a',Single 'b',Multiple 2 'c',Multiple 2 'a',Single 'd',Multiple 4 'e']
 
"aaaabccaadeeee"
 
</pre>
 
   
Solution:
 
 
<haskell>
 
<haskell>
decodeModified :: [ListItem a] -> [a]
+
λ> decodeModified
  +
[Multiple 4 'a',Single 'b',Multiple 2 'c',
decodeModified = concatMap decodeHelper
 
  +
Multiple 2 'a',Single 'd',Multiple 4 'e']
where
 
  +
"aaaabccaadeeee"
decodeHelper (Single x) = [x]
 
decodeHelper (Multiple n x) = replicate n x
 
 
</haskell>
 
</haskell>
   
  +
We only need to map single instances of an element to a list containing only one element and multiple ones to a list containing the specified number of elements and concatenate these lists.
 
  +
 
 
== Problem 13 ==
 
== Problem 13 ==
  +
<div style="border-bottom:1px solid #eee">(**) Run-length encoding of a list (direct solution). <span style="float:right"><small>[[99 questions/Solutions/13|Solutions]]</small></span>
  +
</div>
  +
&nbsp;<br>
   
(**) Run-length encoding of a list (direct solution).
 
 
Implement the so-called run-length encoding data compression method directly. I.e. don't explicitly create the sublists containing the duplicates, as in problem 9, but only count them. As in problem P11, simplify the result list by replacing the singleton lists (1 X) by X.
 
Implement the so-called run-length encoding data compression method directly. I.e. don't explicitly create the sublists containing the duplicates, as in problem 9, but only count them. As in problem P11, simplify the result list by replacing the singleton lists (1 X) by X.
   
<pre>
 
 
Example:
 
Example:
  +
  +
<pre>
 
* (encode-direct '(a a a a b c c a a d e e e e))
 
* (encode-direct '(a a a a b c c a a d e e e e))
 
((4 A) B (2 C) (2 A) D (4 E))
 
((4 A) B (2 C) (2 A) D (4 E))
  +
</pre>
   
 
Example in Haskell:
 
Example in Haskell:
P13> encodeDirect "aaaabccaadeeee"
 
[Multiple 4 'a',Single 'b',Multiple 2 'c',Multiple 2 'a',Single 'd',Multiple 4 'e']
 
</pre>
 
   
Solution:
 
 
<haskell>
 
<haskell>
  +
λ> encodeDirect "aaaabccaadeeee"
encode' :: Eq a => [a] -> [(Int,a)]
 
  +
[Multiple 4 'a',Single 'b',Multiple 2 'c',
encode' = foldr helper []
 
  +
Multiple 2 'a',Single 'd',Multiple 4 'e']
where
 
helper x [] = [(1,x)]
 
helper x (y@(a,b):ys)
 
| x == b = (1+a,x):ys
 
| otherwise = (1,x):y:ys
 
 
encodeDirect :: Eq a => [a] -> [ListItem a]
 
encodeDirect = map encodeHelper . encode'
 
where
 
encodeHelper (1,x) = Single x
 
encodeHelper (n,x) = Multiple n x
 
 
</haskell>
 
</haskell>
   
  +
First of all we could rewrite the function <hask>encode</hask> from problem 10 in a way that is does not create the sublists. Thus, I decided to traverse the original list from right to left (using <hask>foldr</hask>) and to prepend each element to the resulting list in the proper way. Thereafter we only need to modify the function <hask>encodeModified</hask> from problem 11 to use <hask>encode'</hask>.
 
  +
 
 
== Problem 14 ==
 
== Problem 14 ==
  +
<div style="border-bottom:1px solid #eee">(*) Duplicate the elements of a list. <span style="float:right"><small>[[99 questions/Solutions/14|Solutions]]</small></span>
  +
</div>
  +
&nbsp;<br>
   
  +
Example:
(*) Duplicate the elements of a list.
 
   
 
<pre>
 
<pre>
Example:
 
 
* (dupli '(a b c c d))
 
* (dupli '(a b c c d))
 
(A A B B C C C C D D)
 
(A A B B C C C C D D)
  +
</pre>
   
 
Example in Haskell:
 
Example in Haskell:
> dupli [1, 2, 3]
 
[1,1,2,2,3,3]
 
</pre>
 
   
Solution:
 
 
<haskell>
 
<haskell>
dupli [] = []
+
λ> dupli [1, 2, 3]
  +
[1,1,2,2,3,3]
dupli (x:xs) = x:x:dupli xs
 
 
</haskell>
 
</haskell>
   
or, using list comprehension syntax:
 
   
<haskell>
 
dupli list = concat [[x,x] | x <- list]
 
</haskell>
 
 
or, using the list monad:
 
<haskell>
 
dupli xs = xs >>= (\x -> [x,x])
 
</haskell>
 
 
or, using concatMap:
 
<haskell>
 
dupli = concatMap (\x -> [x,x])
 
</haskell>
 
 
also using concatMap:
 
<haskell>
 
dupli = concatMap (replicate 2)
 
</haskell>
 
 
or, using foldr:
 
<haskell>
 
dupli = foldr (\ x xs -> x : x : xs) []
 
</haskell>
 
   
 
== Problem 15 ==
 
== Problem 15 ==
  +
<div style="border-bottom:1px solid #eee">(**) Replicate the elements of a list a given number of times. <span style="float:right"><small>[[99 questions/Solutions/15|Solutions]]</small></span>
  +
</div>
   
  +
Example:
(**) Replicate the elements of a list a given number of times.
 
   
 
<pre>
 
<pre>
Example:
 
 
* (repli '(a b c) 3)
 
* (repli '(a b c) 3)
 
(A A A B B B C C C)
 
(A A A B B B C C C)
  +
</pre>
   
 
Example in Haskell:
 
Example in Haskell:
> repli "abc" 3
 
"aaabbbccc"
 
</pre>
 
   
Solution:
 
 
<haskell>
 
<haskell>
  +
λ> repli "abc" 3
repli :: [a] -> Int -> [a]
 
  +
"aaabbbccc"
repli xs n = concatMap (replicate n) xs
 
 
</haskell>
 
</haskell>
   
  +
or, in Pointfree style:
 
<haskell>
 
repli = flip $ concatMap . replicate
 
</haskell>
 
   
 
== Problem 16 ==
 
== Problem 16 ==
(**) Drop every N'th element from a list.
+
<div style="border-bottom:1px solid #eee">(**) Drop every N'th element from a list. <span style="float:right"><small>[[99 questions/Solutions/16|Solutions]]</small></span>
  +
</div>
  +
&nbsp;<br>
  +
  +
Example:
   
 
<pre>
 
<pre>
Example:
 
 
* (drop '(a b c d e f g h i k) 3)
 
* (drop '(a b c d e f g h i k) 3)
 
(A B D E G H K)
 
(A B D E G H K)
  +
</pre>
   
 
Example in Haskell:
 
Example in Haskell:
*Main> dropEvery "abcdefghik" 3
 
"abdeghk"
 
</pre>
 
   
Solution:
 
 
<haskell>
 
<haskell>
  +
λ> dropEvery "abcdefghik" 3
dropEvery :: [a] -> Int -> [a]
 
  +
"abdeghk"
dropEvery [] _ = []
 
dropEvery (x:xs) n = dropEvery' (x:xs) n 1 where
 
dropEvery' (x:xs) n i = (if (n `divides` i) then
 
[] else
 
[x])
 
++ (dropEvery' xs n (i+1))
 
dropEvery' [] _ _ = []
 
divides x y = y `mod` x == 0
 
 
</haskell>
 
</haskell>
   
or an alternative iterative solution:
 
<haskell>
 
dropEvery :: [a] -> Int -> [a]
 
dropEvery list count = helper list count count
 
where helper [] _ _ = []
 
helper (x:xs) count 1 = helper xs count count
 
helper (x:xs) count n = x : (helper xs count (n - 1))
 
</haskell>
 
 
or yet another iterative solution which divides lists using Prelude:
 
<haskell>
 
dropEvery :: [a] -> Int -> [a]
 
dropEvery [] _ = []
 
dropEvery list count = (take (count-1) list) ++ dropEvery (drop count list) count
 
</haskell>
 
 
or using zip:
 
<haskell>
 
dropEvery n = map snd . filter ((n/=) . fst) . zip (cycle [1..n])
 
</haskell>
 
 
 
== Problem 17 ==
 
== Problem 17 ==
  +
<div style="border-bottom:1px solid #eee">(*) Split a list into two parts; the length of the first part is given. <span style="float:right"><small>[[99 questions/Solutions/17|Solutions]]</small></span>
 
  +
</div>
(*) Split a list into two parts; the length of the first part is given.
 
  +
&nbsp;<br>
   
 
Do not use any predefined predicates.
 
Do not use any predefined predicates.
  +
  +
Example:
   
 
<pre>
 
<pre>
Example:
 
 
* (split '(a b c d e f g h i k) 3)
 
* (split '(a b c d e f g h i k) 3)
 
( (A B C) (D E F G H I K))
 
( (A B C) (D E F G H I K))
  +
</pre>
   
 
Example in Haskell:
 
Example in Haskell:
*Main> split "abcdefghik" 3
 
("abc", "defghik")
 
</pre>
 
   
Solution using take and drop:
 
 
<haskell>
 
<haskell>
  +
λ> split "abcdefghik" 3
split xs n = (take n xs, drop n xs)
 
  +
("abc", "defghik")
 
</haskell>
 
</haskell>
   
Alternatively, we have the following recursive solution:
 
<haskell>
 
split :: [a] -> Int -> ([a], [a])
 
split [] _ = ([], [])
 
split l@(x : xs) n | n > 0 = (x : ys, zs)
 
| otherwise = ([], l)
 
where (ys,zs) = split xs (n - 1)
 
</haskell>
 
   
The same solution as above written more cleanly:
 
<haskell>
 
split :: [a] -> Int -> ([a], [a])
 
split xs 0 = ([], xs)
 
split (x:xs) n = let (f,l) = split xs (n-1) in (x : f, l)
 
</haskell>
 
   
Note that this function, with the parameters in the other order, exists as <hask>splitAt</hask>.
 
 
 
 
== Problem 18 ==
 
== Problem 18 ==
  +
<div style="border-bottom:1px solid #eee">(**) Extract a slice from a list. <span style="float:right"><small>[[99 questions/Solutions/18|Solutions]]</small></span>
 
  +
</div>
(**) Extract a slice from a list.
 
  +
&nbsp;<br>
   
 
Given two indices, i and k, the slice is the list containing the elements between the i'th and k'th element of the original list (both limits included). Start counting the elements with 1.
 
Given two indices, i and k, the slice is the list containing the elements between the i'th and k'th element of the original list (both limits included). Start counting the elements with 1.
  +
  +
Example:
   
 
<pre>
 
<pre>
Example:
 
 
* (slice '(a b c d e f g h i k) 3 7)
 
* (slice '(a b c d e f g h i k) 3 7)
 
(C D E F G)
 
(C D E F G)
  +
</pre>
   
 
Example in Haskell:
 
Example in Haskell:
*Main> slice ['a','b','c','d','e','f','g','h','i','k'] 3 7
 
"cdefg"
 
</pre>
 
   
Solution:
 
 
<haskell>
 
<haskell>
  +
λ> slice ['a','b','c','d','e','f','g','h','i','k'] 3 7
slice xs (i+1) k = take (k-i) $ drop i xs
 
  +
"cdefg"
 
</haskell>
 
</haskell>
   
Or, an iterative solution:
 
<haskell>
 
slice :: [a]->Int->Int->[a]
 
slice lst 1 m = slice' lst m []
 
where
 
slice' :: [a]->Int->[a]->[a]
 
slice' _ 0 acc = reverse acc
 
slice' (x:xs) n acc = slice' xs (n - 1) (x:acc)
 
slice (x:xs) n m = slice xs (n - 1) (m - 1)
 
</haskell>
 
   
Or:
 
 
<haskell>
 
slice :: [a] -> Int -> Int -> [a]
 
slice (x:xs) i k
 
| i > 1 = slice xs (i - 1) (k - 1)
 
| k < 1 = []
 
| otherwise = x:slice xs (i - 1) (k - 1)
 
</haskell>
 
   
 
== Problem 19 ==
 
== Problem 19 ==
  +
<div style="border-bottom:1px solid #eee">(**) Rotate a list N places to the left. <span style="float:right"><small>[[99 questions/Solutions/19|Solutions]]</small></span>
 
  +
</div>
(**) Rotate a list N places to the left.
 
  +
&nbsp;<br>
   
 
Hint: Use the predefined functions length and (++).
 
Hint: Use the predefined functions length and (++).
  +
  +
Examples:
   
 
<pre>
 
<pre>
Examples:
 
 
* (rotate '(a b c d e f g h) 3)
 
* (rotate '(a b c d e f g h) 3)
 
(D E F G H A B C)
 
(D E F G H A B C)
Line 303: Line 189:
 
* (rotate '(a b c d e f g h) -2)
 
* (rotate '(a b c d e f g h) -2)
 
(G H A B C D E F)
 
(G H A B C D E F)
  +
</pre>
   
 
Examples in Haskell:
 
Examples in Haskell:
  +
*Main> rotate ['a','b','c','d','e','f','g','h'] 3
 
  +
<haskell>
  +
λ> rotate ['a','b','c','d','e','f','g','h'] 3
 
"defghabc"
 
"defghabc"
   
*Main> rotate ['a','b','c','d','e','f','g','h'] (-2)
+
λ> rotate ['a','b','c','d','e','f','g','h'] (-2)
 
"ghabcdef"
 
"ghabcdef"
</pre>
 
 
Solution:
 
<haskell>
 
rotate [] _ = []
 
rotate l 0 = l
 
rotate (x:xs) (n+1) = rotate (xs ++ [x]) n
 
rotate l n = rotate l (length l + n)
 
 
</haskell>
 
</haskell>
   
There are two separate cases:
 
* If n > 0, move the first element to the end of the list n times.
 
* If n < 0, convert the problem to the equivalent problem for n > 0 by adding the list's length to n.
 
   
or using cycle:
 
<haskell>
 
rotate xs n = take len . drop (n `mod` len) . cycle $ xs
 
where len = length xs
 
</haskell>
 
 
or
 
 
<haskell>
 
rotate xs n = if n >= 0 then
 
drop n xs ++ take n xs
 
else let l = ((length xs) + n) in
 
drop l xs ++ take l xs
 
</haskell>
 
 
or
 
 
<haskell>
 
rotate xs n = drop nn xs ++ take nn xs
 
where
 
nn = n `mod` length xs
 
</haskell>
 
 
 
 
== Problem 20 ==
 
== Problem 20 ==
  +
<div style="border-bottom:1px solid #eee">(*) Remove the K'th element from a list. <span style="float:right"><small>[[99 questions/Solutions/20|Solutions]]</small></span>
  +
</div>
  +
&nbsp;<br>
   
  +
Example in Prolog:
(*) Remove the K'th element from a list.
 
   
Example in Prolog:
 
 
<pre>
 
<pre>
 
?- remove_at(X,[a,b,c,d],2,R).
 
?- remove_at(X,[a,b,c,d],2,R).
Line 359: Line 217:
   
 
Example in Lisp:
 
Example in Lisp:
  +
 
<pre>
 
<pre>
 
* (remove-at '(a b c d) 2)
 
* (remove-at '(a b c d) 2)
 
(A C D)
 
(A C D)
 
</pre>
 
</pre>
  +
 
(Note that this only returns the residue list, while the Prolog version also returns the deleted element.)
 
(Note that this only returns the residue list, while the Prolog version also returns the deleted element.)
   
 
Example in Haskell:
 
Example in Haskell:
<pre>
 
*Main> removeAt 1 "abcd"
 
('b',"acd")
 
</pre>
 
   
Solution:
 
 
<haskell>
 
<haskell>
  +
λ> removeAt 2 "abcd"
removeAt :: Int -> [a] -> (a, [a])
 
  +
('b',"acd")
removeAt k xs = case back of
 
[] -> error "removeAt: index too large"
 
x:rest -> (x, front ++ rest)
 
where (front, back) = splitAt k xs
 
 
</haskell>
 
</haskell>
   
Simply use the <hask>splitAt</hask> to split after k elements.
 
If the original list has fewer than k+1 elements, the second list will be empty, and there will be no element to extract.
 
Note that the Prolog and Lisp versions treat 1 as the first element in the list, and the Lisp version appends NIL elements to the end of the list if k is greater than the list length.
 
   
or
 
 
<haskell>
 
removeAt n xs = (xs!!n,take n xs ++ drop (n+1) xs)
 
</haskell>
 
   
 
[[Category:Tutorials]]
 
[[Category:Tutorials]]

Latest revision as of 04:58, 10 June 2023


This is part of Ninety-Nine Haskell Problems, based on Ninety-Nine Prolog Problems and Ninety-Nine Lisp Problems.

Problem 11

(*) Modified run-length encoding. Solutions

 

Modify the result of problem 10 in such a way that if an element has no duplicates it is simply copied into the result list. Only elements with duplicates are transferred as (N E) lists.

Example:

* (encode-modified '(a a a a b c c a a d e e e e))
((4 A) B (2 C) (2 A) D (4 E))

Example in Haskell:

λ> encodeModified "aaaabccaadeeee"
[Multiple 4 'a',Single 'b',Multiple 2 'c',
 Multiple 2 'a',Single 'd',Multiple 4 'e']


Problem 12

(**) Decode a run-length encoded list. Solutions

 

Given a run-length code list generated as specified in problem 11. Construct its uncompressed version.

Example in Haskell:

λ> decodeModified 
       [Multiple 4 'a',Single 'b',Multiple 2 'c',
        Multiple 2 'a',Single 'd',Multiple 4 'e']
"aaaabccaadeeee"


Problem 13

(**) Run-length encoding of a list (direct solution). Solutions

 

Implement the so-called run-length encoding data compression method directly. I.e. don't explicitly create the sublists containing the duplicates, as in problem 9, but only count them. As in problem P11, simplify the result list by replacing the singleton lists (1 X) by X.

Example:

* (encode-direct '(a a a a b c c a a d e e e e))
((4 A) B (2 C) (2 A) D (4 E))

Example in Haskell:

λ> encodeDirect "aaaabccaadeeee"
[Multiple 4 'a',Single 'b',Multiple 2 'c',
 Multiple 2 'a',Single 'd',Multiple 4 'e']


Problem 14

(*) Duplicate the elements of a list. Solutions

 

Example:

* (dupli '(a b c c d))
(A A B B C C C C D D)

Example in Haskell:

λ> dupli [1, 2, 3]
[1,1,2,2,3,3]


Problem 15

(**) Replicate the elements of a list a given number of times. Solutions

Example:

* (repli '(a b c) 3)
(A A A B B B C C C)

Example in Haskell:

λ> repli "abc" 3
"aaabbbccc"


Problem 16

(**) Drop every N'th element from a list. Solutions

 

Example:

* (drop '(a b c d e f g h i k) 3)
(A B D E G H K)

Example in Haskell:

λ> dropEvery "abcdefghik" 3
"abdeghk"

Problem 17

(*) Split a list into two parts; the length of the first part is given. Solutions

 

Do not use any predefined predicates.

Example:

* (split '(a b c d e f g h i k) 3)
( (A B C) (D E F G H I K))

Example in Haskell:

λ> split "abcdefghik" 3
("abc", "defghik")


Problem 18

(**) Extract a slice from a list. Solutions

 

Given two indices, i and k, the slice is the list containing the elements between the i'th and k'th element of the original list (both limits included). Start counting the elements with 1.

Example:

* (slice '(a b c d e f g h i k) 3 7)
(C D E F G)

Example in Haskell:

λ> slice ['a','b','c','d','e','f','g','h','i','k'] 3 7
"cdefg"


Problem 19

(**) Rotate a list N places to the left. Solutions

 

Hint: Use the predefined functions length and (++).

Examples:

* (rotate '(a b c d e f g h) 3)
(D E F G H A B C)

* (rotate '(a b c d e f g h) -2)
(G H A B C D E F)

Examples in Haskell:

λ> rotate ['a','b','c','d','e','f','g','h'] 3
"defghabc"

λ> rotate ['a','b','c','d','e','f','g','h'] (-2)
"ghabcdef"


Problem 20

(*) Remove the K'th element from a list. Solutions

 

Example in Prolog:

?- remove_at(X,[a,b,c,d],2,R).
X = b
R = [a,c,d]

Example in Lisp:

* (remove-at '(a b c d) 2)
(A C D)

(Note that this only returns the residue list, while the Prolog version also returns the deleted element.)

Example in Haskell:

λ> removeAt 2 "abcd"
('b',"acd")