Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include "common.h"
- void print_permutations(const char *);
- void print_next_permutations(const char *, const unsigned *);
- int main (void) {
- printf("Input a word: ");
- char * line = get_line(NULL);
- if (!strlen(line)) {
- free(line);
- return 1;
- }
- print_permutations(line);
- free(line);
- return 0;
- }
- void print_permutations (const char * word) {
- unsigned count[256];
- const char * current;
- memset(count, 0, 256 * sizeof(unsigned));
- for (current = word; *current; current ++) count[*current] ++;
- *count = strlen(word);
- print_next_permutations("", count);
- }
- void print_next_permutations (const char * head, const unsigned * list) {
- if (!*list) {
- printf("%s\n", head);
- return;
- }
- unsigned insert_point = strlen(head);
- int character;
- char * string = malloc(insert_point + 2);
- unsigned new_count[256];
- memcpy(new_count, list, sizeof(unsigned) * 256);
- memcpy(string, head, insert_point);
- string[insert_point + 1] = 0;
- (*new_count) --;
- for (character = 1; character < 256; character ++) {
- if (!new_count[character]) continue;
- new_count[character] --;
- string[insert_point] = character;
- print_next_permutations(string, new_count);
- new_count[character] ++;
- }
- free(string);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement