fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. // Function to compare strings lexicographically for sorting
  6. int compare(const void *a, const void *b) {
  7. return strcmp((char *)a, (char *)b);
  8. }
  9.  
  10. // Function to generate the next lexicographical permutation
  11. int next_permutation(char *str) {
  12. int i = strlen(str) - 1;
  13.  
  14. // Step 1: Find the rightmost character which is smaller than the next character
  15. while (i > 0 && str[i - 1] >= str[i]) {
  16. i--;
  17. }
  18.  
  19. // Step 2: If there is no such character, we've generated all permutations
  20. if (i == 0) {
  21. return 0;
  22. }
  23.  
  24. // Step 3: Find the character to swap with (next larger character to the right)
  25. int j = strlen(str) - 1;
  26. while (str[j] <= str[i - 1]) {
  27. j--;
  28. }
  29.  
  30. // Step 4: Swap the characters
  31. char temp = str[i - 1];
  32. str[i - 1] = str[j];
  33. str[j] = temp;
  34.  
  35. // Step 5: Reverse the suffix
  36. j = strlen(str) - 1;
  37. while (i < j) {
  38. temp = str[i];
  39. str[i] = str[j];
  40. str[j] = temp;
  41. i++;
  42. j--;
  43. }
  44.  
  45. return 1;
  46. }
  47.  
  48. void generatePermutations(char *str) {
  49. // Sort the string to get the first permutation in lexicographical order
  50. qsort(str, strlen(str), sizeof(char), compare);
  51.  
  52. // Print the first permutation
  53. printf("%s ", str);
  54.  
  55. // Generate and print the next permutations until no more are possible
  56. while (next_permutation(str)) {
  57. printf("%s ", str);
  58. }
  59.  
  60. printf("\n");
  61. }
  62.  
  63. int main() {
  64. int T;
  65. scanf("%d", &T); // Read number of test cases
  66.  
  67. while (T--) {
  68. char str[6]; // Only up to 5 characters are allowed
  69. scanf("%s", str); // Read the string
  70. generatePermutations(str); // Generate and print permutations
  71. }
  72.  
  73. return 0;
  74. }
  75.  
Success #stdin #stdout 0.01s 5268KB
stdin
2
acb
sad
stdout
abc acb bac bca cab cba 
ads asd das dsa sad sda