-
-
Save eric-vader/e4fff61ebac3614339f5de9a95f56fb9 to your computer and use it in GitHub Desktop.
problem24.1.c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string.h> | |
#include <stdio.h> | |
#include <stdbool.h> | |
void swap(char a[], size_t i, size_t j) { | |
char temp = a[i]; | |
a[i] = a[j]; | |
a[j] = temp; | |
} | |
bool swapped_before(char a[], size_t k, size_t i) { | |
for (size_t j=k; j<i; j++) { | |
if (a[j] == a[i]) { | |
return true; | |
} | |
} | |
return false; | |
} | |
/** | |
* Fix a[0]..a[k - 1] but permute characters a[k]..a[len - 1] | |
* Print out each permutation. | |
* | |
* @param[in,out] a The array to permute | |
* @param[in] n The size of the array | |
* @param[in] k The starting index at which we will permute | |
* | |
* @post The string a remains unchanged | |
*/ | |
void permute(char a[], size_t n, size_t k) { | |
if (k == n-1) { | |
printf("%s\n", a); | |
return; | |
} | |
for (size_t i = k; i < n; i+= 1) { | |
if(!swapped_before(a, k, i)) { | |
swap(a, k, i); | |
permute(a, n, k+1); | |
swap(a, i, k); | |
} | |
} | |
} | |
int main() { | |
char str[] = "aaa"; | |
permute(str, strlen(str), 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment