2 * Searches for "good" ways to divide n matchsticks up and reassemble them
3 * into m matchsticks. "Good" means the smallest fragment is as big
8 * The algorithm is faster if the arguments are ordered so that n > m.
12 * matchsticks/main.c Copyright 2014 Ian Jackson
14 * This program is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation, either version 3 of the License, or
17 * (at your option) any later version.
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
40 * Each input match contributes, or does not contribute, to each
41 * output match; we do not need to consider multiple fragments
42 * relating to the same input/output pair this gives an n*m adjacency
43 * matrix (bitmap). Given such an adjacency matrix, the problem of
44 * finding the best sizes for the fragments can be expressed as a
45 * linear programming problem.
47 * We search all possible adjacency matrices, and for each one we run
48 * GLPK's simplex solver. We represent the adjacency matrix as an
51 * However, there are a couple of wrinkles:
53 * To best represent the problem as a standard LP problem, we separate
54 * out the size of each fragment into a common minimum size variable,
55 * plus a fragment-specific extra size variable. This reduces the LP
56 * problem size at the cost of making the problem construction, and
57 * interpretation of the results, a bit fiddly.
59 * Many of the adjacency matrices are equivalent. In particular,
60 * permutations of the columns, or of the rows, do not change the
61 * meaning. It is only necessasry to consider any one permutation.
62 * We make use of this by considering only adjacency matrices whose
63 * bitmap array contains bitmap words whose numerical values are
64 * nondecreasing in array order.
66 * Once we have a solution, we also avoid considering any candidate
67 * which involves dividing one of the output sticks into so many
68 * fragment that the smallest fragment would necessarily be no bigger
69 * than our best solution. That is, we reject candidates where any of
70 * the hamming weights of the adjacency bitmap words are too large.
72 * And, we want to do the search in order of increasing maximum
73 * hamming weight. This is because in practice optimal solutions tend
74 * to have low hamming weight, and having found a reasonable solution
75 * early allows us to eliminate a lot of candidates without doing the
79 typedef uint32_t AdjWord;
80 #define PRADJ "08"PRIx32
82 static int n, m, maxhamweight;
83 static AdjWord *adjmatrix;
84 static AdjWord adjall;
87 static glp_prob *best_prob;
88 static AdjWord *best_adjmatrix;
90 static unsigned printcounter;
94 static void progress_eol(void) {
95 fprintf(stderr," \r");
99 static AdjWord *xalloc_adjmatrix(void) {
100 return xmalloc(sizeof(*adjmatrix)*n);
103 static void prep(void) {
104 adjall = ~((~(AdjWord)0) << m);
105 adjmatrix = xalloc_adjmatrix();
106 glp_term_out(GLP_OFF);
110 static AdjWord one_adj_bit(int bitnum) {
111 return (AdjWord)1 << bitnum;
114 static int count_set_adj_bits(AdjWord w) {
116 for (j=0, total=0; j<m; j++)
117 total += !!(w & one_adj_bit(j));
121 #define PRINTF(...) if (!doprint) ; else fprintf(stderr, __VA_ARGS__)
123 static int totalfrags;
125 static bool preconsider_ok(int nwords, bool doprint) {
128 PRINTF("%2d ", maxhamweight);
131 for (i=0, totalfrags=0; i<nwords; i++) {
132 int frags = count_set_adj_bits(adjmatrix[i]);
133 had_max += (frags >= maxhamweight);
135 PRINTF("%"PRADJ" ", adjmatrix[i]);
136 double maxminsize = (double)m / frags;
137 if (maxminsize <= best) {
143 /* Skip this candidate as its max hamming weight is lower than
144 * we're currently looking for (which means we must have done it
145 * already). (The recursive iteration ensures that none of the
146 * words have more than the max hamming weight.) */
156 static void optimise(bool doprint) {
157 /* Consider the best answer (if any) for a given adjacency matrix */
162 * Up to a certain point, optimise() can be restarted. We use this
163 * to go back and print the debugging output if it turns out that we
164 * have an interesting case. The HAVE_PRINTED macro does this: its
165 * semantics are to go back in time and make sure that we have
166 * printed the description of the search case.
168 #define HAVE_PRINTED ({ \
169 if (!doprint) { doprint = 1; goto retry_with_print; } \
173 glp_delete_prob(prob);
177 bool ok = preconsider_ok(n, doprint);
182 * We formulate our problem as an LP problem as follows.
183 * In this file "n" and "m" are the matchstick numbers.
185 * Each set bit in the adjacency matrix corresponds to taking a
186 * fragment from old match i and making it part of new match j.
188 * The structural variables (columns) are:
189 * x_minimum minimum size of any fragment (bounded below by 0)
190 * x_morefrag_i_j the amount by which the size of the fragment
191 * i,j exceeds the minimum size (bounded below by 0)
193 * The auxiliary variables (rows) are:
194 * x_total_i total length for each input match (fixed variable)
195 * x_total_j total length for each output match (fixed variable)
197 * The objective function is simply
200 * We use X_ and Y_ to refer to GLPK's (1-based) column and row indices.
201 * ME_ refers to entries in the list of constraint matrix elements
202 * which we build up as we go.
205 prob = glp_create_prob();
207 int Y_totals_i = glp_add_rows(prob, n);
208 int Y_totals_j = glp_add_rows(prob, m);
209 int X_minimum = glp_add_cols(prob, 1);
212 int next_matrix_entry = 1; /* wtf GLPK! */
213 int matrix_entries_size = next_matrix_entry + n + m + totalfrags*2;
214 double matrix_entries[matrix_entries_size];
215 int matrix_entries_XY[2][matrix_entries_size];
217 #define ADD_MATRIX_ENTRY(Y,X) ({ \
218 assert(next_matrix_entry < matrix_entries_size); \
219 matrix_entries_XY[0][next_matrix_entry] = (X); \
220 matrix_entries_XY[1][next_matrix_entry] = (Y); \
221 matrix_entries[next_matrix_entry] = 0; \
222 next_matrix_entry++; \
225 int ME_totals_i__minimum = next_matrix_entry;
226 for (i=0; i<n; i++) ADD_MATRIX_ENTRY(Y_totals_i+i, X_minimum);
228 int ME_totals_j__minimum = next_matrix_entry;
229 for (j=0; j<m; j++) ADD_MATRIX_ENTRY(Y_totals_j+j, X_minimum);
231 /* \forall_i x_total_i = m */
232 /* \forall_i x_total_j = n */
233 for (i=0; i<n; i++) glp_set_row_bnds(prob, Y_totals_i+i, GLP_FX, m,m);
234 for (j=0; j<m; j++) glp_set_row_bnds(prob, Y_totals_j+j, GLP_FX, n,n);
237 glp_set_col_bnds(prob, X_minimum, GLP_LO, 0, 0);
238 glp_set_col_name(prob, X_minimum, "minimum");
240 /* objective is maximising x_minimum */
241 glp_set_obj_dir(prob, GLP_MAX);
242 glp_set_obj_coef(prob, X_minimum, 1);
244 for (i=0; i<n; i++) {
245 for (j=0; j<m; j++) {
246 if (!(adjmatrix[i] & one_adj_bit(j)))
248 /* x_total_i += x_minimum */
249 /* x_total_j += x_minimum */
250 matrix_entries[ ME_totals_i__minimum + i ] ++;
251 matrix_entries[ ME_totals_j__minimum + j ] ++;
253 /* x_morefrag_i_j >= 0 */
254 int X_morefrag_i_j = glp_add_cols(prob, 1);
255 glp_set_col_bnds(prob, X_morefrag_i_j, GLP_LO, 0, 0);
258 snprintf(buf,sizeof(buf),"mf %d,%d",i,j);
259 glp_set_col_name(prob, X_morefrag_i_j, buf);
262 /* x_total_i += x_morefrag_i_j */
263 /* x_total_j += x_morefrag_i_j */
264 int ME_totals_i__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_i+i, X_morefrag_i_j);
265 int ME_totals_j__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_j+j, X_morefrag_i_j);
266 matrix_entries[ME_totals_i__mf_i_j] = 1;
267 matrix_entries[ME_totals_j__mf_i_j] = 1;
271 assert(next_matrix_entry == matrix_entries_size);
273 glp_load_matrix(prob, matrix_entries_size-1,
274 matrix_entries_XY[1], matrix_entries_XY[0],
277 int r = glp_simplex(prob, NULL);
278 PRINTF(" glp=%d", r);
281 case e: PRINTF(" " #e ); goto out;
283 case e: HAVE_PRINTED; printf(" " #e " CRASHING\n"); exit(-1);
285 default: HAVE_PRINTED; printf(" ! CRASHING\n"); exit(-1);
305 r = glp_get_status(prob);
306 PRINTF(" status=%d", r);
318 double got = glp_get_obj_val(prob);
327 if (best_prob) glp_delete_prob(best_prob);
330 free(best_adjmatrix);
331 best_adjmatrix = xalloc_adjmatrix();
332 memcpy(best_adjmatrix, adjmatrix, sizeof(*adjmatrix)*n);
340 glp_delete_prob(prob);
341 if (doprint) progress_eol();
344 static void iterate_recurse(int i, AdjWord min) {
347 optimise(!(printcounter & 0xfff));
350 for (adjmatrix[i] = min;
353 if (count_set_adj_bits(adjmatrix[i]) > maxhamweight)
355 if (i == 0 && (adjmatrix[i] & (1+adjmatrix[i])))
358 iterate_recurse(i+1, adjmatrix[i]);
361 if (adjmatrix[i] == adjall)
366 static void iterate(void) {
367 for (maxhamweight=1; maxhamweight<=m; maxhamweight++) {
368 double maxminsize = (double)m / maxhamweight;
369 if (maxminsize <= best)
372 iterate_recurse(0, 1);
376 static void report(void) {
377 fprintf(stderr, "\n");
379 double min = glp_get_obj_val(best_prob);
382 for (i = 0; i < n; i++)
383 for (j = 0; j < m; j++)
385 cols = glp_get_num_cols(best_prob);
386 for (i = 1; i <= cols; i++) {
388 if (2 != sscanf(glp_get_col_name(best_prob, i), "mf %d,%d", &x, &y))
390 a[x][y] = min + glp_get_col_prim(best_prob, i);
392 printf("%d into %d: min fragment %g\n", n, m, min);
393 for (i = 0; i < n; i++) {
394 for (j = 0; j < m; j++) {
396 printf(" %9.3f", a[i][j]);
403 if (ferror(stdout) || fclose(stdout)) { perror("stdout"); exit(-1); }
406 int main(int argc, char **argv) {
408 while ((opt = getopt(argc,argv,"j:")) >= 0) {
410 case 'j': ncpus = atoi(optarg); break;
411 case '+': assert(!"bad option");