Numbers with prime digits whose sum is 13: Difference between revisions

Content added Content deleted
(→‎{{header|Phix}}: iterative version)
(→‎{{header|Haskell}}: Parameterized target sum, formatted output.)
Line 196: Line 196:
As an unfold, in the recursive pattern described by Nigel Galloway on the Talk page.
As an unfold, in the recursive pattern described by Nigel Galloway on the Talk page.
<lang haskell>import Data.List.Split (chunksOf)
<lang haskell>import Data.List.Split (chunksOf)
import Data.List (unfoldr)
import Data.List (intercalate, transpose, unfoldr)
import Text.Printf


primeDigitsNumsSummingTo13 :: [Int]
primeDigitsNumsSummingToN :: Int -> [Int]
primeDigitsNumsSummingTo13 = concat $ unfoldr go (return <$> primeDigits)
primeDigitsNumsSummingToN n = concat $ unfoldr go (return <$> primeDigits)
where
where
primeDigits = [2, 3, 5, 7]
primeDigits = [2, 3, 5, 7]
go :: [[Int]] -> Maybe ([Int], [[Int]])
go xs
go xs
| null xs = Nothing
| null xs = Nothing
| otherwise = Just (step xs)
| otherwise = Just (nextLength xs)
nextLength :: [[Int]] -> ([Int], [[Int]])
step xs =
nextLength xs =
let harvest nv =
let harvest nv =
[ unDigits $ fst nv
[ unDigits $ fst nv
| 13 == snd nv ]
| n == snd nv ]
prune nv =
prune nv =
[ fst nv
[ fst nv
| 12 > snd nv ]
| pred n > snd nv ]
in ((,) . concatMap harvest <*> concatMap prune)
in ((,) . concatMap harvest <*> concatMap prune)
(((,) <*> sum) <$> ((<$> xs) . (<>) . return =<< primeDigits))
(((,) <*> sum) <$> ((<$> xs) . (<>) . return =<< primeDigits))


--------------------------- TEST -------------------------
unDigits :: [Int] -> Int
unDigits = foldl ((+) . (10 *)) 0

main :: IO ()
main :: IO ()
main =
main = do
let n = 13
mapM_ (putStrLn . unwords) $ chunksOf 6 (show <$> primeDigitsNumsSummingTo13)</lang>
xs = primeDigitsNumsSummingToN n
mapM_
putStrLn
[ concat
[ (show . length) xs
, " numbers with prime digits summing to "
, show n
, ":\n"
]
, table " " $ chunksOf 10 (show <$> xs)
]

table :: String -> [[String]] -> String
table gap rows =
let ic = intercalate
ws = maximum . fmap length <$> transpose rows
pw = printf . flip ic ["%", "s"] . show
in unlines $ ic gap . zipWith pw ws <$> rows

unDigits :: [Int] -> Int
unDigits = foldl ((+) . (10 *)) 0</lang>
{{Out}}
{{Out}}
<pre>337 355 373 535 553 733
<pre>43 numbers with prime digits summing to 13:

2227 2272 2335 2353 2533 2722
337 355 373 535 553 733 2227 2272 2335 2353
3235 3253 3325 3352 3523 3532
2533 2722 3235 3253 3325 3352 3523 3532 5233 5323
5233 5323 5332 7222 22225 22252
22333 22522 23233 23323 23332 25222
5332 7222 22225 22252 22333 22522 23233 23323 23332 25222
32233 32323 32332 33223 33232 33322
32233 32323 32332 33223 33232 33322 52222 222223 222232 222322
52222 222223 222232 222322 223222 232222
223222 232222 322222</pre>
322222</pre>


=={{header|JavaScript}}==
=={{header|JavaScript}}==