How to print all possible permutations (all possible orderings) of the words in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>

void swap(char **a, char **b) {
    char *temp = *a;
    *a = *b;
    *b = temp;
}

void print_words_permutations(char *words[], int left, int right) {
    if (left == right) {
        for (int i = 0; i <= right; i++) {
            printf("%s%s", words[i], (i < right ? " " : ""));
        }
        printf("\n");
        return;
    }

    for (int i = left; i <= right; i++) {
        swap(&words[left], &words[i]);
        print_words_permutations(words, left + 1, right);
        swap(&words[left], &words[i]); // backtrack
    }
}

int main() {
    char *words[] = {"word-1", "word-2", "word-3"};
    int n = sizeof(words) / sizeof(words[0]);

    print_words_permutations(words, 0, n - 1);

    return 0;
}


/*
run:

word-1 word-2 word-3
word-1 word-3 word-2
word-2 word-1 word-3
word-2 word-3 word-1
word-3 word-2 word-1
word-3 word-1 word-2

*/

 



answered Apr 14 by avibootz

Related questions

...