ocaml: phase 5.1 subset_sum.ml baseline (count subsets of [1..8] summing to 10 = 8)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 45s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 45s
Pure recursion — at each element, take it or don't:
let rec count_subsets xs target =
match xs with
| [] -> if target = 0 then 1 else 0
| x :: rest ->
count_subsets rest target
+ count_subsets rest (target - x)
For [1;2;3;4;5;6;7;8] target 10, the recursion tree has 2^8 = 256
leaves. Returns 8 — number of subsets summing to 10:
1+2+3+4, 1+2+7, 1+3+6, 1+4+5, 2+3+5, 2+8, 3+7, 4+6 = 8
Tests doubly-recursive list traversal pattern with single-arg list
+ accumulator-via-target.
65 baseline programs total.
This commit is contained in:
@@ -57,6 +57,7 @@
|
||||
"run_length.ml": 11,
|
||||
"safe_div.ml": 20,
|
||||
"shuffle.ml": 55,
|
||||
"subset_sum.ml": 8,
|
||||
"word_freq.ml": 8,
|
||||
"zip_unzip.ml": 1000,
|
||||
"sieve.ml": 15,
|
||||
|
||||
10
lib/ocaml/baseline/subset_sum.ml
Normal file
10
lib/ocaml/baseline/subset_sum.ml
Normal file
@@ -0,0 +1,10 @@
|
||||
let rec count_subsets xs target =
|
||||
match xs with
|
||||
| [] -> if target = 0 then 1 else 0
|
||||
| x :: rest ->
|
||||
count_subsets rest target
|
||||
+ count_subsets rest (target - x)
|
||||
|
||||
;;
|
||||
|
||||
count_subsets [1; 2; 3; 4; 5; 6; 7; 8] 10
|
||||
Reference in New Issue
Block a user