Subset sum problem: Difference between revisions

Content added Content deleted
m (→‎{{header|REXX}}: elided comments about REXX code previously removed.)
(→‎{{header|Haskell}}: Applied hlint, hindent to second (non brute-force) variant, for legibility)
Line 865: Line 865:
<pre>["archbishop","gestapo"]</pre>
<pre>["archbishop","gestapo"]</pre>


None bruteforce: the list of numbers used here are different, and difficult for a bruteforce method.
Non brute-force: the list of numbers used here are different, and difficult for a bruteforce method.
<lang haskell>subsum w = snd.head.filter ((==w).fst).(++[(w,[])]).foldl s [(0,[])]
<lang haskell>subsum :: Int -> [Int] -> [Int]
subsum w =
where
s a x = merge a $ map f a where f (a,l) = (a+x, l++[x])
snd . head . filter ((== w) . fst) . (++ [(w, [])]) . foldl s [(0, [])]
where
s a x = merge a $ map f a
-- keep list of sums sorted and unique
where
merge [] a = a
f (a, l) = (a + x, l ++ [x])
merge a [] = a
merge a@((av,al):as) b@((bv,bl):bs)
-- Keep list of sums sorted and unique.
| av < bv = (av,al):merge as b
merge [] a = a
| av == bv = (bv,bl):merge as bs
| otherwise = (bv,bl):merge a bs
merge a [] = a
merge a@((av, al):as) b@((bv, bl):bs)
| av < bv = (av, al) : merge as b
| av == bv = (bv, bl) : merge as bs
| otherwise = (bv, bl) : merge a bs
items :: [Int]
items = [-61, 1, 32, 373, 311, 249, 311, 32, -92, -185, -433,
items = [-61, 1, 32, 373, 311, 249, 311, 32, -92, -185, -433,
-402, -247, 156, 125, 249, 32, -464, -278, 218, 32, -123,
-402, -247, 156, 125, 249, 32, -464, -278, 218, 32, -123,
-216, 373, -185, -402, 156, -402, -61, -31, 902 ]
-216, 373, -185, -402, 156, -402, -61, -31, 902 ]

main :: IO ()
main = print $ subsum 0 items</lang>
main = print $ subsum 0 items</lang>
{{out}}
{{out}}
<pre>[-61,32,373,311,249,311,32,-92,-185,-433,-402,-247,156,125,249,32,-464,-278,218,32,-123,-216,373,-185,-402,156,-402,-61,902]</pre>
<pre>
[-61,32,373,311,249,311,32,-92,-185,-433,-402,-247,156,125,249,32,-464,-278,218,32,-123,-216,373,-185,-402,156,-402,-61,902]
</pre>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==