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