chiark / gitweb /
Prune by symmetry: constrain 1st adj row to all 1s at low end.
[matchsticks-search.git] / main.c
1 /*
2  * Searches for "good" ways to divide n matchsticks up and reassemble them
3  * into m matchsticks.  "Good" means the smallest fragment is as big
4  * as possible.
5  *
6  * Invoke as   ./main n m
7  *
8  * The algorithm is faster if the arguments are ordered so that n > m.
9  */
10
11 /*
12  * matchsticks/main.c  Copyright 2014 Ian Jackson
13  *
14  * This program is free software: you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation, either version 3 of the License, or
17  * (at your option) any later version.
18  *
19  * This program is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  */
24
25 #include <stdio.h>
26 #include <stdint.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <assert.h>
30 #include <stdbool.h>
31 #include <inttypes.h>
32
33 #include <publib.h>
34 #include <glpk.h>
35
36 /*
37  * Algorithm.
38  *
39  * Each input match contributes, or does not contribute, to each
40  * output match; we do not need to consider multiple fragments
41  * relating to the same input/output pair this gives an n*m adjacency
42  * matrix (bitmap).  Given such an adjacency matrix, the problem of
43  * finding the best sizes for the fragments can be expressed as a
44  * linear programming problem.
45  *
46  * We search all possible adjacency matrices, and for each one we run
47  * GLPK's simplex solver.  We represent the adjacency matrix as an
48  * array of bitmaps.
49  *
50  * However, there are a couple of wrinkles:
51  *
52  * To best represent the problem as a standard LP problem, we separate
53  * out the size of each fragment into a common minimum size variable,
54  * plus a fragment-specific extra size variable.  This reduces the LP
55  * problem size at the cost of making the problem construction, and
56  * interpretation of the results, a bit fiddly.
57  *
58  * Many of the adjacency matrices are equivalent.  In particular,
59  * permutations of the columns, or of the rows, do not change the
60  * meaning.  It is only necessasry to consider any one permutation.
61  * We make use of this by considering only adjacency matrices whose
62  * bitmap array contains bitmap words whose numerical values are
63  * nondecreasing in array order.
64  *
65  * Once we have a solution, we also avoid considering any candidate
66  * which involves dividing one of the output sticks into so many
67  * fragment that the smallest fragment would necessarily be no bigger
68  * than our best solution.  That is, we reject candidates where any of
69  * the hamming weights of the adjacency bitmap words are too large.
70  *
71  * And, we want to do the search in order of increasing maximum
72  * hamming weight.  This is because in practice optimal solutions tend
73  * to have low hamming weight, and having found a reasonable solution
74  * early allows us to eliminate a lot of candidates without doing the
75  * full LP.
76  */
77
78 typedef uint32_t AdjWord;
79 #define PRADJ "08"PRIx32
80
81 static int n, m, maxhamweight;
82 static AdjWord *adjmatrix;
83 static AdjWord adjall;
84
85 static double best;
86 static glp_prob *best_prob;
87 static AdjWord *best_adjmatrix;
88
89 static unsigned printcounter;
90
91 static AdjWord *xalloc_adjmatrix(void) {
92   return xmalloc(sizeof(*adjmatrix)*n);
93 }
94
95 static void prep(void) {
96   adjall = ~((~(AdjWord)0) << m);
97   adjmatrix = xalloc_adjmatrix();
98   glp_term_out(GLP_OFF);
99 }
100
101 static AdjWord one_adj_bit(int bitnum) {
102   return (AdjWord)1 << bitnum;
103 }
104
105 static int count_set_adj_bits(AdjWord w) {
106   int j, total;
107   for (j=0, total=0; j<m; j++)
108     total += !!(w & one_adj_bit(j));
109   return total;
110 }
111
112 static void optimise(int doprint) {
113   /* Consider the best answer (if any) for a given adjacency matrix */
114   glp_prob *prob = 0;
115   int i, j, totalfrags;
116
117   /*
118    * Up to a certain point, optimise() can be restarted.  We use this
119    * to go back and print the debugging output if it turns out that we
120    * have an interesting case.  The HAVE_PRINTED macro does this: its
121    * semantics are to go back in time and make sure that we have
122    * printed the description of the search case.
123    */
124 #define HAVE_PRINTED ({                                         \
125       if (!doprint) { doprint = 1; goto retry_with_print; }     \
126     })
127  retry_with_print:
128   if (prob) {
129     glp_delete_prob(prob);
130     prob = 0;
131   }
132
133 #define PRINTF(...) if (!doprint) ; else fprintf(stderr, __VA_ARGS__) /* bodgy */
134
135   PRINTF("%2d ", maxhamweight);
136
137   bool had_max = 0;
138   for (i=0, totalfrags=0; i<n; i++) {
139     int frags = count_set_adj_bits(adjmatrix[i]);
140     had_max += (frags == maxhamweight);
141     totalfrags += frags;
142     PRINTF("%"PRADJ" ", adjmatrix[i]);
143     double maxminsize = (double)m / frags;
144     if (maxminsize <= best) {
145       PRINTF(" too fine");
146       goto out;
147     }
148   }
149   if (!had_max) {
150     /* Skip this candidate as its max hamming weight is lower than
151      * we're currently looking for (which means we must have done it
152      * already).  (The recursive iteration ensures that none of the
153      * words have more than the max hamming weight.) */
154     PRINTF(" nomaxham");
155     goto out;
156   }
157
158   /*
159    * We formulate our problem as an LP problem as follows.
160    * In this file "n" and "m" are the matchstick numbers.
161    *
162    * Each set bit in the adjacency matrix corresponds to taking a
163    * fragment from old match i and making it part of new match j.
164    *
165    * The structural variables (columns) are:
166    *   x_minimum        minimum size of any fragment (bounded below by 0)
167    *   x_morefrag_i_j   the amount by which the size of the fragment
168    *                     i,j exceeds the minimum size (bounded below by 0)
169    *
170    * The auxiliary variables (rows) are:
171    *   x_total_i       total length for each input match (fixed variable)
172    *   x_total_j       total length for each output match (fixed variable)
173    *
174    * The objective function is simply
175    *   maximise x_minimum
176    *
177    * We use X_ and Y_ to refer to GLPK's (1-based) column and row indices.
178    * ME_ refers to entries in the list of constraint matrix elements
179    * which we build up as we go.
180    */
181
182   prob = glp_create_prob();
183
184   int Y_totals_i = glp_add_rows(prob, n);
185   int Y_totals_j = glp_add_rows(prob, m);
186   int X_minimum = glp_add_cols(prob, 1);
187
188   {
189   int next_matrix_entry = 1; /* wtf GLPK! */
190   int matrix_entries_size = next_matrix_entry + n + m + totalfrags*2;
191   double matrix_entries[matrix_entries_size];
192   int matrix_entries_XY[2][matrix_entries_size];
193
194 #define ADD_MATRIX_ENTRY(Y,X) ({                        \
195       assert(next_matrix_entry < matrix_entries_size);  \
196       matrix_entries_XY[0][next_matrix_entry] = (X);    \
197       matrix_entries_XY[1][next_matrix_entry] = (Y);    \
198       matrix_entries[next_matrix_entry] = 0;            \
199       next_matrix_entry++;                              \
200     })
201
202   int ME_totals_i__minimum = next_matrix_entry;
203   for (i=0; i<n; i++) ADD_MATRIX_ENTRY(Y_totals_i+i, X_minimum);
204
205   int ME_totals_j__minimum = next_matrix_entry;
206   for (j=0; j<m; j++) ADD_MATRIX_ENTRY(Y_totals_j+j, X_minimum);
207
208   /* \forall_i x_total_i = m */
209   /* \forall_i x_total_j = n */
210   for (i=0; i<n; i++) glp_set_row_bnds(prob, Y_totals_i+i, GLP_FX, m,m);
211   for (j=0; j<m; j++) glp_set_row_bnds(prob, Y_totals_j+j, GLP_FX, n,n);
212
213   /* x_minimum >= 0 */
214   glp_set_col_bnds(prob, X_minimum, GLP_LO, 0, 0);
215   glp_set_col_name(prob, X_minimum, "minimum");
216
217   /* objective is maximising x_minimum */
218   glp_set_obj_dir(prob, GLP_MAX);
219   glp_set_obj_coef(prob, X_minimum, 1);
220
221   for (i=0; i<n; i++) {
222     for (j=0; j<m; j++) {
223       if (!(adjmatrix[i] & one_adj_bit(j)))
224         continue;
225       /* x_total_i += x_minimum */
226       /* x_total_j += x_minimum */
227       matrix_entries[ ME_totals_i__minimum + i ] ++;
228       matrix_entries[ ME_totals_j__minimum + j ] ++;
229
230       /* x_morefrag_i_j >= 0 */
231       int X_morefrag_i_j = glp_add_cols(prob, 1);
232       glp_set_col_bnds(prob, X_morefrag_i_j, GLP_LO, 0, 0);
233       if (doprint) {
234         char buf[255];
235         snprintf(buf,sizeof(buf),"mf %d,%d",i,j);
236         glp_set_col_name(prob, X_morefrag_i_j, buf);
237       }
238
239       /* x_total_i += x_morefrag_i_j */
240       /* x_total_j += x_morefrag_i_j */
241       int ME_totals_i__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_i+i, X_morefrag_i_j);
242       int ME_totals_j__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_j+j, X_morefrag_i_j);
243       matrix_entries[ME_totals_i__mf_i_j] = 1;
244       matrix_entries[ME_totals_j__mf_i_j] = 1;
245     }
246   }
247
248   assert(next_matrix_entry == matrix_entries_size);
249
250   glp_load_matrix(prob, matrix_entries_size-1,
251                   matrix_entries_XY[1], matrix_entries_XY[0],
252                   matrix_entries);
253
254   int r = glp_simplex(prob, NULL);
255   PRINTF(" glp=%d", r);
256
257 #define OKERR(e) \
258   case e: PRINTF(" " #e ); goto out;
259 #define BADERR(e) \
260   case e: HAVE_PRINTED; printf(" " #e " CRASHING\n"); exit(-1);
261 #define DEFAULT \
262   default: HAVE_PRINTED; printf(" ! CRASHING\n"); exit(-1);
263
264   switch (r) {
265   OKERR(GLP_ESING);
266   OKERR(GLP_ECOND);
267   OKERR(GLP_EBOUND);
268   OKERR(GLP_EFAIL);
269   OKERR(GLP_ENOPFS);
270   OKERR(GLP_ENODFS);
271   BADERR(GLP_EBADB);
272   BADERR(GLP_EOBJLL);
273   BADERR(GLP_EOBJUL);
274   BADERR(GLP_EITLIM);
275   BADERR(GLP_ETMLIM);
276   BADERR(GLP_EINSTAB);
277   BADERR(GLP_ENOCVG);
278   case 0: break;
279   DEFAULT;
280   }
281
282   r = glp_get_status(prob);
283   PRINTF(" status=%d", r);
284
285   switch (r) {
286   OKERR(GLP_NOFEAS);
287   OKERR(GLP_UNDEF);
288   BADERR(GLP_FEAS);
289   BADERR(GLP_INFEAS);
290   BADERR(GLP_UNBND);
291   case GLP_OPT: break;
292   DEFAULT;
293   }
294
295   double got = glp_get_obj_val(prob);
296   PRINTF("  %g", got);
297   if (got <= best)
298     goto out;
299
300   HAVE_PRINTED;
301
302   best = got;
303
304   if (best_prob) glp_delete_prob(best_prob);
305   best_prob = prob;
306
307   free(best_adjmatrix);
308   best_adjmatrix = xalloc_adjmatrix();
309   memcpy(best_adjmatrix, adjmatrix, sizeof(*adjmatrix)*n);
310
311   PRINTF(" BEST        \n");
312   return;
313
314   }
315  out:
316   if (prob)
317     glp_delete_prob(prob);
318   if (doprint) { PRINTF("        \r"); fflush(stdout); }
319 }
320
321 static void iterate_recurse(int i, AdjWord min) {
322   if (i >= n) {
323     printcounter++;
324     optimise(!(printcounter & 0xfff));
325     return;
326   }
327   for (adjmatrix[i] = min;
328        ;
329        adjmatrix[i]++) {
330     if (count_set_adj_bits(adjmatrix[i]) > maxhamweight)
331       goto again;
332     if (i == 0 && (adjmatrix[i] & (1+adjmatrix[i])))
333       goto again;
334
335     iterate_recurse(i+1, adjmatrix[i]);
336
337   again:
338     if (adjmatrix[i] == adjall)
339       return;
340   }
341 }
342
343 static void iterate(void) {
344   for (maxhamweight=1; maxhamweight<=m; maxhamweight++) {
345     double maxminsize = (double)m / maxhamweight;
346     if (maxminsize <= best)
347       continue;
348
349     iterate_recurse(0, 1);
350   }
351 }
352
353 int main(int argc, char **argv) {
354   assert(argc==3);
355   n = atoi(argv[1]);
356   m = atoi(argv[2]);
357   prep();
358   iterate();
359   fprintf(stderr, "\n");
360   if (best_prob) {
361     double min = glp_get_obj_val(best_prob);
362     double a[n][m];
363     int i, j, cols;
364     for (i = 0; i < n; i++)
365       for (j = 0; j < m; j++)
366         a[i][j] = 0;
367     cols = glp_get_num_cols(best_prob);
368     for (i = 1; i <= cols; i++) {
369       int x, y;
370       if (2 != sscanf(glp_get_col_name(best_prob, i), "mf %d,%d", &x, &y))
371         continue;
372       a[x][y] = min + glp_get_col_prim(best_prob, i);
373     }
374     printf("%d into %d: min fragment %g\n", n, m, min);
375     for (i = 0; i < n; i++) {
376       for (j = 0; j < m; j++) {
377         if (a[i][j])
378           printf(" %9.3f", a[i][j]);
379         else
380           printf("          ");
381       }
382       printf("\n");
383     }
384   }
385   if (ferror(stdout) || fclose(stdout)) { perror("stdout"); exit(-1); }
386   return 0;
387 }