文字グループのソート

3047 ワード

1.所定の文字を組み合わせた後、辞書順に並べ替えて出力する.例:入力:a,b,c;出力:abc,acb,bac,bca,cab,cba 2.指定した文字を組み合わせた後、辞書順に並べ替えて出力します.例:入力:a,b,c;出力:a,b,c,ab,ac,bc,abc
//Example 1
#include 
#include 

void combchar(char* str, int from, int to)
{
    if(from >= to){
        for (int i = 0; i <= to; ++i){
            PRINT("%c", str[i]);
        }
        PRINT(" ");
        return;
    }

    int j = 0;
    for(int i = from; i <= to; i++){
        char tmp = str[i];
        for(j = i; j-1 >= from; --j){
            str[j] = str[j-1];
        }
        str[j] = tmp;

        combchar(str, from+1, to);

        for(j = from; j+1 <= i; ++j){
            str[j] = str[j+1];
        }
        str[j] = tmp;

        if(from == 0) PRINT("
"); } } int main(){ char str[] = {'a', 'b', 'c', 'd'}; combchar(str, 0, sizeof(str)-1); return 0; }

Example 1 Resultの結果は次のとおりです.
Example 1 Result:
abcd abdc acbd acdb adbc adcb 
bacd badc bcad bcda bdac bdca 
cabd cadb cbad cbda cdab cdba 
dabc dacb dbac dbca dcab dcba
//Example 2
#include 
#include 
#define PRINT   printf
int num = 0;
void combination(char* str, int from, int to, int len, int t)
{
    if(len == 1){
        PRINT("%c
", str[from]); ++num; for(int j = from+1; j <= to; j++){ PRINT("%*c
", 3*t+1, str[j]); ++num; } return; } for(int j = from; j <= to-len+1; j++){//1,2,3,4 PRINT("%*c->", (j==from) ? 1 : 3*t+1, str[j]); combination(str, j+1, to, len-1, t+1); } } void combination2(char* str, int from, int to, int len, int t, char* tmpStr) { if(len == 1){ for(int j = from; j <= to; j++){ tmpStr[t] = str[j]; for(int i = 0; i <= t; i++){ PRINT("%c", tmpStr[i]); } PRINT(" "); } }else{ for(int j = from; j <= to-len+1; j++){//1,2,3,4 tmpStr[t] = str[j]; combination2(str, j+1, to, len-1, t+1, tmpStr); } } if(t == 0) PRINT("
"); } void findSubStr(char* str, int from, int to) { char tmpStr[from-to+1]; for(int j = 1; j <= to-from+1; j++){//len=1,2,3,4 //combination(str, from, to, j, 0); combination2(str, j+1, to, len-1, t+1, tmpStr); PRINT("-------------------%d|%d
", j, num); } } int main(){ char str[] = {'a', 'b', 'c', 'd'}; int size = strlen(str); findSubStr(str, 0, size-1); return 0; }

Example 2 Resultの結果は次のとおりです.
Example 2 combination Result:
a
b
c
d
a->b
   c
   d
b->c
   d
c->d
a->b->c
      d
   c->d
b->c->d
a->b->c->d

Example 2 combination2 Result
a b c d 
ab ac ad bc bd cd 
abc abd acd bcd 
abcd