Browse Source

[Haskell][22] Adding Solution

Vinicius Teshima 4 tháng trước cách đây
mục cha
commit
16836ab7a5
3 tập tin đã thay đổi với 58 bổ sung0 xóa
  1. 0 0
      haskell/input/0022.txt
  2. 33 0
      haskell/src/0022.hs
  3. 25 0
      haskell/src/Utils.hs

Những thai đổi đã bị hủy bỏ vì nó quá lớn
+ 0 - 0
haskell/input/0022.txt


+ 33 - 0
haskell/src/0022.hs

@@ -0,0 +1,33 @@
+{-
+Using names.txt (right click and 'Save Link/Target As...'),
+ a 46K text file containing over five-thousand first names,
+ begin by sorting it into alphabetical order.
+Then working out the alphabetical value for each name,
+ multiply this value by its alphabetical position in the list to obtain a name score.
+For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 \times 53 = 49714.
+What is the total of all the name scores in the file?
+-}
+
+import Utils
+
+import System.Environment
+
+import Data.Char
+import Data.List
+import Data.Maybe
+
+import Debug.Trace
+import Text.Printf
+
+alphabeticalValue :: String -> Int
+alphabeticalValue s = map toUpper s |> map ord |> map (`sub` 64) |> sum
+                        where sub = (-)
+
+solution :: String -> Int
+solution input = filter (/='"') input |> splitByChar ',' |> sort |> mapi (\i x -> (i+1)*(alphabeticalValue x)) |> sum
+
+main :: IO ()
+main = do
+  inputContent <- (\x -> "input/" ++ x ++ ".txt") <$> getProgName >>= readFile
+
+  putStrLn ("Solution: " ++ show (solution inputContent))

+ 25 - 0
haskell/src/Utils.hs

@@ -4,6 +4,9 @@ module Utils where
   import Data.List
   import Data.Char
 
+  import Debug.Trace
+  import Text.Printf
+
   (|>) = (&)
 
   (!?) :: [a] -> Int -> Maybe a
@@ -217,3 +220,25 @@ module Utils where
   flattenTupleList [(x, y)] = [x, y]
   flattenTupleList ((x, y):xs) = [x, y] ++ (flattenTupleList xs)
 
+  mapi :: (Int -> a -> b) -> [a] -> [b]
+  mapi _ [] = []
+  mapi f l  = go' l 0
+    where go' [] _ = []
+          go' [x] i = [f i x]
+          go' (x:xs) i = [f i x] ++ go' xs (i+1)
+
+  splitByChar :: Char -> String -> [String]
+  splitByChar c s = go' (elemIndex c s) s
+    where go' :: Maybe Int -> String -> [String]
+          go' (Nothing) s = [s]
+          go' (Just i)  s = [b] ++ go' (elemIndex c a) a
+                              where
+                                (b, aRaw) = splitAt i s
+                                a = tail aRaw
+
+  tracePPId :: Show a => [a] -> [a]
+  tracePPId l = if (go' l 0) then [] else l
+    where
+      go' :: Show a => [a] -> Int -> Bool
+      go' []     _ = False
+      go' (x:xs) i = trace (printf "%5d -> %s" i (show x)) (go' xs (i+1))

Một số tệp đã không được hiển thị bởi vì quá nhiều tập tin thay đổi trong này khác