From 47979bb844eda3821f08c1f00afc081ee0a3a260 Mon Sep 17 00:00:00 2001 From: Nathan Wagner Date: Sun, 21 Sep 2014 13:02:48 +0000 Subject: [PATCH 2/2] rewrote array shuffler for geqo_recombination This simplifies the array shuffling by doing it inplace and eliminating a memory allocation and array initialization. The output is identical in the sense that it still randomizes an array, but the actual shuffled array will be different. --- src/backend/optimizer/geqo/geqo_recombination.c | 32 +++++++------------------ 1 file changed, 9 insertions(+), 23 deletions(-) diff --git a/src/backend/optimizer/geqo/geqo_recombination.c b/src/backend/optimizer/geqo/geqo_recombination.c index 652fadc..b327776 100644 --- a/src/backend/optimizer/geqo/geqo_recombination.c +++ b/src/backend/optimizer/geqo/geqo_recombination.c @@ -37,31 +37,17 @@ void init_tour(PlannerInfo *root, Gene *tour, int num_gene) { - Gene *tmp; - int remainder; - int next, - i; + int i, j; - /* Fill a temp array with the IDs of all not-yet-visited cities */ - tmp = (Gene *) palloc(num_gene * sizeof(Gene)); - - for (i = 0; i < num_gene; i++) - tmp[i] = (Gene) (i + 1); - - remainder = num_gene - 1; - - for (i = 0; i < num_gene; i++) - { - /* choose value between 0 and remainder inclusive */ - next = geqo_randint(root, remainder, 0); - /* output that element of the tmp array */ - tour[i] = tmp[next]; - /* and delete it */ - tmp[next] = tmp[remainder]; - remainder--; + /* shuffle tour in-place, uses Fisher-Yates inside-out algorithm */ + for (i=0; i < num_gene; i++) { + j = geqo_randint(root, i, 0); + /* we could skip the compare and just assign */ + if (i != j) { + tour[i] = tour[j]; + } + tour[j] = (Gene) i+1; } - - pfree(tmp); } /* alloc_city_table -- 2.5.0