今天有個網友問我組合數生成算法的問題,這個寫的早,只給他回復了原理。剛好這段時間玩“15選5”,知道那個是隨機的,概率問題(中就是中了,沒中就是沒中),沒啥好分析的,可還是忍不住想計算下……
好,不廢話了,下面開工。
一、原理
借助二進制計數的機制來進行,比如字符串“123”中選出兩個字符,如下計算:
1:二進制串為 0001
2: 0010
3: 0011
4: 0100
5: 0101
6: 0110
7: 0111
8: 1000
其中含有兩個1的有
3: 0011
5: 0101
6: 0110
所以一共3個
如果是1顯示當前位置數據,不是1則不顯示,用字符串“123”匹配后結果為:
23
1 3
12
即:
23
13
12
方法很土,不過可以實現功能,夠一般用。
二、示例代碼
下面是C++的示例代碼:
View Code
1 /*
2 File : combination.cpp
3 Author : Mike
4 E-Mail : Mike_Zhang@live.com
5 */
6 #include <cstdio>
7 #include <cstdlib>
8 #include <iostream>
9 #include <string>
10 #include <vector>
11
12 using namespace std;
13
14 //計算數據中二進制數據中1的個數
15 int count(unsigned int v)
16 {
17 int ret = 0;
18 while(v>0)
19 {
20 v &= (v-1);
21 ++ret;
22 }
23 return ret;
24 }
25
26 //檢測pos位置的二進制數據是否是1
27 bool check(unsigned int v,int pos)
28 {
29 unsigned int tmp=0x01;
30 int sz = sizeof(v)*8;
31 if(pos > sz)
32 {
33 printf("pos > sz\r\n");
34 return -1;
35 }
36 tmp <<= pos;
37 return (v & tmp);
38 }
39
40 int main()
41 {
42 int i=0,j=0;
43 vector<string> vstr;
44 int szvstr = 0;
45 string str="";
46 int num = 0;
47 cout<<"Input size of vector : ";
48 cin>>szvstr;
49
50 for(i=0;i<szvstr;++i)
51 {
52 cout<<"Input string : ";
53 cin>>str;
54 vstr.push_back(str);
55 }
56 //簡單檢查數據
57 while(num > szvstr or num ==0 )
58 {
59 cout<<"Input number : ";
60 cin>>num;
61 }
62
63 unsigned int counter = 1;
64 counter <<= szvstr;
65 int szUnsign = sizeof(unsigned int) * 8;
66
67 int total = 0;
68 //輸出組合結果
69 for(i=0;i<counter;++i)
70 {
71 if(num == count(i))
72 {
73 for(j=0;j<szUnsign && j < szvstr;++j)
74 {
75 if(check(i,j))
76 cout<<vstr[j] << " ";
77 }
78 cout<<endl;
79 ++total;
80 }
81 }
82 cout <<"total = "<<total<<endl;
83 }
三、運行效果
1、輸入數據:
首先輸入集合的大小,比如15
接下來輸入每個元素,比如01、02、03。。。15
最后輸入要選的組合,比如“15選5”的話就輸入5
具體如下:

2、執行結果:
這里會輸出各種組合(“15選5”的各種組合),並輸出各種組合的總個數,具體如下:

其他:
python實現代碼:
import itertools
tmpL=[]
for i in range(1,16):
tmpL.append("%02d" % i)
cmbResult = list(itertools.combinations(tmpL,5))
for data in cmbResult :
print data
print len(cmbResult)
好,就這些了,希望對你有幫助。
