Jump to content

  • Log In with Google      Sign In   
  • Create Account

#ActualÁlvaro

Posted 11 December 2012 - 07:38 AM

What you call "remap" is usually called a "permutation".

This is how I would write the code:
#include <stdio.h>
#include <inttypes.h>
#include <string.h>

void apply_kth_permutation(uint8_t *array, unsigned n, unsigned k) {
  for (unsigned i = 0; i < n; ++i) {
	unsigned j = i + (k % (n-i));
    k /= n-i;
	uint8_t temp = array[i];
	array[i] = array[j];
	array[j] = temp;
  }
}

int main() {
  uint8_t s[5] = "abcd";
  uint8_t a[5];
  for (unsigned k=0; k<24; ++k) {
	memcpy(a, s, 5);
	apply_kth_permutation(a, 4, k);
	puts(a);
  }
}

#1Álvaro

Posted 11 December 2012 - 07:36 AM

What you call "remap" is usually called a "permutation".

This is how I would write the code:
#include <stdio.h>
#include <inttypes.h>
#include <string.h>

void apply_kth_permutation(uint8_t *array, unsigned n, unsigned k) {
  for (unsigned i = 0; i < n; ++i) {
    unsigned j = i + (k % (n-i));
    uint8_t temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
}

int main() {
  uint8_t s[5] = "abcd";
  uint8_t a[5];
  for (unsigned k=0; k<24; ++k) {
    memcpy(a, s, 5);
    apply_kth_permutation(a, 4, k);
    puts(a);
  }
}

PARTNERS