[C/C++ 演算法]- 產生可能的清單(字典順序)

[C/C++ 演算法]- 產生可能的清單(字典順序)

[C/C++ 演算法]- 產生可能的清單(字典順序)

剛才找資料時發現一個C/C++的教學網站,趕快發揮(C/P)的長才將它備份來,有需要的同好,歡迎來(C/P)一下^^。

拷貝來源:
http://openhome.cc/Gossip/AlgorithmGossip/
http://openhome.cc/Gossip/AlgorithmGossip/PossibleSet2.htm

#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20

void print(int*);
int getPosition(int*);
int hasNext(int*, int);
void next(int*, int);
int main(void) {
int list[MAXSIZE] = {0};
int n;
printf("輸入清單個數:");
scanf("%d", &n);
print(list);
while(hasNext(list, n)) {
next(list, n);
print(list);
}
return 0;
}
void print(int* list) {
printf("[");
int i, position;
for(i = 0, position = getPosition(list); i < position; i++) {
printf("%d, ", list[i]);
}
printf(position == -1 ? "]\n" : "%d]\n", list[i]);
}
int getPosition(int* list) {
int i;
for(i = 0; list[i] != 0; i++);
return i - 1;
}
int hasNext(int* list, int n) {
int position = getPosition(list);
return position == -1 || list[position] < n || position != 0;
}
void next(int* list, int n) {
int position = getPosition(list);
if(position == -1) {           // 第一個非空清單
        list[0] = 1;
}
else if(list[position] < n) {  // 遞增清單個數
        list[position + 1] = list[position] + 1;
}
else if(position != 0) {       // 如果不是第一個位置
        list[position] = 0;
list[position - 1]++;      // 下一個清單尾數
    }
}

 

 

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *