我编写了从classLength
元素中打印length
长度组合的代码。它工作正常,但我不明白为什么。
我的问题:
当
while(index[0] != length - classLength)
循环结束程序不打印最后一个组合,所以我必须在while
循环后打印它。为什么?
我尝试在上面提到的while
循环中更改条件。
而是length-classLength
我写了lenght-classLength+1
运行程序时会导致无限循环。为什么会这样?
请注意
的注释部分while(index[position] == maxIndex /*&& position >= 0*/)
while
循环条件和评论if
语句
/*if(position>=0)*/ index[position]++;
当代码的这些部分被取消注释并被注释时,程序将正常运行。我最初使用这些条件编写代码,因此程序无法访问具有不正确索引的数组。但是如果没有这些安全检查,这样做会很好。 为什么指数总是在范围内并且不会发生错误?
C ++代码
#include <iostream>
#include <fstream>
using namespace std;
/**Print all combinations of k-th class of n elements**/
int main() {
const int maxN = 100;
int length = 0, classLength = 0;
cout << "Input number of elements and class number: " << endl;
cin >> length >> classLength;
int array[maxN];
cout << "Input elements: " << endl;
for(int i = 0; i < length; i++)
cin >> array[i];
//first combination has indices 0, 1, ... , k-1
int index[maxN];
for(int i = 0; i < classLength; i++)
index[i] = i;
int ordNum = 1;
ofstream out("output.txt");
//length of class is classLength, last combination's last element's index is n-1
//last combination's last element's index is n-1-k
while(index[0] != length - classLength) {
//print current combination
out << ordNum++ << ")\t";
for(int i = 0; i < classLength; i++)
out << array[index[i]] << " ";
out << endl;
int position = classLength-1, maxIndex = length-1;
//if index at current position is its max
// value then we have to carry digit
while(index[position] == maxIndex /*&& position >= 0*/) {
index[position] = -1;
position--, maxIndex--;
}
//when loop stops position is at index that
//should be added the carried 1
/*if(position>=0)*/
index[position]++;
//if a carry accured indices must be arranged so that
//array index[] is non-decreasing
for(int i = 1; i < classLength; i++)
if(index[i] <= index[i-1])
index[i] = index[i-1]+1;
}
out << ordNum++ << ")\t";
for(int i = 0; i < classLength; i++)
out << array[index[i]] << " ";
out << endl;
out.close();
return 0;
}