ECF 1.5
knapsack-shd.c
1/* knapsack-shd.c
2 *
3 * (C) 2018 Carlos M. Fonseca <cmfonsec@dei.uc.pt>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or (at
8 * your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 */
19
20#include <stdlib.h>
21#include <stdio.h>
22#include <time.h>
23#include <gsl/gsl_rng.h>
24#include "knapsack.h"
25#include "shd.h"
26
27gsl_rng *rng; /* The single rng instance used by the whole code */
28
29int main(int argc, char **argv) {
30 struct problem *p;
31 struct solverState *ss;
32 int max_iter, i;
33 double cost, mincost;
34
35 if (argc < 3) {
36 fprintf(stderr, "Usage: %s <file name> <max iter>\n", argv[0]);
37 return 0;
38 }
39
40 /* Set up random number generation */
41 rng = gsl_rng_alloc(gsl_rng_mt19937);
42 gsl_rng_set(rng, time(0));
43
44 /* Input arguments */
45 max_iter = atoi(argv[2]);
46
47 /* Problem and solver instantiation */
48 p = newProblem(argv[1]);
49 if (p != NULL) {
50 ss = newSolver(p);
51
52 /* Run */
53 mincost = getObjectiveValue(getSolverSolution(ss));
54 printf("iter = 0, obj = %.0f\n", mincost);
55 for (i = 0; i < max_iter; i++) {
56 nextSolverState(ss);
57 cost = getObjectiveValue(getSolverSolution(ss));
58 if (cost < mincost) {
59 mincost = cost;
60 printf("iter = %d, obj = %.0f\n", i+1, mincost);
61 }
62 }
63
64 /* Report result */
65 printSolution(getSolverSolution(ss));
66
67 /* Clean up */
68 freeSolver(ss);
69 freeProblem(p);
70 }
71 gsl_rng_free(rng);
72 return 0;
73}
74