summaryrefslogtreecommitdiff
path: root/4-kyu/permutational-primes.hs
diff options
context:
space:
mode:
authorMistivia <i@mistivia.com>2025-04-24 17:16:21 +0800
committerMistivia <i@mistivia.com>2025-04-24 17:16:21 +0800
commit7ac9846329cc231c79fa1158f1e1f1d5fc96bc22 (patch)
tree555cc7216b57eddc8f199723ca1c6a1961ebc9a5 /4-kyu/permutational-primes.hs
parent3b2a2c6f8ff46123a154c32dcfd35d8fdec8f439 (diff)
permutational-primes
Diffstat (limited to '4-kyu/permutational-primes.hs')
-rw-r--r--4-kyu/permutational-primes.hs40
1 files changed, 40 insertions, 0 deletions
diff --git a/4-kyu/permutational-primes.hs b/4-kyu/permutational-primes.hs
new file mode 100644
index 0000000..6aedafe
--- /dev/null
+++ b/4-kyu/permutational-primes.hs
@@ -0,0 +1,40 @@
+-- https://www.codewars.com/kata/55eec0ee00ae4a8fa0000075
+module PermutationalPrimes (permutationalPrimes) where
+
+import Control.Monad
+import qualified Data.List as L
+import qualified Data.Set as Set
+
+deduplicateList :: Ord a => [a] -> [a]
+deduplicateList = Set.toList . Set.fromList
+
+permutations :: Int -> Int -> [Int]
+permutations n upperLimit =
+ filter (<= upperLimit) $
+ map read $ filter (\lst -> head lst /= '0') $
+ lstPermutations $ show n
+
+lstPermutations = L.permutations
+
+primes = filterPrime [2..] where
+ filterPrime (p:xs) =
+ p : filterPrime [x | x <- xs, x `mod` p /= 0]
+
+
+permuatationsPrimeCnt primeSet n upperLimit =
+ if foldl1 min permPrimes == n then (length permPrimes - 1)
+ else 0
+ where
+ permPrimes = deduplicateList $ filter isPrime $ permutations n upperLimit
+ where isPrime x = Set.member x primeSet
+
+permutationalPrimes :: Int -> Int -> Maybe (Int, Int, Int)
+permutationalPrimes nMax kPerms =
+ if ret /= [] then
+ Just (length ret, head ret, foldl1 max ret)
+ else
+ Nothing
+ where
+ ret = seq primeSet $ filter (\n -> kPerms == permuatationsPrimeCnt primeSet n nMax) $
+ Set.toList primeSet
+ where primeSet = Set.fromList $ takeWhile (<=nMax) primes