Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,938 questions

51,875 answers

573 users

How to generate all possible permutations of a string in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
 
void swap(char *si, char *sj) {
 
    char temp;
 
    temp = *si;
    *si = *sj;
    *sj = temp;
}
 
void print_permutations(char *s, int i, int len) {
   if (i == len)
       printf("%s\n", s);
   else {
        for (int j = i; j <= len; j++) {
            swap((s + i), (s + j));
            print_permutations(s, i + 1, len);
            swap((s + i), (s + j));
       }
   }
} 
 
int main(void) {
   char s[10] = "abcd";
 
   print_permutations(s, 0, strlen(s) - 1);
 
   return 0;
 
}
 
 
 
/*
run:
 
abcd
abdc
acbd
acdb
adcb
adbc
bacd
badc
bcad
bcda
bdca
bdac
cbad
cbda
cabd
cadb
cdab
cdba
dbca
dbac
dcba
dcab
dacb
dabc
 
*/

 



answered Feb 16, 2021 by avibootz
edited Feb 16, 2021 by avibootz
...