chiark / gitweb /
error fixes; tried interior but doesn't work (EINSTAB) and docs say cannot cope with...
[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   glp_set_col_name(prob, X_minimum, "minimum");
125
126   /* objective is maximising x_minimum */
127   glp_set_obj_dir(prob, GLP_MAX);
128   glp_set_obj_coef(prob, X_minimum, 1);
129
130   for (i=0; i<n; i++) {
131     for (j=0; j<m; j++) {
132       if (!(adjmatrix[i] & one_adj_bit(j)))
133         continue;
134       /* x_total_i += x_minimum */
135       /* x_total_j += x_minimum */
136       matrix_entries[ ME_totals_i__minimum + i ] ++;
137       matrix_entries[ ME_totals_j__minimum + j ] ++;
138
139       /* x_morefrag_i_j >= 0 */
140       int X_morefrag_i_j = glp_add_cols(prob, 1);
141       glp_set_col_bnds(prob, X_morefrag_i_j, GLP_LO, 0, 0);
142       if (doprint) {
143         char buf[255];
144         snprintf(buf,sizeof(buf),"mf %d,%d",i,j);
145         glp_set_col_name(prob, X_morefrag_i_j, buf);
146       }
147
148       /* x_total_i += x_morefrag_i_j */
149       /* x_total_j += x_morefrag_i_j */
150       int ME_totals_i__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_i+i, X_morefrag_i_j);
151       int ME_totals_j__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_j+j, X_morefrag_i_j);
152       matrix_entries[ME_totals_i__mf_i_j] = 1;
153       matrix_entries[ME_totals_j__mf_i_j] = 1;
154     }
155   }
156
157   assert(next_matrix_entry == matrix_entries_size);
158
159   glp_load_matrix(prob, matrix_entries_size-1,
160                   matrix_entries_XY[1], matrix_entries_XY[0],
161                   matrix_entries);
162
163   int r = glp_simplex(prob, NULL);
164   PRINTF(" glp=%d", r);
165
166 #define OKERR(e) \
167   case e: PRINTF(" " #e ); goto out;
168 #define BADERR(e) \
169   case e: HAVE_PRINTED; printf(" " #e " CRASHING\n"); exit(-1);
170 #define DEFAULT \
171   default: HAVE_PRINTED; printf(" ! CRASHING\n"); exit(-1);
172
173   switch (r) {
174   OKERR(GLP_ESING);
175   OKERR(GLP_ECOND);
176   OKERR(GLP_EBOUND);
177   OKERR(GLP_EFAIL);
178   OKERR(GLP_ENOPFS);
179   OKERR(GLP_ENODFS);
180   BADERR(GLP_EBADB);
181   BADERR(GLP_EOBJLL);
182   BADERR(GLP_EOBJUL);
183   BADERR(GLP_EITLIM);
184   BADERR(GLP_ETMLIM);
185   BADERR(GLP_EINSTAB);
186   BADERR(GLP_ENOCVG);
187   case 0: break;
188   DEFAULT;
189   }
190
191   r = glp_get_status(prob);
192   PRINTF(" status=%d", r);
193
194   switch (r) {
195   OKERR(GLP_NOFEAS);
196   OKERR(GLP_UNDEF);
197   BADERR(GLP_FEAS);
198   BADERR(GLP_INFEAS);
199   BADERR(GLP_UNBND);
200   case GLP_OPT: break;
201   DEFAULT;
202   }
203
204   double got = glp_get_obj_val(prob);
205   PRINTF("  %g", got);
206   if (got <= best)
207     goto out;
208
209   HAVE_PRINTED;
210
211   best = got;
212
213   if (best_prob) glp_delete_prob(best_prob);
214   best_prob = prob;
215
216   free(best_adjmatrix);
217   best_adjmatrix = xalloc_adjmatrix();
218   memcpy(best_adjmatrix, adjmatrix, sizeof(*adjmatrix)*n);
219
220   printf(" BEST        \n");
221   return;
222
223   }
224  out:
225   if (prob)
226     glp_delete_prob(prob);
227   if (doprint) { printf("        \r"); fflush(stdout); }
228 }
229
230 static void iterate_recurse(int i, AdjWord min) {
231   if (i >= n) {
232     printcounter++;
233     optimise(!(printcounter & 0xfff));
234     return;
235   }
236   for (adjmatrix[i] = min;
237        ;
238        adjmatrix[i]++) {
239     iterate_recurse(i+1, adjmatrix[i]);
240     if (adjmatrix[i] == adjall)
241       return;
242   }
243 }
244
245 static void iterate(void) {
246   iterate_recurse(0, 1);
247 }
248
249 int main(int argc, char **argv) {
250   n = atoi(argv[1]);
251   m = atoi(argv[2]);
252   prep();
253   iterate();
254   printf("\n");
255   if (best_prob)
256     glp_print_sol(best_prob,"/dev/stdout");
257   if (ferror(stdout) || fclose(stdout)) { perror("stdout"); exit(-1); }
258   return 0;
259 }