35static int randint(
int n_max) {
40 y = div(-RAND_MAX-1, -n_max-1);
43 while (x > RAND_MAX + y.rem);
47#include <gsl/gsl_rng.h>
50static int randint(
int n_max) {
51 return gsl_rng_uniform_int(rng, n_max+1);
65struct problem *newProblem(
const char *filename) {
68 int i, n=-1, capacity=-1;
69 infile = fopen(filename,
"r");
71 fscanf(infile,
"%d", &n);
72 fscanf(infile,
"%d", &capacity);
73 if (n > 0 && capacity > 0) {
75 p->weight = (
int *) malloc(n *
sizeof (
int));
76 p->profit = (
int *) malloc(n *
sizeof (
int));
77 for (i = 0; i < n; i++)
78 fscanf(infile,
"%d %d", p->profit+i, p->weight+i);
80 p->capacity = capacity;
82 fprintf(stderr,
"Invalid knapsack instance %s\n", filename);
85 fprintf(stderr,
"Cannot open file %s\n", filename);
102 s->data = (
char*) malloc(p->n * sizeof (
char));
108 struct move *v = (
struct move*) malloc(
sizeof (
struct move));
115 ps->pos = (
int*) malloc(p->n * sizeof (
int));
121void freeProblem(
struct problem *p) {
127void freeSolution(
struct solution *s) {
132void freeMove(
struct move *v) {
136void freePathState(
struct pathState *ps) {
150void printProblem(
struct problem *p) {
152 printf(
"Knapsack problem instance\n");
153 printf(
" Number of items: %d\n", p->n);
154 printf(
" Capacity: %d\n", p->capacity);
156 for (i = 0; i < p->n; i++)
157 printf(
" %d", p->weight[i]);
160 for (i = 0; i < p->n; i++)
161 printf(
" %d", p->profit[i]);
165void printSolution(
struct solution *s) {
168 printf(
"Knapsack solution\n x:");
169 for (i = 0; i < n; i++)
170 printf(
" %c", s->data[i]+
'0');
174void printMove(
struct move *v) {
175 printf(
"Knapsack move\n Flip x[%d]\n", v->data);
178void printPathState(
struct pathState *ps) {
180 printf(
"Path state\n");
181 printf(
" Path length: %d\n Positions:", ps->distance);
182 for (i = 0; i < ps->distance; i++)
183 printf(
" %d", ps->pos[i]);
200 for (i = 0; i < n; i++)
201 s->data[i] = randint(1);
203 s->profit = 0, s->weight = 0;
204 for (i = 0; i < n; i++)
206 s->profit += p->profit[i];
207 s->weight += p->weight[i];
209 s->objvalue = s->weight - p->capacity;
210 if (s->objvalue <= 0)
211 s->objvalue = -s->profit;
217double getObjectiveValue(
struct solution *s) {
218 return (
double)s->objvalue;
228 v->data = randint(s->n-1);
235 dest->prob = src->prob;
237 dest->profit = src->profit;
238 dest->weight = src->weight;
239 memcpy(dest->data, src->data, src->n * sizeof (
char));
240 dest->objvalue = src->objvalue;
251 if (i < 0 || i >= s->n)
253 if (s->data[i] == 0) {
255 s->weight += p->weight[i];
256 s->profit += p->profit[i];
259 s->weight -= p->weight[i];
260 s->profit -= p->profit[i];
262 s->objvalue = s->weight - p->capacity;
263 if (s->objvalue <= 0)
264 s->objvalue = -s->profit;
277 for (i = 0, k = 0; i < n; i++)
278 if (s1->data[i] != s2->data[i])
291 for (i = 0; i < n; i++)
306 if (ps->distance == 0) {
311 r = randint(--ps->distance);
312 v->data = ps->pos[r];
314 ps->pos[r] = ps->pos[ps->distance];
324int getPathLength(
const struct pathState *ps) {