// This is the main project file for VC++ application project
// generated using an Application Wizard.
#include <window.h>
#include "stdafx.h"
using namespace System;
// 移動位置, 改變方式就可以改變順序.
void ShiftString( char *comb, int idx, int numChar)
{
int c, i;
for( i = numChar - idx - 1, c = comb[i]; i<numChar-1; i++)
comb[i] = comb[i+1];
comb[i] = c;
}
#define MAXNUM 10
int Combination( char *str)
{
char comb[MAXNUM];
int timesLimit[MAXNUM], curTimes[MAXNUM];
int numChar = strlen( str);
int i, idx, no;
if( numChar > MAXNUM) // Array 太小, 調一下.
return 0;
//初始資料
for( i= 0; i<numChar; i++)
{
comb[i] = str[i];
timesLimit[i] = i; // 0 -> numChar-1
curTimes[i] = 0; // 每個字都先設定第一次
}
no = 1; // 次數統計
idx = 0;
while(1)
{
// 顯示寫這,
std::cout<<comb<<",";
// 如果次數夠了, 修改回來
idx = 1;
do{
if( curTimes[idx] < timesLimit[idx])
break;
ShiftString( comb, idx, numChar);
}
while( ++idx < numChar);
// 判斷要修改的位置
idx = 0;
while(curTimes[idx] >= timesLimit[idx])
{
curTimes[idx] = 0;//前面位置規0
if( ++idx >= numChar)
return no; //偷懶下!
}
ShiftString( comb, idx, numChar);
curTimes[idx]++;
no ++; // 次數累加
}
return no; //回傳次數
}
int _tmain()
{
Combination( "12345" );
system("pause");
return 0;
}
沒有留言:
張貼留言