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.
38 #include <sys/types.h>
41 #include <sys/fcntl.h>
48 * Each input match contributes, or does not contribute, to each
49 * output match; we do not need to consider multiple fragments
50 * relating to the same input/output pair this gives an n*m adjacency
51 * matrix (bitmap). Given such an adjacency matrix, the problem of
52 * finding the best sizes for the fragments can be expressed as a
53 * linear programming problem.
55 * We search all possible adjacency matrices, and for each one we run
56 * GLPK's simplex solver. We represent the adjacency matrix as an
59 * However, there are a couple of wrinkles:
61 * To best represent the problem as a standard LP problem, we separate
62 * out the size of each fragment into a common minimum size variable,
63 * plus a fragment-specific extra size variable. This reduces the LP
64 * problem size at the cost of making the problem construction, and
65 * interpretation of the results, a bit fiddly.
67 * Many of the adjacency matrices are equivalent. In particular,
68 * permutations of the columns, or of the rows, do not change the
69 * meaning. It is only necessasry to consider any one permutation.
70 * We make use of this by considering only adjacency matrices whose
71 * bitmap array contains bitmap words whose numerical values are
72 * nondecreasing in array order.
74 * Once we have a solution, we also avoid considering any candidate
75 * which involves dividing one of the output sticks into so many
76 * fragment that the smallest fragment would necessarily be no bigger
77 * than our best solution. That is, we reject candidates where any of
78 * the hamming weights of the adjacency bitmap words are too large.
80 * And, we want to do the search in order of increasing maximum
81 * hamming weight. This is because in practice optimal solutions tend
82 * to have low hamming weight, and having found a reasonable solution
83 * early allows us to eliminate a lot of candidates without doing the
87 typedef uint32_t AdjWord;
88 #define PRADJ "08"PRIx32
90 static int n, m, maxhamweight;
91 static AdjWord *adjmatrix;
92 static AdjWord adjall;
95 static glp_prob *best_prob;
96 static AdjWord *best_adjmatrix;
98 static int n_over_best;
101 static unsigned printcounter;
103 static void iterate(void);
104 static void iterate_recurse(int i, AdjWord min);
105 static bool preconsider_ok(int nwords, bool doprint);
106 static bool maxhamweight_ok(void);
107 static void optimise(bool doprint);
109 static void progress_eol(void) {
110 fprintf(stderr," \r");
114 static void set_best(double new_best) {
116 n_over_best = floor(n / best);
119 /*----- multicore support -----*/
130 * - one pipe ("work") from generator to workers
131 * - ever-extending file ("bus") containing new "best" values
132 * - one file for each worker giving maxhamweight and adjmatrix for best
134 * generator runs iterate_recurse to a certain depth and writes the
135 * candidates to a pipe
137 * workers read candidates from the pipe and resume iterate_recurse
138 * halfway through the recursion
140 * whenever a worker does a doprint, it checks the bus for new best
141 * value; actual best values are appended
143 * master waits for generator and all workers to finish and then
144 * runs optimise() for each worker's best, then prints
147 static int ncpus = 0, multicore_iteration_boundary = INT_MAX;
149 static int mc_bus, mc_work[2];
150 static off_t mc_bus_read;
157 static Worker *mc_us;
159 static void multicore_check_for_new_best(void);
162 static AdjWord mc_iter_min;
164 static size_t mc_iovlen;
165 static struct iovec mc_iov[MAX_NIOVS];
167 #define IOV0 (mc_niovs = mc_iovlen = 0)
169 #define IOV(obj, count) ({ \
170 assert(mc_niovs < MAX_NIOVS); \
171 mc_iov[mc_niovs].iov_base = &(obj); \
172 mc_iov[mc_niovs].iov_len = sizeof(obj) * (count); \
173 mc_iovlen += mc_iov[mc_niovs].iov_len; \
177 static void mc_rwvsetup_outer(void) {
179 IOV(maxhamweight, 1);
181 IOV(*adjmatrix, multicore_iteration_boundary);
185 static void mc_rwvsetup_full(void) {
190 static void vlprintf(const char *fmt, va_list al) {
191 vfprintf(stderr,fmt,al);
195 static void LPRINTF(const char *fmt, ...) {
202 static void mc_awaitpid(int wnum, pid_t pid) {
203 LPRINTF("master awaiting %2d [%ld]",wnum,(long)pid);
205 pid_t got = waitpid(pid, &status, 0);
208 fprintf(stderr,"\nFAILED SUBPROC %2d [%ld] %d\n",
209 wnum, (long)pid, status);
214 static void multicore_outer_iteration(int i, AdjWord min) {
215 static unsigned check_counter;
217 assert(i == multicore_iteration_boundary);
220 ssize_t r = writev(mc_work[1], mc_iov, mc_niovs);
221 assert(r == mc_iovlen);
222 /* effectively, this writev arranges to transfers control
223 * to some worker's instance of iterate_recurse via mc_iterate_worker */
225 if (!(check_counter++ & 0xff))
226 multicore_check_for_new_best();
229 static void mc_iterate_worker(void) {
232 ssize_t r = readv(mc_work[0], mc_iov, mc_niovs);
234 assert(r == mc_iovlen);
236 bool ok = maxhamweight_ok();
239 ok = preconsider_ok(multicore_iteration_boundary, 1);
243 /* stop iterate_recurse from trying to run multicore_outer_iteration */
244 int mc_org_it_bound = multicore_iteration_boundary;
245 multicore_iteration_boundary = INT_MAX;
246 iterate_recurse(mc_org_it_bound, mc_iter_min);
247 multicore_iteration_boundary = mc_org_it_bound;
249 LPRINTF("worker %2d reporting",mc_us->w);
250 if (best_adjmatrix) {
251 adjmatrix = best_adjmatrix;
253 ssize_t r = writev(fileno(mc_us->results), mc_iov, mc_niovs);
254 assert(r == mc_iovlen);
256 LPRINTF("worker %2d ending",mc_us->w);
260 static void multicore(void) {
265 multicore_iteration_boundary = n / 2;
267 FILE *busf = tmpfile(); assert(busf);
268 mc_bus = fileno(busf);
269 int r = fcntl(mc_bus, F_GETFL); assert(r >= 0);
271 r = fcntl(mc_bus, F_SETFL, r); assert(r >= 0);
273 r = pipe(mc_work); assert(!r);
275 mc_workers = xmalloc(sizeof(*mc_workers) * ncpus);
276 for (w=0; w<ncpus; w++) {
278 mc_workers[w].results = tmpfile(); assert(mc_workers[w].results);
279 mc_workers[w].pid = fork(); assert(mc_workers[w].pid >= 0);
280 if (!mc_workers[w].pid) {
281 mc_us = &mc_workers[w];
283 LPRINTF("worker %2d running", w);
291 genpid = fork(); assert(genpid >= 0);
293 LPRINTF("generator running");
299 mc_awaitpid(-1, genpid);
300 for (w=0; w<ncpus; w++)
301 mc_awaitpid(w, mc_workers[w].pid);
303 for (w=0; w<ncpus; w++) {
305 LPRINTF("reading report from %2d",w);
306 ssize_t sr = preadv(fileno(mc_workers[w].results), mc_iov, mc_niovs, 0);
313 static void multicore_check_for_new_best(void) {
318 ssize_t got = pread(mc_bus, &msg, sizeof(msg), mc_bus_read);
320 assert(got == sizeof(msg));
323 mc_bus_read += sizeof(msg);
327 static void multicore_found_new_best(void) {
330 if (mc_us /* might be master */) fprintf(stderr," w%-2d ",mc_us->w);
331 ssize_t wrote = write(mc_bus, &best, sizeof(best));
332 assert(wrote == sizeof(best));
335 /*----- end of multicore support -----*/
337 static AdjWord *xalloc_adjmatrix(void) {
338 return xmalloc(sizeof(*adjmatrix)*n);
341 static void prep(void) {
342 adjall = ~((~(AdjWord)0) << m);
343 adjmatrix = xalloc_adjmatrix();
344 glp_term_out(GLP_OFF);
346 weight = calloc(sizeof(*weight), m); assert(weight);
347 n_over_best = INT_MAX;
350 static AdjWord one_adj_bit(int bitnum) {
351 return (AdjWord)1 << bitnum;
354 static int count_set_adj_bits(AdjWord w) {
356 for (j=0, total=0; j<m; j++)
357 total += !!(w & one_adj_bit(j));
361 #define PRINTF(...) if (!doprint) ; else fprintf(stderr, __VA_ARGS__)
363 static int totalfrags;
365 static bool maxhamweight_ok(void) {
366 double maxminsize = (double)m / maxhamweight;
367 return maxminsize > best;
370 static bool preconsider_ok(int nwords, bool doprint) {
373 PRINTF("%2d ", maxhamweight);
376 for (i=0, totalfrags=0; i<nwords; i++) {
377 int frags = count_set_adj_bits(adjmatrix[i]);
378 had_max += (frags >= maxhamweight);
380 PRINTF("%"PRADJ" ", adjmatrix[i]);
381 double maxminsize = (double)m / frags;
382 if (maxminsize <= best) {
388 /* Skip this candidate as its max hamming weight is lower than
389 * we're currently looking for (which means we must have done it
390 * already). (The recursive iteration ensures that none of the
391 * words have more than the max hamming weight.) */
401 static void optimise(bool doprint) {
402 /* Consider the best answer (if any) for a given adjacency matrix */
407 * Up to a certain point, optimise() can be restarted. We use this
408 * to go back and print the debugging output if it turns out that we
409 * have an interesting case. The HAVE_PRINTED macro does this: its
410 * semantics are to go back in time and make sure that we have
411 * printed the description of the search case.
413 #define HAVE_PRINTED ({ \
414 if (!doprint) { doprint = 1; goto retry_with_print; } \
418 glp_delete_prob(prob);
422 bool ok = preconsider_ok(n, doprint);
427 * We formulate our problem as an LP problem as follows.
428 * In this file "n" and "m" are the matchstick numbers.
430 * Each set bit in the adjacency matrix corresponds to taking a
431 * fragment from old match i and making it part of new match j.
433 * The structural variables (columns) are:
434 * x_minimum minimum size of any fragment (bounded below by 0)
435 * x_morefrag_i_j the amount by which the size of the fragment
436 * i,j exceeds the minimum size (bounded below by 0)
438 * The auxiliary variables (rows) are:
439 * x_total_i total length for each input match (fixed variable)
440 * x_total_j total length for each output match (fixed variable)
442 * The objective function is simply
445 * We use X_ and Y_ to refer to GLPK's (1-based) column and row indices.
446 * ME_ refers to entries in the list of constraint matrix elements
447 * which we build up as we go.
450 prob = glp_create_prob();
452 int Y_totals_i = glp_add_rows(prob, n);
453 int Y_totals_j = glp_add_rows(prob, m);
454 int X_minimum = glp_add_cols(prob, 1);
457 int next_matrix_entry = 1; /* wtf GLPK! */
458 int matrix_entries_size = next_matrix_entry + n + m + totalfrags*2;
459 double matrix_entries[matrix_entries_size];
460 int matrix_entries_XY[2][matrix_entries_size];
462 #define ADD_MATRIX_ENTRY(Y,X) ({ \
463 assert(next_matrix_entry < matrix_entries_size); \
464 matrix_entries_XY[0][next_matrix_entry] = (X); \
465 matrix_entries_XY[1][next_matrix_entry] = (Y); \
466 matrix_entries[next_matrix_entry] = 0; \
467 next_matrix_entry++; \
470 int ME_totals_i__minimum = next_matrix_entry;
471 for (i=0; i<n; i++) ADD_MATRIX_ENTRY(Y_totals_i+i, X_minimum);
473 int ME_totals_j__minimum = next_matrix_entry;
474 for (j=0; j<m; j++) ADD_MATRIX_ENTRY(Y_totals_j+j, X_minimum);
476 /* \forall_i x_total_i = m */
477 /* \forall_i x_total_j = n */
478 for (i=0; i<n; i++) glp_set_row_bnds(prob, Y_totals_i+i, GLP_FX, m,m);
479 for (j=0; j<m; j++) glp_set_row_bnds(prob, Y_totals_j+j, GLP_FX, n,n);
482 glp_set_col_bnds(prob, X_minimum, GLP_LO, 0, 0);
483 glp_set_col_name(prob, X_minimum, "minimum");
485 /* objective is maximising x_minimum */
486 glp_set_obj_dir(prob, GLP_MAX);
487 glp_set_obj_coef(prob, X_minimum, 1);
489 for (i=0; i<n; i++) {
490 for (j=0; j<m; j++) {
491 if (!(adjmatrix[i] & one_adj_bit(j)))
493 /* x_total_i += x_minimum */
494 /* x_total_j += x_minimum */
495 matrix_entries[ ME_totals_i__minimum + i ] ++;
496 matrix_entries[ ME_totals_j__minimum + j ] ++;
498 /* x_morefrag_i_j >= 0 */
499 int X_morefrag_i_j = glp_add_cols(prob, 1);
500 glp_set_col_bnds(prob, X_morefrag_i_j, GLP_LO, 0, 0);
503 snprintf(buf,sizeof(buf),"mf %d,%d",i,j);
504 glp_set_col_name(prob, X_morefrag_i_j, buf);
507 /* x_total_i += x_morefrag_i_j */
508 /* x_total_j += x_morefrag_i_j */
509 int ME_totals_i__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_i+i, X_morefrag_i_j);
510 int ME_totals_j__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_j+j, X_morefrag_i_j);
511 matrix_entries[ME_totals_i__mf_i_j] = 1;
512 matrix_entries[ME_totals_j__mf_i_j] = 1;
516 assert(next_matrix_entry == matrix_entries_size);
518 glp_load_matrix(prob, matrix_entries_size-1,
519 matrix_entries_XY[1], matrix_entries_XY[0],
522 int r = glp_simplex(prob, NULL);
523 PRINTF(" glp=%d", r);
526 case e: PRINTF(" " #e ); goto out;
528 case e: HAVE_PRINTED; printf(" " #e " CRASHING\n"); exit(-1);
530 default: HAVE_PRINTED; printf(" ! CRASHING\n"); exit(-1);
550 r = glp_get_status(prob);
551 PRINTF(" status=%d", r);
563 double got = glp_get_obj_val(prob);
571 multicore_found_new_best();
573 if (best_prob) glp_delete_prob(best_prob);
576 free(best_adjmatrix);
577 best_adjmatrix = xalloc_adjmatrix();
578 memcpy(best_adjmatrix, adjmatrix, sizeof(*adjmatrix)*n);
586 glp_delete_prob(prob);
587 if (doprint) progress_eol();
588 if (doprint) multicore_check_for_new_best();
591 static void iterate_recurse(int i, AdjWord min) {
594 optimise(!(printcounter & 0xfff));
597 if (i >= multicore_iteration_boundary) {
598 multicore_outer_iteration(i, min);
601 for (adjmatrix[i] = min;
604 if (count_set_adj_bits(adjmatrix[i]) > maxhamweight)
606 if (i == 0 && (adjmatrix[i] & (1+adjmatrix[i])))
609 for (int j = 0; j < m; j++)
610 if (adjmatrix[i] & one_adj_bit(j))
612 for (int j = 0; j < m; j++)
613 if (weight[j] >= n_over_best)
616 iterate_recurse(i+1, adjmatrix[i]);
619 for (int j = 0; j < m; j++)
620 if (adjmatrix[i] & one_adj_bit(j))
624 if (adjmatrix[i] == adjall)
629 static void iterate(void) {
630 for (maxhamweight=1; maxhamweight<=m; maxhamweight++) {
631 if (!maxhamweight_ok())
634 iterate_recurse(0, 1);
638 static void report(void) {
639 fprintf(stderr, "\n");
641 double min = glp_get_obj_val(best_prob);
644 for (i = 0; i < n; i++)
645 for (j = 0; j < m; j++)
647 cols = glp_get_num_cols(best_prob);
648 for (i = 1; i <= cols; i++) {
650 if (2 != sscanf(glp_get_col_name(best_prob, i), "mf %d,%d", &x, &y))
652 a[x][y] = min + glp_get_col_prim(best_prob, i);
654 printf("%d into %d: min fragment %g\n", n, m, min);
655 for (i = 0; i < n; i++) {
656 for (j = 0; j < m; j++) {
658 printf(" %9.3f", a[i][j]);
665 if (ferror(stdout) || fclose(stdout)) { perror("stdout"); exit(-1); }
668 int main(int argc, char **argv) {
670 while ((opt = getopt(argc,argv,"j:")) >= 0) {
672 case 'j': ncpus = atoi(optarg); break;
673 case '+': assert(!"bad option");
685 if (ncpus) multicore();