Ver Fonte

[Haskell][27] Adding Solution

Vinicius Teshima há 4 meses atrás
pai
commit
863e8527ea
2 ficheiros alterados com 39 adições e 0 exclusões
  1. 30 0
      haskell/src/0027.hs
  2. 9 0
      haskell/src/Utils.hs

+ 30 - 0
haskell/src/0027.hs

@@ -0,0 +1,30 @@
+
+import Utils
+
+import Data.List
+import Data.Maybe
+
+--import Debug.Trace
+--import Text.Printf
+
+numOfPrimes :: Int -> Int -> Int
+numOfPrimes a b = go' 0
+  where
+    go' :: Int -> Int
+    go' n
+      -- | trace (printf "go' n=%-5d r=%-5d" n r) False = undefined
+      | otherwise = if (isPrime r) then go' (n+1) else n
+      where r = (n*n) + (a*n) + b
+
+solution :: Int
+solution = combinations2 [aDLimit..aULimit] [bDLimit..bULimit]
+             |> mapFindMaxInitial (uncurry numOfPrimes)
+             |> (uncurry (*))
+  where
+    aULimit = 999
+    bULimit = 1000
+    aDLimit = -999
+    bDLimit = -1000
+
+main :: IO ()
+main = putStrLn ("Solution: " ++ show solution)

+ 9 - 0
haskell/src/Utils.hs

@@ -283,3 +283,12 @@ module Utils where
                       then go' (x * 10) True (n)
                       else [(intToDigit hmf)] ++ (go' (x-(dn*hmf)) False (n-1))
                         where hmf = howManyFit dn x
+
+  isPrime :: Int -> Bool
+  isPrime x = (divs x) == [1]
+
+  addResult :: (a -> b) -> a -> (a, b)
+  addResult f x = (x, f x)
+
+  mapFindMaxInitial :: Ord b => (a -> b) -> [a] -> a
+  mapFindMaxInitial f l = map (addResult f) l |> maximumBy (\a b -> compare (snd a) (snd b)) |> fst