chiark / gitweb /
less printing, optimise
[matchsticks-search.git] / main.c
1
2 #include <stdio.h>
3 #include <stdint.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <assert.h>
7 #include <inttypes.h>
8
9 #include <publib.h>
10 #include <glpk.h>
11
12 typedef uint32_t AdjWord;
13 #define PRADJ "08"PRIx32
14
15 static int n, m;
16 static AdjWord *adjmatrix;
17 static AdjWord adjall;
18
19 static double best;
20 static glp_prob *best_prob;
21 static AdjWord *best_adjmatrix;
22
23 static unsigned printcounter;
24
25 static AdjWord *xalloc_adjmatrix(void) {
26   return xmalloc(sizeof(*adjmatrix)*n);
27 }
28
29 static void prep(void) {
30   adjall = ~((~(AdjWord)0) << m);
31   adjmatrix = xalloc_adjmatrix();
32   glp_term_out(GLP_OFF);
33 }
34
35 static AdjWord one_adj_bit(int bitnum) {
36   return (AdjWord)1 << bitnum;
37 }
38
39 static int count_set_adj_bits(AdjWord w) {
40   int j, total;
41   for (j=0, total=0; j<m; j++)
42     total += !!(w & one_adj_bit(j));
43   return total;
44 }
45
46 static void optimise(int doprint) {
47   glp_prob *prob = 0;
48   int i, j, totalfrags;
49
50   for (i=0, totalfrags=0; i<n; i++) {
51     int frags = count_set_adj_bits(adjmatrix[i]);
52     totalfrags += frags;
53     if (doprint) printf("%"PRADJ" ", adjmatrix[i]);
54     double maxminsize = (double)m / frags;
55     if (maxminsize < best) {
56       if (doprint) printf(" too fine");
57       goto out;
58     }
59   }
60
61   /*
62    * We formulate our problem as an LP problem as follows.
63    * In this file "n" and "m" are the matchstick numbers.
64    *
65    * Each set bit in the adjacency matrix corresponds to taking a
66    * fragment from old match i and making it part of new match j.
67    *
68    * The structural variables (columns) are:
69    *   x_minimum        minimum size of any fragment (bounded below by 0)
70    *   x_morefrag_i_j   the amount by which the size of the fragment
71    *                     i,j exceeds the minimum size (bounded below by 0)
72    *
73    * The auxiliary variables (rows) are:
74    *   x_total_i       total length for each input match (fixed variable)
75    *   x_total_j       total length for each output match (fixed variable)
76    *
77    * The objective function is simply
78    *   maximise x_minimum
79    *
80    * We use X_ and Y_ to refer to GLPK's (1-based) column and row indices.
81    * ME_ refers to entries in the list of constraint matrix elements
82    * which we build up as we go.
83    */
84
85   prob = glp_create_prob();
86
87   int Y_totals_i = glp_add_rows(prob, n);
88   int Y_totals_j = glp_add_rows(prob, m);
89   int X_minimum = glp_add_cols(prob, 1);
90
91   {
92   int next_matrix_entry = 1; /* wtf GLPK! */
93   int matrix_entries_size = next_matrix_entry + n + m + totalfrags*2;
94   double matrix_entries[matrix_entries_size];
95   int matrix_entries_XY[2][matrix_entries_size];
96
97 #define ADD_MATRIX_ENTRY(Y,X) ({                        \
98       assert(next_matrix_entry < matrix_entries_size);  \
99       matrix_entries_XY[0][next_matrix_entry] = (X);    \
100       matrix_entries_XY[1][next_matrix_entry] = (Y);    \
101       matrix_entries[next_matrix_entry] = 0;            \
102       next_matrix_entry++;                              \
103     })
104
105   int ME_totals_i__minimum = next_matrix_entry;
106   for (i=0; i<n; i++) ADD_MATRIX_ENTRY(Y_totals_i+i, X_minimum);
107
108   int ME_totals_j__minimum = next_matrix_entry;
109   for (j=0; j<m; j++) ADD_MATRIX_ENTRY(Y_totals_j+j, X_minimum);
110
111   /* \forall_i x_totals_i = m */
112   /* \forall_i x_totals_j = n */
113   for (i=0; i<n; i++) glp_set_row_bnds(prob, Y_totals_i+i, GLP_FX, m,m);
114   for (j=0; j<m; j++) glp_set_row_bnds(prob, Y_totals_j+j, GLP_FX, n,n);
115
116   /* x_minimum >= 0 */
117   glp_set_col_bnds(prob, X_minimum, GLP_LO, 0, 0);
118
119   /* objective is maximising x_minimum */
120   glp_set_obj_dir(prob, GLP_MAX);
121   glp_set_obj_coef(prob, X_minimum, 1);
122
123   for (i=0; i<n; i++) {
124     for (j=0; j<m; j++) {
125       if (!(adjmatrix[i] & one_adj_bit(j)))
126         continue;
127       /* x_total_i += x_minimum */
128       /* x_total_j += x_minimum */
129       matrix_entries[ ME_totals_i__minimum + i ] ++;
130       matrix_entries[ ME_totals_j__minimum + j ] ++;
131
132       /* x_morefrag_i_j >= 0 */
133       int X_morefrag_i_j = glp_add_cols(prob, 1);
134       glp_set_col_bnds(prob, X_morefrag_i_j, GLP_LO, 0, 0);
135
136       /* x_total_i += x_morefrag_i_j */
137       /* x_total_j += x_morefrag_i_j */
138       int ME_totals_i__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_i+i, X_morefrag_i_j);
139       int ME_totals_j__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_j+j, X_morefrag_i_j);
140       matrix_entries[ME_totals_i__mf_i_j] = 1;
141       matrix_entries[ME_totals_j__mf_i_j] = 1;
142     }
143   }
144
145   assert(next_matrix_entry == matrix_entries_size);
146
147   glp_load_matrix(prob, matrix_entries_size-1,
148                   matrix_entries_XY[1], matrix_entries_XY[0],
149                   matrix_entries);
150
151   int r = glp_simplex(prob, NULL);
152   if (doprint) printf(" simplex=%d", r);
153
154 #define OKERR(e) \
155   case e: if (doprint) printf(" " #e ); goto out;
156 #define BADERR(e) \
157   case e: if (doprint) printf(" " #e " CRASHING"); exit(-1);
158 #define DEFAULT \
159   default: if (doprint) printf(" ! CRASHING"); exit(-1);
160
161   switch (r) {
162   OKERR(GLP_ESING);
163   OKERR(GLP_ECOND);
164   OKERR(GLP_EBOUND);
165   OKERR(GLP_EFAIL);
166   OKERR(GLP_ENOPFS);
167   OKERR(GLP_ENODFS);
168   BADERR(GLP_EBADB);
169   BADERR(GLP_EOBJLL);
170   BADERR(GLP_EOBJUL);
171   BADERR(GLP_EITLIM);
172   BADERR(GLP_ETMLIM);
173   case 0: break;
174   DEFAULT;
175   }
176
177   r = glp_get_status(prob);
178   if (doprint) printf(" status=%d", r);
179
180   switch (r) {
181   OKERR(GLP_NOFEAS);
182   OKERR(GLP_UNDEF);
183   BADERR(GLP_FEAS);
184   BADERR(GLP_INFEAS);
185   BADERR(GLP_UNBND);
186   case GLP_OPT: break;
187   DEFAULT;
188   }
189
190   double got = glp_get_obj_val(prob);
191   if (doprint) printf("  %g", got);
192   if (got <= best)
193     goto out;
194
195   if (!doprint) {
196     optimise(1);
197     goto out;
198   }
199
200   best = got;
201
202   if (best_prob) glp_delete_prob(best_prob);
203   best_prob = prob;
204
205   free(best_adjmatrix);
206   best_adjmatrix = xalloc_adjmatrix();
207   memcpy(best_adjmatrix, adjmatrix, sizeof(*adjmatrix)*n);
208
209   printf(" BEST        \n");
210   return;
211
212   }
213  out:
214   if (prob)
215     glp_delete_prob(prob);
216   if (doprint) { printf("        \r"); fflush(stdout); }
217 }
218
219 static void iterate_recurse(int i, AdjWord min) {
220   if (i >= n) {
221     printcounter++;
222     optimise(!(printcounter & 0xfff));
223     return;
224   }
225   for (adjmatrix[i] = min;
226        ;
227        adjmatrix[i]++) {
228     iterate_recurse(i+1, adjmatrix[i]);
229     if (adjmatrix[i] == adjall)
230       return;
231   }
232 }
233
234 static void iterate(void) {
235   iterate_recurse(0, 1);
236 }
237
238 int main(int argc, char **argv) {
239   n = atoi(argv[1]);
240   m = atoi(argv[2]);
241   prep();
242   iterate();
243   printf("\n");
244   if (ferror(stdout) || fclose(stdout)) { perror("stdout"); exit(-1); }
245   return 0;
246 }