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