Last active
December 20, 2015 03:59
-
-
Save chribben/6067354 to your computer and use it in GitHub Desktop.
1. Write a function that, given a sequence of either positive or negative integers, returns true if any subset of the list sums up to zero. Eg:
find-solutions ([-7 4 3 8 -5]) => true
find-solutions ([-6 2 3]) => false 2. Make it work with any number, not just zero. Eg:
find-solutions (0, [-7 4 3 8 -5]) => true
find-solutions (13, [-7 4 3 8 -5]) …
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let initMask length = List.init length (fun i -> if i = length - 1 then 1 else 0) | |
let addOne mask = List.foldBack (fun t (resList, c) -> (if (t = 1 && c = 1) then (0::resList, 1) elif (t = 0 && c= 0) then (0::resList, 0) else (1::resList, 0))) mask ([], 1) |> fst | |
let subsetsWhosSumsSatisfiesPredicate lst pred = | |
let rec work mask = seq{ | |
let sum, subSet = List.fold2 (fun (accSum, subSet) m l -> if m = 0 then (accSum, subSet) else (accSum + l, l::subSet)) (0, []) mask lst | |
if pred sum then | |
yield (List.rev subSet) | |
if List.exists (fun t -> t = 0) mask then | |
yield! work (addOne mask) | |
} | |
work (initMask (List.length lst)) | |
//Tests in repl | |
> subsetsWhosSumsSatisfiesPredicate [-7;4;3;8;-5] ((=)0);; | |
> let isEven s = s / 2 = 0;; | |
> let isOdd s = s % 2 <> 0;; | |
> subsetsWhosSumsSatisfiesPredicate [-7;4;3;8;-5] (isEven);; | |
> subsetsWhosSumsSatisfiesPredicate [-7;4;3;8;-5] (isOdd);; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment