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