Create all permutations of a string. Here, haskell version is really impressive
permutation [] = [[]] permutation xs = [x:ys | x <- nub (xs), ys <- permutation (delete x xs)]In an array 1-100 numbers are stored, one number is missing how do you find it?
missing = succ . length . takeWhile id . zipWith (==) [1..] . sortIn an array 1-100 exactly one number is duplicate how do you find it?
duplicated = length . takeWhile id . zipWith (==) [1..] . sortor after removing duplication:
increasingPrefixLength = length . takeWhile id . zipWith (==) [1..] . sort missing = succ . increasingPrefixLength duplicated = increasingPrefixLengthjust for clarification, let's see how it works:
missing [1,3,2,5,6] -- 4 duplicated [3,2,1,2,4] -- 2From other source: sum of digits of decimal expansion of 100!
(apply + (map #(Integer/parseInt (str %)) (str (apply *' (range 1 101)))))number of zeros in decimal expansion of 100!
(count (filter #(= \0 %) (str (apply *' (range 1 101)))))and the same in haskell (with currying and compact syntax for function composition)
sum . map digitToInt . show $ product [1..100] length . filter (== '0') . show $ product [1..100]Why functional style is useful? Often it's simpler because it has less edge cases (yes, you have to know the language and understand the FP). Of course above tasks aren't much more difficult in procedural approach and still, during the interview, you will probably have to solve them also in java. But I guarantee you: after such an answer you are a few points ahead of your competitors.
0 komentarze :
Post a Comment