/*
求(1...m)中,n个数的组合
本程序的思路是开一个数组,其下标表示1到m个数,数组元素的值为1表示其下标代表的数被选中,为0则没选中。
首先初始化,将数组前n个元素置1,表示第一个组合为前n个数。
然后从左到右扫描数组元素值的“10”组合,找到第一个“10”组合后将其变为“01”组合,
同时将其左边的所有“1”全部移动到数组的最左端。
当第一个“1”移动到数组的m-n的位置,即n个“1”全部移动到最右端时,就得到了最后一个组合。
例如求5中选3的组合:
1 1 1 0 0 //1,2,3
1 1 0 1 0 //1,2,4
1 0 1 1 0 //1,3,4
0 1 1 1 0 //2,3,4
1 1 0 0 1 //1,2,5
1 0 1 0 1 //1,3,5
0 1 1 0 1 //2,3,5
1 0 0 1 1 //1,4,5
0 1 0 1 1 //2,4,5
0 0 1 1 1 //3,4,5
*/
#include <stdio.h>
#include <malloc.h>
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
#include <stdio.h>
#include <stdlib.h>
//#include <string.h>
//float x[5] = {1.0, 2.0, 3.0, 4.0, 5.0};
float x[20] = {30.00, 49.00, 7.78, 9.80, 8.30, 11.08, 6.44, 6.48, 20.00, 50.37, 34.70, 9.22, 9.12, 5.86, 63.00, 63.00, 13.64, 18.96, 7.40, 10.00};
vector<vector<int>*>* store_vect = new vector <vector<int>*> ;
//输出
void output(int *num, int m)
{
vector<int>* vect = new vector<int>;
int i;
for(i = 0; i < m; ++i){
if(*(num+i) == 1){
printf("%d ", i+1);
vect->push_back(1);
}
else{
vect->push_back(0);
}
}
printf("\n");
store_vect->push_back(vect);
}
//检测n个“1”是否全部移动到最右端
//是则返回1
int check(int *num, int m, int n)
{
int i, flag = 1;
for(i = m-1; i > m-n-1; --i)
{
if(*(num+i) == 0)
{
flag = 0;
break;
}
}
return flag;
}
void chooseNum(int m, int n)
{
int *num, i, j, count;
num = (int*)malloc(sizeof(int)*m);
for(i = 0; i < n; ++i)//前n个元素置1
*(num+i) = 1;
if(m == n)
{
output(num, m);
return;
}
for(i = n; i < m; ++i)//后面m-n个元素置0
*(num+i) = 0;
output(num, m);
while(1)
{
count = 0;
//找到第一个“10”组合后将其变为“01”组合
for(i = 0; i < m-1; ++i)
{
if(*(num+i) == 1 && *(num+i+1) == 0)
{
*(num+i) = 0;
*(num+i+1) = 1;
// printf("交换 %d %d \n", i+1, i+2);
// printf("count: %d \n", count);
break;
}
if(*(num+i) == 1)
++count;
}
//将其左边的所有“1”全部移动到数组的最左端
for(j = 0; j < i; ++j)
{
if(j < count){
*(num+j) = 1;
// printf("赋1: %d \n", j+1);
}
else{
*(num+j) = 0;
// printf("赋0: %d \n", j+1);
}
}
// printf("输出 \n");
output(num, m);
if(check(num, m, n) == 1)
break;
}
free(num);
}
int main()
{
int m = 3, n = 2;
scanf("%d%d", &m, &n);
chooseNum(m, n);
char * filename = "out.txt";
ofstream m_out;
m_out.open(filename, ios::out);
if (!m_out) {
cout << "could not Open File :" << filename << endl;
return 0;
}
m_out.seekp(0, ios::beg);
m_out.seekp(0, ios::end);
printf("=========================================\n");
int size = store_vect->size();
float sum = 0;
for (int i = 0; i < size; i++) {
sum = 0;
vector<int>* vect = store_vect->at(i);
int cnt = vect->size();
for (int j = 0; j < cnt; j++) {
int temp = vect->at(j);
if (temp == 1) {
//printf("%d ", j + 1);
m_out << j+1 << " ";
sum+=x[j];
}
}
//printf(" 和 : %f\n", sum);
m_out << " 和 : " << sum << endl;
// printf("\n");
}
printf("=========================================\n");
m_out.close();
//
//clean
int tsize = store_vect->size();
for (int i = 0; i < tsize; i++) {
vector<int>* vect = store_vect->at(i);
vect->clear();
delete vect;
vect = NULL;
}
store_vect->clear();
delete store_vect;
store_vect = NULL;
///
return 0;
}