Skip to content

Instantly share code, notes, and snippets.

@bit-hack
Created August 24, 2022 17:39
Show Gist options
  • Save bit-hack/a1c2fa37ee0f9fc59a426928787ccf71 to your computer and use it in GitHub Desktop.
Save bit-hack/a1c2fa37ee0f9fc59a426928787ccf71 to your computer and use it in GitHub Desktop.
Generate all permutations of an array
#include <stdio.h>
#include <stdint.h>
void swap(uint8_t *a, uint8_t i, uint8_t j) {
uint8_t t = a[i];
a[i] = a[j];
a[j] = t;
}
void terminal(uint8_t *a) {
puts((char*)a);
}
void permute(uint8_t *a, int i, int size) {
if (i==size) {
terminal(a);
}
for (int j=i; j < size; ++j) {
swap(a, j, i);
permute(a, i+1, size);
swap(a, j, i); // unswap
}
}
int main(void) {
uint8_t a[5];
a[0] = '0';
a[1] = '1';
a[2] = '2';
a[3] = '3';
a[4] = '\0';
permute(a, 0, 4);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment