diff options
author | Alexandre Jesus <adbjesus@gmail.com> | 2017-11-06 18:27:28 +0000 |
---|---|---|
committer | Alexandre Jesus <adbjesus@gmail.com> | 2017-11-06 18:27:28 +0000 |
commit | 01c757e09afbc6ae401a56e9f588b21cea54b613 (patch) | |
tree | 1d516f02c731ee7f2dff19b0dfddbafb4c041788 /src/common.c | |
parent | 3333e0c5a1a8e39c74fb178ac124940844463520 (diff) | |
download | libuknapsack-01c757e09afbc6ae401a56e9f588b21cea54b613.tar.gz libuknapsack-01c757e09afbc6ae401a56e9f588b21cea54b613.zip |
Add nem_ull with shuffle
Diffstat (limited to 'src/common.c')
-rw-r--r-- | src/common.c | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/src/common.c b/src/common.c index 7a8b316..5fc944e 100644 --- a/src/common.c +++ b/src/common.c @@ -111,3 +111,33 @@ int len_front(struct front_item * f){ for(N=0;f!=NULL;f=f->next,N++); return N; } + +/* Shuffle data items starting on a certain index, in place */ +void shuffle_items(struct data * d, int start) { + int i, ind; + struct item * new_items; + + if (start < 0) return; + if (start >= d->N) return; + + new_items = (struct item *)malloc(d->N * sizeof(struct item)); + + /* These stay the same */ + for(i = 0; i < start; i++) { + new_items[i].p = d->items[i].p; + new_items[i].w = d->items[i].w; + } + + /* Shuffle the rest */ + for(i = start; i < d->N; i++) { + ind = rand() % (d->N - i); + new_items[i].p = d->items[i+ind].p; + new_items[i].w = d->items[i+ind].w; + d->items[i+ind].p = d->items[i].p; + d->items[i+ind].w = d->items[i].w; + } + + /* Replace old array */ + free(d->items); + d->items = new_items; +} |