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:
As an unfold, in the recursive pattern described by Nigel Galloway on the Talk page.
<lang haskell>import Data.List.Split (chunksOf)
import Data.List (intercalate, transpose, unfoldr)
import Text.Printf
 
primeDigitsNumsSummingTo13primeDigitsNumsSummingToN :: Int -> [Int]
primeDigitsNumsSummingTo13primeDigitsNumsSummingToN n = concat $ unfoldr go (return <$> primeDigits)
where
primeDigits = [2, 3, 5, 7]
go :: [[Int]] -> Maybe ([Int], [[Int]])
go xs
| null xs = Nothing
| otherwise = Just (stepnextLength xs)
nextLength :: [[Int]] -> ([Int], [[Int]])
stepnextLength xs =
let harvest nv =
[ unDigits $ fst nv
| 13n == snd nv ]
prune nv =
[ fst nv
| 12pred n > snd nv ]
in ((,) . concatMap harvest <*> concatMap prune)
(((,) <*> sum) <$> ((<$> xs) . (<>) . return =<< primeDigits))
 
--------------------------- TEST -------------------------
unDigits :: [Int] -> Int
unDigits = foldl ((+) . (10 *)) 0
 
main :: IO ()
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}}
<pre>33743 355numbers 373with 535prime 553digits 733summing to 13:
 
2227 2272 2335 2353 2533 2722
337 355 373 535 553 733 2227 2272 2335 2353
2533 2722 3235 3253 3325 3352 3523 3532 5233 5323
5233 5323 5332 7222 22225 22252
5332 7222 22225 22252 22333 22522 23233 23323 23332 25222
32233 32323 32332 33223 33232 33322 52222 222223 222232 222322
52222 222223 222232 222322 223222 232222 322222</pre>
322222</pre>
 
=={{header|JavaScript}}==