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