Click here to Skip to main content
15,881,769 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C++
#include <stdio.h>
#define SWAP(a,b) {int temp = a; a = b; b = temp;}
#define N 10

void perm(char str[],int count,int t)
{
    if (t==count-1){ 
        for (int i=0;i<count;++i)
            printf("%c",str[i]);
        printf("\n");
    }
    else{
        for (int j=t;j<count;++j){
            SWAP(str[t],str[j]); 
            t++;
            perm(str,count,t); 
            t--;
            SWAP(str[t],str[j]);
        }
    }
}

int main()
{
    int t=0;
    char str[N]="";
    int count=0;
    printf("Enter a number:\n");
    gets(str);
    while(str[count]){
        count++;
    }
    printf("res:\n");
    perm(str,count,t);
    return 0;
}


What I have tried:

><
Posted
Updated 6-Dec-22 3:03am
v2
Comments
Richard MacCutchan 6-Dec-22 9:02am    
You have tagged this message Javascript and Kotlin, but the code you posted is clearly ordinary C.
Richard MacCutchan 6-Dec-22 9:06am    
What is it supposed to do? It would appear that it is trying to reorder the characters in the string.
Member 15627495 6-Dec-22 9:23am    
perm(...,...,...) is a permutation function, and use recursion, this function call itself when running.

you know for {"A","B"} , it renders {A,AA,AB,B,BB,BA}.
tu run this function , you have to fill the array str[N] = ['char_1','char_2','char_3'....,'char_9']
Member 15627495 6-Dec-22 10:57am    
in methods about recursive function, there are 'cases', often call 'simple case' and 'hard case'.
in this "perm(,,)" function, the simple case is for i<=count , so the array str is read, and not more.
the complexe case is in the 'else' statement, where more functions and processing are needed.
recursion = simple case + hard case. it's like 'easy' and 'hard'.

as a recursive function call itself, you have the perm(...,,) function in the hard case ( else statement ).

it's sometimes hard to understand but the 'loop' is done through the call of "perm(,,)" which call again pêrm(,,). the 'exit' condition is 'count' var.
recursive functions are faster than common loops.
Member 15627495 6-Dec-22 11:10am    
the two SWAP calls are 'melting' the str[] content to provide one another string content.
str[1] take the place from str[0], then a new content is available for the printf , and so and so..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900