Advertisement
aaaaaa123456789

JV programming challenges, week 5, challenge 1

Dec 21st, 2013
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.33 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #include "common.h"
  6.  
  7. void print_permutations(const char *);
  8. void print_next_permutations(const char *, const unsigned *);
  9.  
  10. int main (void) {
  11.   printf("Input a word: ");
  12.   char * line = get_line(NULL);
  13.   if (!strlen(line)) {
  14.     free(line);
  15.     return 1;
  16.   }
  17.   print_permutations(line);
  18.   free(line);
  19.   return 0;
  20. }
  21.  
  22. void print_permutations (const char * word) {
  23.   unsigned count[256];
  24.   const char * current;
  25.   memset(count, 0, 256 * sizeof(unsigned));
  26.   for (current = word; *current; current ++) count[*current] ++;
  27.   *count = strlen(word);
  28.   print_next_permutations("", count);
  29. }
  30.  
  31. void print_next_permutations (const char * head, const unsigned * list) {
  32.   if (!*list) {
  33.     printf("%s\n", head);
  34.     return;
  35.   }
  36.   unsigned insert_point = strlen(head);
  37.   int character;
  38.   char * string = malloc(insert_point + 2);
  39.   unsigned new_count[256];
  40.   memcpy(new_count, list, sizeof(unsigned) * 256);
  41.   memcpy(string, head, insert_point);
  42.   string[insert_point + 1] = 0;
  43.   (*new_count) --;
  44.   for (character = 1; character < 256; character ++) {
  45.     if (!new_count[character]) continue;
  46.     new_count[character] --;
  47.     string[insert_point] = character;
  48.     print_next_permutations(string, new_count);
  49.     new_count[character] ++;
  50.   }
  51.   free(string);
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement