Skip to content

Instantly share code, notes, and snippets.

@svagionitis
Last active August 29, 2015 14:16
Show Gist options
  • Save svagionitis/7a5fefc86589206bcc2e to your computer and use it in GitHub Desktop.
Save svagionitis/7a5fefc86589206bcc2e to your computer and use it in GitHub Desktop.
Permutations using the algorithms described http://www.quickperm.org/pseudo2.php
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#define SZ_ARRAY 5
void swap_array(uint64_t arr[], uint64_t i, uint64_t j)
{
arr[i] ^= arr[j];
arr[j] ^= arr[i];
arr[i] ^= arr[j];
}
void circular_shift_to_left(uint64_t arr[], uint64_t sz)
{
for (uint64_t i = 0;i<sz-1;i++)
swap_array(arr, i, i+1);
}
void circular_shift_to_left_by(uint64_t arr[], uint64_t sz, uint64_t num_shift)
{
for (uint64_t s = 0;s<num_shift;s++)
{
for (uint64_t i = 0;i<sz-1;i++)
swap_array(arr, i, i+1);
}
}
void print_array(uint64_t arr[], uint64_t sz)
{
for (uint64_t i = 0;i<sz;i++)
fprintf(stdout, "%ju", arr[i]);
fprintf(stdout, "\n");
}
void algo1(const uint64_t arr[], uint64_t sz)
{
uint64_t a[SZ_ARRAY] = {0};
uint64_t p[SZ_ARRAY] = {0};
memcpy(a, arr, sz*sizeof(uint64_t));
for (uint64_t i = 0;i<sz;i++)
p[i] = i;
uint64_t i = 1;
while(i < sz)
{
p[i]--;
uint64_t j = 0;
if (i%2 != 0)
j = p[i];
swap_array(a, j, i);
print_array(a, sz);
i = 1;
while(p[i] == 0)
{
p[i] = i;
i++;
}
}
}
void algo2(const uint64_t arr[], uint64_t sz)
{
uint64_t counter = 0;
uint64_t a[SZ_ARRAY] = {0};
uint64_t p[SZ_ARRAY] = {0};
memcpy(a, arr, sz*sizeof(uint64_t));
for (uint64_t i = 0;i<sz;i++)
p[i] = i;
uint64_t i = 1;
uint64_t j = 0;
while(i < sz)
{
if (p[i] > 0)
{
p[i]--;
j = 0;
if (i%2 != 0)
j = p[i];
swap_array(a, j, i);
print_array(a, sz);
counter++;
i = 1;
}
else
{
p[i] = i;
i++;
}
}
fprintf(stdout, "Permutations counted for size %ju is %ju.\n", sz, counter);
}
// It's not working
void myalgo(const uint64_t arr[], uint64_t sz)
{
uint64_t counter = 0;
uint64_t a[SZ_ARRAY] = {0};
memcpy(a, arr, sz*sizeof(uint64_t));
uint64_t k = 0;
uint64_t tmp[SZ_ARRAY] = {0};
memcpy(tmp, a, sz*sizeof(uint64_t));
while(k<sz-2)
{
for (uint64_t i = 0;i<sz-1;i++)
{
swap_array(tmp, i, i+1);
print_array(tmp, sz);
counter++;
}
for (uint64_t i = sz-2;i>1;i--)
{
swap_array(tmp, i-1, i);
print_array(tmp, sz);
counter++;
}
k++;
}
fprintf(stdout, "Permutations counted for size %ju is %ju.\n", sz, counter);
}
int main(int argc, char *argv[])
{
// Initial array
const uint64_t arr[SZ_ARRAY] = {1, 2, 3, 4, 5};
algo2(arr, SZ_ARRAY);
myalgo(arr, SZ_ARRAY);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment