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