Added algorithm for generating random permutations of the set of nodes

This commit is contained in:
zenon 2018-05-31 12:17:25 +02:00
parent b43a600510
commit 0ae6626e32

View File

@ -7,6 +7,7 @@
#include "common.h"
#include <limits.h>
#include <time.h>
static const char *pname;
@ -105,7 +106,7 @@ void parse(int argc, char *argv[])
str = orig_copy = strdup(edge);
int count = 0;
while ((token = strsep(&str, "-"))) {
if (str == NULL) {
if (strcmp(token, edge) == 0 && str == NULL) {
fprintf(stderr, "[%s] An edge consists of two "
"nodes separated by a dash\n", pname);
free(orig_copy);
@ -190,6 +191,23 @@ void cleanup()
free(graph.array);
}
void genSolution(int permutation[])
{
int r;
for (int i = 0; i < graph.V; i++) {
permutation[i] = i;
}
for (int i = (graph.V - 1); i > 0; i--) {
r = rand() % (i+1);
int tmp = permutation[r];
permutation[r] = permutation[i];
permutation[i] = tmp;
}
}
int main(int argc, char *argv[])
{
if (argc == 1)
@ -226,8 +244,19 @@ int main(int argc, char *argv[])
parse(argc, argv);
srand(time(NULL));
int permutation[graph.V];
while (quit == 0) {
printGraph();
for (int i = 0; i < 10; i++) {
genSolution(permutation);
printf("[");
for (int i = 0; i < (graph.V - 1); i++) {
printf("%d, ", permutation[i]);
}
printf("%d]\n", permutation[graph.V-1]);
}
break;
}