Sum to 100: Difference between revisions

→‎{{header|Haskell}}: Replaced an arrow with an applicative, tidied.
No edit summary
(→‎{{header|Haskell}}: Replaced an arrow with an applicative, tidied.)
Line 2,796:
 
=={{header|Haskell}}==
<lang Haskell>import DataControl.MonoidMonad ((<>)replicateM)
import Data.Ord (comparing)
import Control.Arrow ((&&&))
import Data.Char (intToDigit)
import ControlData.Monad (replicateM)List
( find,
import Data.List (nub, group, sort, sortBy, find, intercalate)
group,
intercalate,
]nub,
sort,
sortBy,
)
import ControlData.ArrowMonoid ((&&&<>))
import Data.Ord (comparing)
 
data Sign
Line 2,808 ⟶ 2,814:
| Minus
deriving (Eq, Show)
 
------------------------ SUM TO 100 ----------------------
 
universe :: [[(Int, Sign)]]
universe =
zip [1 .. 9] <$>
<$> filter
filter ((/= Plus) . head) (replicateM 9 [Unsigned, Plus, Minus])
((/= Plus) . head)
filter ((/= Plus) . head) (replicateM 9 [Unsigned, Plus, Minus])
 
allNonNegativeSums :: [Int]
allNonNegativeSums = sort $ filter (>= 0) (asSum <$> universe)
sort $
filter
(>= 0)
(asSum <$> universe)
 
uniqueNonNegativeSums :: [Int]
Line 2,822 ⟶ 2,836:
asSum :: [(Int, Sign)] -> Int
asSum xs =
n +
+ ( case s of
[] -> 0
_ -> read s :: Int)
, show )
where
(n, s) = foldr readSign (0, []) xs
readSign :: (Int, Sign) -> (Int, String) -> (Int, String)
(Int, Sign) ->
(Int, String) ->
(Int, String)
readSign (i, x) (n, s)
| x == Unsigned = (n, intToDigit i : s)
| otherwise =
( ( case x of
Plus -> (+)
_ -> (-))
)
n
(read (show i <> s) :: Int),
, [])
)
 
asString :: [(Int, Sign)] -> String
Line 2,845 ⟶ 2,865:
| x == Unsigned = intToDigit i : s
| otherwise =
( case x of
Plus -> " +"
_ -> " -") <>
[intToDigit i] <>)
s <> [intToDigit i]
<> s
 
--------------------------- TEST -------------------------
main :: IO ()
main =
putStrLn $
unlines
[ "Sums to 100:",
unlines
, unlines (asString <$> filter ((100 ==) . asSum) universe),
, "\n10 commonest sums (sum, number of routes to it):",
, show
((head &&& length) <$>show
take 10 (sortBy (flip (comparing length),) (group<$> allNonNegativeSums))head <*> length)
, "\nFirst positive integer not expressible as a sum of this<$> kind:"take
10
, maybeReport (find (uncurry (/=)) (zip [0 ..] uniqueNonNegativeSums))
( sortBy
, "\n10 largest sums:"
, show (take 10 (sortBy (flip compare)(comparing uniqueNonNegativeSumslength))
(group allNonNegativeSums)
]
)
),
"\nFirst positive integer not expressible "
<> "as a sum of this kind:",
maybeReport
( find
(uncurry (/=))
, maybeReport (find (uncurry (/=)) (zip [0 ..] uniqueNonNegativeSums))
),
, "\n10 largest sums:",
show
( take
10
( sortBy
(flip compare)
uniqueNonNegativeSums
)
)
]
where
maybeReport ::
:: Show a =>
=> Maybe (a, b) -> String
String
maybeReport (Just (x, _)) = show x
maybeReport _ = "No gaps found"</lang>
9,655

edits