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 arguments must be ordered so that n > m:
9 * n is the number of (more, shorter) input matches of length m
10 * m is the number of (fewer, longer) output matches of length n
13 * -j<jobs> run in parallel on <jobs> cores
17 * matchsticks/main.c Copyright 2014 Ian Jackson
19 * This program is free software: you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation, either version 3 of the License, or
22 * (at your option) any later version.
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
43 #include <sys/types.h>
46 #include <sys/fcntl.h>
51 #define VERSION "(unknown-version)"
57 * Each input match contributes, or does not contribute, to each
58 * output match; we do not need to consider multiple fragments
59 * relating to the same input/output pair this gives an n*m adjacency
60 * matrix (bitmap). Given such an adjacency matrix, the problem of
61 * finding the best sizes for the fragments can be expressed as a
62 * linear programming problem.
64 * We search all possible adjacency matrices, and for each one we run
65 * GLPK's simplex solver. We represent the adjacency matrix as an
66 * array of bitmaps: one word per input stick, with one bit per output
69 * However, there are a couple of wrinkles:
71 * To best represent the problem as a standard LP problem, we separate
72 * out the size of each fragment into a common minimum size variable,
73 * plus a fragment-specific extra size variable. This reduces the LP
74 * problem size at the cost of making the problem construction, and
75 * interpretation of the results, a bit fiddly.
77 * Many of the adjacency matrices are equivalent. In particular,
78 * permutations of the columns, or of the rows, do not change the
79 * meaning. It is only necessasry to consider any one permutation.
80 * We make use of this by considering only adjacency matrices whose
81 * bitmap array contains bitmap words whose numerical values are
82 * nondecreasing in array order.
84 * Once we have a solution, we also avoid considering any candidate
85 * which involves dividing one of the input sticks into so many
86 * fragment that the smallest fragment would necessarily be no bigger
87 * than our best solution. That is, we reject candidates where any of
88 * the hamming weights of the adjacency bitmap words are too large.
90 * We further winnow the set of possible adjacency matrices, by
91 * ensuring the same bit is not set in too many entries of adjmatrix
92 * (ie, as above, only considering output sticks); and by ensuring
93 * that it is not set in too few: each output stick must consist
94 * of at least two fragments since the output sticks are longer than
97 * And, we want to do the search in order of increasing maximum
98 * hamming weight. This is because in practice optimal solutions tend
99 * to have low hamming weight, and having found a reasonable solution
100 * early allows us to eliminate a lot of candidates without doing the
104 typedef uint32_t AdjWord;
105 #define PRADJ "08"PRIx32
107 #define FOR_BITS(j,m) for (j=0, j##bit=1; j < (m); j++, j##bit<<=1)
109 static int n, m, maxhamweight;
110 static AdjWord *adjmatrix;
111 static AdjWord adjall;
114 static glp_prob *best_prob;
115 static AdjWord *best_adjmatrix;
117 static int n_max_frags, m_max_frags;
120 static unsigned printcounter;
122 static void iterate(void);
123 static void iterate_recurse(int i, AdjWord min);
124 static bool preconsider_ok(int nwords, bool doprint);
125 static bool maxhamweight_ok(void);
126 static void optimise(bool doprint);
128 static void progress_eol(void) {
129 fprintf(stderr," \r");
133 static void set_best(double new_best) {
136 * When computing n_max_frags, we want to set a value that will skip
137 * anything that won't provide strictly better solutions. So we
141 * <=> frags < | n / best |
143 * <=> frags <= | n / best | - 1
145 * But best values from glpk are slightly approximate, so we
146 * subtract a fudge factor from our target.
148 double near_best = best * 0.98 - 0.02;
149 n_max_frags = ceil(n / near_best) - 1;
150 m_max_frags = ceil(m / near_best) - 1;
153 /*----- multicore support -----*/
164 * - one pipe ("work") from generator to workers
165 * - ever-extending file ("bus") containing new "best" values
166 * - one file for each worker giving maxhamweight and adjmatrix for best
168 * generator runs iterate_recurse to a certain depth and writes the
169 * candidates to a pipe
171 * workers read candidates from the pipe and resume iterate_recurse
172 * halfway through the recursion
174 * whenever a worker does a doprint, it checks the bus for new best
175 * value; actual best values are appended
177 * master waits for generator and all workers to finish and then
178 * runs optimise() for each worker's best, then prints
181 static int ncpus = 0, multicore_iteration_boundary = INT_MAX;
183 static int mc_bus, mc_work[2];
184 static off_t mc_bus_read;
191 static Worker *mc_us;
192 static bool mc_am_generator;
194 static void multicore_check_for_new_best(void);
197 static AdjWord mc_iter_min;
199 static size_t mc_iovlen;
200 static struct iovec mc_iov[MAX_NIOVS];
202 #define IOV0 (mc_niovs = mc_iovlen = 0)
204 #define IOV(obj, count) ({ \
205 assert(mc_niovs < MAX_NIOVS); \
206 mc_iov[mc_niovs].iov_base = &(obj); \
207 mc_iov[mc_niovs].iov_len = sizeof(obj) * (count); \
208 mc_iovlen += mc_iov[mc_niovs].iov_len; \
212 static void mc_rwvsetup_outer(void) {
214 IOV(maxhamweight, 1);
216 IOV(*adjmatrix, multicore_iteration_boundary);
220 static void mc_rwvsetup_full(void) {
225 static void vlprintf(const char *fmt, va_list al) {
226 vfprintf(stderr,fmt,al);
230 static void LPRINTF(const char *fmt, ...) {
237 static void mc_awaitpid(int wnum, pid_t pid) {
238 LPRINTF("master awaiting %2d [%ld]",wnum,(long)pid);
240 pid_t got = waitpid(pid, &status, 0);
243 fprintf(stderr,"\nFAILED SUBPROC %2d [%ld] %d\n",
244 wnum, (long)pid, status);
249 static void multicore_outer_iteration(int i, AdjWord min) {
250 static unsigned check_counter;
252 assert(i == multicore_iteration_boundary);
255 ssize_t r = writev(mc_work[1], mc_iov, mc_niovs);
256 assert(r == mc_iovlen);
257 /* effectively, this writev arranges to transfers control
258 * to some worker's instance of iterate_recurse via mc_iterate_worker */
260 if (!(check_counter++ & 0xff))
261 multicore_check_for_new_best();
264 static void mc_iterate_worker(void) {
267 ssize_t r = readv(mc_work[0], mc_iov, mc_niovs);
269 assert(r == mc_iovlen);
271 bool ok = maxhamweight_ok();
274 ok = preconsider_ok(multicore_iteration_boundary, 1);
278 /* stop iterate_recurse from trying to run multicore_outer_iteration */
279 int mc_org_it_bound = multicore_iteration_boundary;
280 multicore_iteration_boundary = INT_MAX;
281 iterate_recurse(mc_org_it_bound, mc_iter_min);
282 multicore_iteration_boundary = mc_org_it_bound;
284 if (best_adjmatrix) {
285 LPRINTF("worker %2d reporting",mc_us->w);
286 adjmatrix = best_adjmatrix;
288 ssize_t r = writev(fileno(mc_us->results), mc_iov, mc_niovs);
289 assert(r == mc_iovlen);
291 LPRINTF("worker %2d ending",mc_us->w);
295 static void multicore(void) {
300 multicore_iteration_boundary = n / 2;
302 FILE *busf = tmpfile(); assert(busf);
303 mc_bus = fileno(busf);
304 int r = fcntl(mc_bus, F_GETFL); assert(r >= 0);
306 r = fcntl(mc_bus, F_SETFL, r); assert(r >= 0);
308 r = pipe(mc_work); assert(!r);
310 mc_workers = xmalloc(sizeof(*mc_workers) * ncpus);
311 for (w=0; w<ncpus; w++) {
313 mc_workers[w].results = tmpfile(); assert(mc_workers[w].results);
314 mc_workers[w].pid = fork(); assert(mc_workers[w].pid >= 0);
315 if (!mc_workers[w].pid) {
316 mc_us = &mc_workers[w];
318 LPRINTF("worker %2d running", w);
326 genpid = fork(); assert(genpid >= 0);
329 LPRINTF("generator running");
335 mc_awaitpid(-1, genpid);
336 for (w=0; w<ncpus; w++)
337 mc_awaitpid(w, mc_workers[w].pid);
339 for (w=0; w<ncpus; w++) {
341 LPRINTF("reading report from %2d",w);
342 ssize_t sr = preadv(fileno(mc_workers[w].results), mc_iov, mc_niovs, 0);
344 LPRINTF("got report from %2d",w);
350 static void multicore_check_for_new_best(void) {
351 if (!(mc_us || mc_am_generator))
356 ssize_t got = pread(mc_bus, &msg, sizeof(msg), mc_bus_read);
358 assert(got == sizeof(msg));
361 mc_bus_read += sizeof(msg);
365 static void multicore_found_new_best(void) {
369 if (mc_us /* might be master */) fprintf(stderr," w%-2d ",mc_us->w);
370 ssize_t wrote = write(mc_bus, &best, sizeof(best));
371 assert(wrote == sizeof(best));
374 /*----- end of multicore support -----*/
376 static AdjWord *xalloc_adjmatrix(void) {
377 return xmalloc(sizeof(*adjmatrix)*n);
380 static void prep(void) {
381 adjall = ~((~(AdjWord)0) << m);
382 adjmatrix = xalloc_adjmatrix();
383 glp_term_out(GLP_OFF);
385 weight = calloc(sizeof(*weight), m); assert(weight);
386 n_max_frags = INT_MAX;
387 m_max_frags = INT_MAX;
391 static AdjWord one_adj_bit(int bitnum) {
392 return (AdjWord)1 << bitnum;
396 static int count_set_adj_bits(AdjWord w) {
400 total += !!(w & jbit);
404 #define PRINTF(...) if (!doprint) ; else fprintf(stderr, __VA_ARGS__)
406 static int totalfrags;
408 static bool maxhamweight_ok(void) {
409 return maxhamweight <= m_max_frags;
412 static bool preconsider_ok(int nwords, bool doprint) {
415 PRINTF("%2d ", maxhamweight);
418 for (i=0, totalfrags=0; i<nwords; i++) {
419 int frags = count_set_adj_bits(adjmatrix[i]);
420 PRINTF("%"PRADJ" ", adjmatrix[i]);
421 if (frags > m_max_frags) {
425 had_max += (frags >= maxhamweight);
429 /* Skip this candidate as its max hamming weight is lower than
430 * we're currently looking for (which means we must have done it
431 * already). (The recursive iteration ensures that none of the
432 * words have more than the max hamming weight.) */
442 static void optimise(bool doprint) {
443 /* Consider the best answer (if any) for a given adjacency matrix */
449 * Up to a certain point, optimise() can be restarted. We use this
450 * to go back and print the debugging output if it turns out that we
451 * have an interesting case. The HAVE_PRINTED macro does this: its
452 * semantics are to go back in time and make sure that we have
453 * printed the description of the search case.
455 #define HAVE_PRINTED ({ \
456 if (!doprint) { doprint = 1; goto retry_with_print; } \
460 glp_delete_prob(prob);
464 bool ok = preconsider_ok(n, doprint);
469 * We formulate our problem as an LP problem as follows.
470 * In this file "n" and "m" are the matchstick numbers.
472 * Each set bit in the adjacency matrix corresponds to taking a
473 * fragment from old match i and making it part of new match j.
475 * The structural variables (columns) are:
476 * x_minimum minimum size of any fragment (bounded below by 0)
477 * x_morefrag_i_j the amount by which the size of the fragment
478 * i,j exceeds the minimum size (bounded below by 0)
480 * The auxiliary variables (rows) are:
481 * x_total_i total length for each input match (fixed variable)
482 * x_total_j total length for each output match (fixed variable)
484 * The objective function is simply
487 * We use X_ and Y_ to refer to GLPK's (1-based) column and row indices.
488 * ME_ refers to entries in the list of constraint matrix elements
489 * which we build up as we go.
492 prob = glp_create_prob();
494 int Y_totals_i = glp_add_rows(prob, n);
495 int Y_totals_j = glp_add_rows(prob, m);
496 int X_minimum = glp_add_cols(prob, 1);
499 int next_matrix_entry = 1; /* wtf GLPK! */
500 int matrix_entries_size = next_matrix_entry + n + m + totalfrags*2;
501 double matrix_entries[matrix_entries_size];
502 int matrix_entries_XY[2][matrix_entries_size];
504 #define ADD_MATRIX_ENTRY(Y,X) ({ \
505 assert(next_matrix_entry < matrix_entries_size); \
506 matrix_entries_XY[0][next_matrix_entry] = (X); \
507 matrix_entries_XY[1][next_matrix_entry] = (Y); \
508 matrix_entries[next_matrix_entry] = 0; \
509 next_matrix_entry++; \
512 int ME_totals_i__minimum = next_matrix_entry;
513 for (i=0; i<n; i++) ADD_MATRIX_ENTRY(Y_totals_i+i, X_minimum);
515 int ME_totals_j__minimum = next_matrix_entry;
516 for (j=0; j<m; j++) ADD_MATRIX_ENTRY(Y_totals_j+j, X_minimum);
518 /* \forall_i x_total_i = m */
519 /* \forall_i x_total_j = n */
520 for (i=0; i<n; i++) glp_set_row_bnds(prob, Y_totals_i+i, GLP_FX, m,m);
521 for (j=0; j<m; j++) glp_set_row_bnds(prob, Y_totals_j+j, GLP_FX, n,n);
524 glp_set_col_bnds(prob, X_minimum, GLP_LO, 0, 0);
525 glp_set_col_name(prob, X_minimum, "minimum");
527 /* objective is maximising x_minimum */
528 glp_set_obj_dir(prob, GLP_MAX);
529 glp_set_obj_coef(prob, X_minimum, 1);
531 for (i=0; i<n; i++) {
533 if (!(adjmatrix[i] & jbit))
535 /* x_total_i += x_minimum */
536 /* x_total_j += x_minimum */
537 matrix_entries[ ME_totals_i__minimum + i ] ++;
538 matrix_entries[ ME_totals_j__minimum + j ] ++;
540 /* x_morefrag_i_j >= 0 */
541 int X_morefrag_i_j = glp_add_cols(prob, 1);
542 glp_set_col_bnds(prob, X_morefrag_i_j, GLP_LO, 0, 0);
545 snprintf(buf,sizeof(buf),"mf %d,%d",i,j);
546 glp_set_col_name(prob, X_morefrag_i_j, buf);
549 /* x_total_i += x_morefrag_i_j */
550 /* x_total_j += x_morefrag_i_j */
551 int ME_totals_i__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_i+i, X_morefrag_i_j);
552 int ME_totals_j__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_j+j, X_morefrag_i_j);
553 matrix_entries[ME_totals_i__mf_i_j] = 1;
554 matrix_entries[ME_totals_j__mf_i_j] = 1;
558 assert(next_matrix_entry == matrix_entries_size);
560 glp_load_matrix(prob, matrix_entries_size-1,
561 matrix_entries_XY[1], matrix_entries_XY[0],
564 int r = glp_simplex(prob, NULL);
565 PRINTF(" glp=%d", r);
568 case e: PRINTF(" " #e ); goto out;
570 case e: HAVE_PRINTED; printf(" " #e " CRASHING\n"); exit(-1);
572 default: HAVE_PRINTED; printf(" ! CRASHING\n"); exit(-1);
592 r = glp_get_status(prob);
593 PRINTF(" status=%d", r);
605 double got = glp_get_obj_val(prob);
613 multicore_found_new_best();
615 if (best_prob) glp_delete_prob(best_prob);
618 free(best_adjmatrix);
619 best_adjmatrix = xalloc_adjmatrix();
620 memcpy(best_adjmatrix, adjmatrix, sizeof(*adjmatrix)*n);
628 glp_delete_prob(prob);
629 if (doprint) progress_eol();
630 if (doprint) multicore_check_for_new_best();
633 static void iterate_recurse(int i, AdjWord min) {
643 optimise(!(printcounter & 0xfff));
646 if (i >= multicore_iteration_boundary) {
647 multicore_outer_iteration(i, min);
650 for (adjmatrix[i] = min;
653 if (count_set_adj_bits(adjmatrix[i]) > maxhamweight)
655 if (i == 0 && (adjmatrix[i] & (1+adjmatrix[i])))
659 if (adjmatrix[i] & jbit)
661 for (int j = 0; j < m; j++)
662 if (weight[j] >= n_max_frags)
665 iterate_recurse(i+1, adjmatrix[i]);
669 if (adjmatrix[i] & jbit)
673 if (adjmatrix[i] == adjall)
678 static void iterate(void) {
679 for (maxhamweight=1; maxhamweight<=m; maxhamweight++) {
680 if (!maxhamweight_ok())
683 iterate_recurse(0, 1);
687 static void report(void) {
688 fprintf(stderr, "\n");
690 double min = glp_get_obj_val(best_prob);
693 for (i = 0; i < n; i++)
694 for (j = 0; j < m; j++)
696 cols = glp_get_num_cols(best_prob);
697 for (i = 1; i <= cols; i++) {
699 if (2 != sscanf(glp_get_col_name(best_prob, i), "mf %d,%d", &x, &y))
701 a[x][y] = min + glp_get_col_prim(best_prob, i);
703 printf("%d into %d: min fragment %g [%s]\n", n, m, min, VERSION);
704 for (i = 0; i < n; i++) {
705 for (j = 0; j < m; j++) {
707 printf(" %9.3f", a[i][j]);
714 if (ferror(stdout) || fclose(stdout)) { perror("stdout"); exit(-1); }
717 int main(int argc, char **argv) {
719 while ((opt = getopt(argc,argv,"j:")) >= 0) {
721 case 'j': ncpus = atoi(optarg); break;
722 case '+': assert(!"bad option");
735 if (ncpus) multicore();