Today, we used the algorithm for solving the composite sequence and implemented it using C ++ and OCaml.
Problem description: There are arrays (linked lists, etc.) a, length len, and n elements are extracted from them to give all the removal sequences.
This is the problem of arrangement and combination. There are a total of C (len, n) sequences, which were once done by High School. The implementation process is actually relatively simple, as follows:
If the current position is s, a [s] can be obtained first, and n-1 elements are extracted from the remaining elements to form a sequence;
Or n elements are extracted from the remaining elements as a sequence instead of a [s ].
Iterate this process
C ++ code
#include<iostream>#include<vector>using namespace std;vector<vector<int> > pick(int l[],int s,int e,int n){vector<vector<int> > v;if(e-s+1>=n&&n>0){vector<vector<int> > res1 = pick(l,s+1,e,n-1);int size=res1.size();if(size>0){for(int i=0;i<size;i++){res1[i].push_back(l[s]);}}else{vector<int> tmp;tmp.push_back(l[s]);res1.push_back(tmp);}vector<vector<int> > res2 = pick(l,s+1,e,n);size=res2.size();for(int i=0;i<size;i++){res1.push_back(res2[i]);}v= res1;}return v;}int main(){int coe[]={1,2,3,4,5};vector<vector<int> > res = pick(coe,0,4,3);int size=res.size();for (int i=0;i<size;i++){vector<int> v=res[i];int len=v.size();for (int j=0;j<len;j++){cout<<v[j]<<",";}cout<<endl;}}
Running result
OCaml code
1 let rec pick a s e len =
2 let v = ref [] in
3 if e-s+1>=len&&len>0 then
4 begin
5 let len0 = len in
6 let res1 = pick a (s+1) e (len-1) in
7 let len = List.length !res1 in
8 let ele = List.nth a s in
9 if len>0 then
10 begin
11 List.iter(fun r->
12 r := ele::!r;
13 )!res1;
14 end else
15 begin
16 res1 := [ref [ele]];
17 end;
18
19 let res2 = pick a (s+1) e len0 in
20 List.iter(fun r->
21 res1 := r::!res1;
22 )!res2;
23
24 v := !res1;
25 end;
26
27 v
28 in
29
30 let a = [1;2;3;4;5] in
31 let res = pick a 0 4 3 in
32
33 List.iter(fun r->
34 List.iter(fun r1->
35 Printf.printf "%d," r1;
36 )!r;
37 Printf.printf "\n";
38 )!res;
Running result