Explorar el Código

[Haskell][20] Adding Solution

Vinicius Teshima hace 4 meses
padre
commit
c50077324e
Se han modificado 2 ficheros con 28 adiciones y 0 borrados
  1. 16 0
      haskell/src/0020.hs
  2. 12 0
      haskell/src/Utils.hs

+ 16 - 0
haskell/src/0020.hs

@@ -0,0 +1,16 @@
+{-
+n! means n * (n - 1) * ... * 3 * 2 * 1.
+For example, 10! = 10 * 9 * ... * 3 * 2 * 1 = 3628800,
+and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
+Find the sum of the digits in the number 100!.
+-}
+
+import Utils
+
+import Data.Maybe
+
+solution :: Int
+solution = foldl (+) 0 (map (\x -> fromJust (c2i x)) (show (factorial 100)))
+
+main :: IO ()
+main = putStrLn ("Solution: " ++ show solution)

+ 12 - 0
haskell/src/Utils.hs

@@ -2,6 +2,7 @@ module Utils where
   import Data.Function
   import Data.Maybe
   import Data.List
+  import Data.Char
 
   (|>) = (&)
 
@@ -11,6 +12,12 @@ module Utils where
     | i == 0          = car l
     | otherwise       = cdr l >>= \x -> x !? (i-1)
 
+  c2i :: Char -> Maybe Int
+  c2i c = if cv < 48 || cv > 57
+          then Nothing
+          else Just (cv - 48)
+    where cv = ord c
+
   car :: [a] -> Maybe a
   car []    = Nothing
   car [x]   = Just x
@@ -193,3 +200,8 @@ module Utils where
       go' d (x:xs)
         | d == tD   = x
         | otherwise = go' (dateNextDay d) xs
+
+  factorial :: Integer -> Integer
+  factorial 0 = 0
+  factorial 1 = 1
+  factorial x = x * factorial (x-1)