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