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
14 * matchsticks/main.c Copyright 2014 Ian Jackson
16 * This program is free software: you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License as published by
18 * the Free Software Foundation, either version 3 of the License, or
19 * (at your option) any later version.
21 * This program is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 * GNU General Public License for more details.
40 #include <sys/types.h>
43 #include <sys/fcntl.h>
48 #define VERSION "(unknown-version)"
54 * Each input match contributes, or does not contribute, to each
55 * output match; we do not need to consider multiple fragments
56 * relating to the same input/output pair this gives an n*m adjacency
57 * matrix (bitmap). Given such an adjacency matrix, the problem of
58 * finding the best sizes for the fragments can be expressed as a
59 * linear programming problem.
61 * We search all possible adjacency matrices, and for each one we run
62 * GLPK's simplex solver. We represent the adjacency matrix as an
63 * array of bitmaps: one word per input stick, with one bit per output
66 * However, there are a couple of wrinkles:
68 * To best represent the problem as a standard LP problem, we separate
69 * out the size of each fragment into a common minimum size variable,
70 * plus a fragment-specific extra size variable. This reduces the LP
71 * problem size at the cost of making the problem construction, and
72 * interpretation of the results, a bit fiddly.
74 * Many of the adjacency matrices are equivalent. In particular,
75 * permutations of the columns, or of the rows, do not change the
76 * meaning. It is only necessasry to consider any one permutation.
77 * We make use of this by considering only adjacency matrices whose
78 * bitmap array contains bitmap words whose numerical values are
79 * nondecreasing in array order.
81 * Once we have a solution, we also avoid considering any candidate
82 * which involves dividing one of the input sticks into so many
83 * fragment that the smallest fragment would necessarily be no bigger
84 * than our best solution. That is, we reject candidates where any of
85 * the hamming weights of the adjacency bitmap words are too large.
87 * We further winnow the set of possible adjacency matrices, by
88 * ensuring the same bit is not set in too many entries of adjmatrix
89 * (ie, as above, only considering output sticks); and by ensuring
90 * that it is not set in too few: each output stick must consist
91 * of at least two fragments since the output sticks are longer than
94 * And, we want to do the search in order of increasing maximum
95 * hamming weight. This is because in practice optimal solutions tend
96 * to have low hamming weight, and having found a reasonable solution
97 * early allows us to eliminate a lot of candidates without doing the
101 typedef uint32_t AdjWord;
102 #define PRADJ "08"PRIx32
104 #define FOR_BITS(j,m) for (j=0, j##bit=1; j < (m); j++, j##bit<<=1)
106 static int n, m, maxhamweight;
107 static AdjWord *adjmatrix;
108 static AdjWord adjall;
111 static glp_prob *best_prob;
112 static AdjWord *best_adjmatrix;
114 static int n_max_frags, m_max_frags;
117 static unsigned printcounter;
119 static void iterate(void);
120 static void iterate_recurse(int i, AdjWord min);
121 static bool preconsider_ok(int nwords, bool doprint);
122 static bool maxhamweight_ok(void);
123 static void optimise(bool doprint);
125 static void progress_eol(void) {
126 fprintf(stderr," \r");
130 static void set_best(double new_best) {
133 * When computing n_max_frags, we want to set a value that will skip
134 * anything that won't provide strictly better solutions. So we
138 * <=> frags < | n / best |
140 * <=> frags <= | n / best | - 1
142 * But best values from glpk are slightly approximate, so we
143 * subtract a fudge factor from our target.
145 double near_best = best * 0.98 - 0.02;
146 n_max_frags = ceil(n / near_best) - 1;
147 m_max_frags = ceil(m / near_best) - 1;
150 /*----- multicore support -----*/
161 * - one pipe ("work") from generator to workers
162 * - ever-extending file ("bus") containing new "best" values
163 * - one file for each worker giving maxhamweight and adjmatrix for best
165 * generator runs iterate_recurse to a certain depth and writes the
166 * candidates to a pipe
168 * workers read candidates from the pipe and resume iterate_recurse
169 * halfway through the recursion
171 * whenever a worker does a doprint, it checks the bus for new best
172 * value; actual best values are appended
174 * master waits for generator and all workers to finish and then
175 * runs optimise() for each worker's best, then prints
178 static int ncpus = 0, multicore_iteration_boundary = INT_MAX;
180 static int mc_bus, mc_work[2];
181 static off_t mc_bus_read;
188 static Worker *mc_us;
189 static bool mc_am_generator;
191 static void multicore_check_for_new_best(void);
194 static AdjWord mc_iter_min;
196 static size_t mc_iovlen;
197 static struct iovec mc_iov[MAX_NIOVS];
199 #define IOV0 (mc_niovs = mc_iovlen = 0)
201 #define IOV(obj, count) ({ \
202 assert(mc_niovs < MAX_NIOVS); \
203 mc_iov[mc_niovs].iov_base = &(obj); \
204 mc_iov[mc_niovs].iov_len = sizeof(obj) * (count); \
205 mc_iovlen += mc_iov[mc_niovs].iov_len; \
209 static void mc_rwvsetup_outer(void) {
211 IOV(maxhamweight, 1);
213 IOV(*adjmatrix, multicore_iteration_boundary);
217 static void mc_rwvsetup_full(void) {
222 static void vlprintf(const char *fmt, va_list al) {
223 vfprintf(stderr,fmt,al);
227 static void LPRINTF(const char *fmt, ...) {
234 static void mc_awaitpid(int wnum, pid_t pid) {
235 LPRINTF("master awaiting %2d [%ld]",wnum,(long)pid);
237 pid_t got = waitpid(pid, &status, 0);
240 fprintf(stderr,"\nFAILED SUBPROC %2d [%ld] %d\n",
241 wnum, (long)pid, status);
246 static void multicore_outer_iteration(int i, AdjWord min) {
247 static unsigned check_counter;
249 assert(i == multicore_iteration_boundary);
252 ssize_t r = writev(mc_work[1], mc_iov, mc_niovs);
253 assert(r == mc_iovlen);
254 /* effectively, this writev arranges to transfers control
255 * to some worker's instance of iterate_recurse via mc_iterate_worker */
257 if (!(check_counter++ & 0xff))
258 multicore_check_for_new_best();
261 static void mc_iterate_worker(void) {
264 ssize_t r = readv(mc_work[0], mc_iov, mc_niovs);
266 assert(r == mc_iovlen);
268 bool ok = maxhamweight_ok();
271 ok = preconsider_ok(multicore_iteration_boundary, 1);
275 /* stop iterate_recurse from trying to run multicore_outer_iteration */
276 int mc_org_it_bound = multicore_iteration_boundary;
277 multicore_iteration_boundary = INT_MAX;
278 iterate_recurse(mc_org_it_bound, mc_iter_min);
279 multicore_iteration_boundary = mc_org_it_bound;
281 if (best_adjmatrix) {
282 LPRINTF("worker %2d reporting",mc_us->w);
283 adjmatrix = best_adjmatrix;
285 ssize_t r = writev(fileno(mc_us->results), mc_iov, mc_niovs);
286 assert(r == mc_iovlen);
288 LPRINTF("worker %2d ending",mc_us->w);
292 static void multicore(void) {
297 multicore_iteration_boundary = n / 2;
299 FILE *busf = tmpfile(); assert(busf);
300 mc_bus = fileno(busf);
301 int r = fcntl(mc_bus, F_GETFL); assert(r >= 0);
303 r = fcntl(mc_bus, F_SETFL, r); assert(r >= 0);
305 r = pipe(mc_work); assert(!r);
307 mc_workers = xmalloc(sizeof(*mc_workers) * ncpus);
308 for (w=0; w<ncpus; w++) {
310 mc_workers[w].results = tmpfile(); assert(mc_workers[w].results);
311 mc_workers[w].pid = fork(); assert(mc_workers[w].pid >= 0);
312 if (!mc_workers[w].pid) {
313 mc_us = &mc_workers[w];
315 LPRINTF("worker %2d running", w);
323 genpid = fork(); assert(genpid >= 0);
326 LPRINTF("generator running");
332 mc_awaitpid(-1, genpid);
333 for (w=0; w<ncpus; w++)
334 mc_awaitpid(w, mc_workers[w].pid);
336 for (w=0; w<ncpus; w++) {
338 LPRINTF("reading report from %2d",w);
339 ssize_t sr = preadv(fileno(mc_workers[w].results), mc_iov, mc_niovs, 0);
341 LPRINTF("got report from %2d",w);
347 static void multicore_check_for_new_best(void) {
348 if (!(mc_us || mc_am_generator))
353 ssize_t got = pread(mc_bus, &msg, sizeof(msg), mc_bus_read);
355 assert(got == sizeof(msg));
358 mc_bus_read += sizeof(msg);
362 static void multicore_found_new_best(void) {
366 if (mc_us /* might be master */) fprintf(stderr," w%-2d ",mc_us->w);
367 ssize_t wrote = write(mc_bus, &best, sizeof(best));
368 assert(wrote == sizeof(best));
371 /*----- end of multicore support -----*/
373 static AdjWord *xalloc_adjmatrix(void) {
374 return xmalloc(sizeof(*adjmatrix)*n);
377 static void prep(void) {
378 adjall = ~((~(AdjWord)0) << m);
379 adjmatrix = xalloc_adjmatrix();
380 glp_term_out(GLP_OFF);
382 weight = calloc(sizeof(*weight), m); assert(weight);
383 n_max_frags = INT_MAX;
384 m_max_frags = INT_MAX;
388 static AdjWord one_adj_bit(int bitnum) {
389 return (AdjWord)1 << bitnum;
393 static int count_set_adj_bits(AdjWord w) {
397 total += !!(w & jbit);
401 #define PRINTF(...) if (!doprint) ; else fprintf(stderr, __VA_ARGS__)
403 static int totalfrags;
405 static bool maxhamweight_ok(void) {
406 return maxhamweight <= m_max_frags;
409 static bool preconsider_ok(int nwords, bool doprint) {
412 PRINTF("%2d ", maxhamweight);
415 for (i=0, totalfrags=0; i<nwords; i++) {
416 int frags = count_set_adj_bits(adjmatrix[i]);
417 PRINTF("%"PRADJ" ", adjmatrix[i]);
418 if (frags > m_max_frags) {
422 had_max += (frags >= maxhamweight);
426 /* Skip this candidate as its max hamming weight is lower than
427 * we're currently looking for (which means we must have done it
428 * already). (The recursive iteration ensures that none of the
429 * words have more than the max hamming weight.) */
439 static void optimise(bool doprint) {
440 /* Consider the best answer (if any) for a given adjacency matrix */
446 * Up to a certain point, optimise() can be restarted. We use this
447 * to go back and print the debugging output if it turns out that we
448 * have an interesting case. The HAVE_PRINTED macro does this: its
449 * semantics are to go back in time and make sure that we have
450 * printed the description of the search case.
452 #define HAVE_PRINTED ({ \
453 if (!doprint) { doprint = 1; goto retry_with_print; } \
457 glp_delete_prob(prob);
461 bool ok = preconsider_ok(n, doprint);
466 * We formulate our problem as an LP problem as follows.
467 * In this file "n" and "m" are the matchstick numbers.
469 * Each set bit in the adjacency matrix corresponds to taking a
470 * fragment from old match i and making it part of new match j.
472 * The structural variables (columns) are:
473 * x_minimum minimum size of any fragment (bounded below by 0)
474 * x_morefrag_i_j the amount by which the size of the fragment
475 * i,j exceeds the minimum size (bounded below by 0)
477 * The auxiliary variables (rows) are:
478 * x_total_i total length for each input match (fixed variable)
479 * x_total_j total length for each output match (fixed variable)
481 * The objective function is simply
484 * We use X_ and Y_ to refer to GLPK's (1-based) column and row indices.
485 * ME_ refers to entries in the list of constraint matrix elements
486 * which we build up as we go.
489 prob = glp_create_prob();
491 int Y_totals_i = glp_add_rows(prob, n);
492 int Y_totals_j = glp_add_rows(prob, m);
493 int X_minimum = glp_add_cols(prob, 1);
496 int next_matrix_entry = 1; /* wtf GLPK! */
497 int matrix_entries_size = next_matrix_entry + n + m + totalfrags*2;
498 double matrix_entries[matrix_entries_size];
499 int matrix_entries_XY[2][matrix_entries_size];
501 #define ADD_MATRIX_ENTRY(Y,X) ({ \
502 assert(next_matrix_entry < matrix_entries_size); \
503 matrix_entries_XY[0][next_matrix_entry] = (X); \
504 matrix_entries_XY[1][next_matrix_entry] = (Y); \
505 matrix_entries[next_matrix_entry] = 0; \
506 next_matrix_entry++; \
509 int ME_totals_i__minimum = next_matrix_entry;
510 for (i=0; i<n; i++) ADD_MATRIX_ENTRY(Y_totals_i+i, X_minimum);
512 int ME_totals_j__minimum = next_matrix_entry;
513 for (j=0; j<m; j++) ADD_MATRIX_ENTRY(Y_totals_j+j, X_minimum);
515 /* \forall_i x_total_i = m */
516 /* \forall_i x_total_j = n */
517 for (i=0; i<n; i++) glp_set_row_bnds(prob, Y_totals_i+i, GLP_FX, m,m);
518 for (j=0; j<m; j++) glp_set_row_bnds(prob, Y_totals_j+j, GLP_FX, n,n);
521 glp_set_col_bnds(prob, X_minimum, GLP_LO, 0, 0);
522 glp_set_col_name(prob, X_minimum, "minimum");
524 /* objective is maximising x_minimum */
525 glp_set_obj_dir(prob, GLP_MAX);
526 glp_set_obj_coef(prob, X_minimum, 1);
528 for (i=0; i<n; i++) {
530 if (!(adjmatrix[i] & jbit))
532 /* x_total_i += x_minimum */
533 /* x_total_j += x_minimum */
534 matrix_entries[ ME_totals_i__minimum + i ] ++;
535 matrix_entries[ ME_totals_j__minimum + j ] ++;
537 /* x_morefrag_i_j >= 0 */
538 int X_morefrag_i_j = glp_add_cols(prob, 1);
539 glp_set_col_bnds(prob, X_morefrag_i_j, GLP_LO, 0, 0);
542 snprintf(buf,sizeof(buf),"mf %d,%d",i,j);
543 glp_set_col_name(prob, X_morefrag_i_j, buf);
546 /* x_total_i += x_morefrag_i_j */
547 /* x_total_j += x_morefrag_i_j */
548 int ME_totals_i__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_i+i, X_morefrag_i_j);
549 int ME_totals_j__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_j+j, X_morefrag_i_j);
550 matrix_entries[ME_totals_i__mf_i_j] = 1;
551 matrix_entries[ME_totals_j__mf_i_j] = 1;
555 assert(next_matrix_entry == matrix_entries_size);
557 glp_load_matrix(prob, matrix_entries_size-1,
558 matrix_entries_XY[1], matrix_entries_XY[0],
561 int r = glp_simplex(prob, NULL);
562 PRINTF(" glp=%d", r);
565 case e: PRINTF(" " #e ); goto out;
567 case e: HAVE_PRINTED; printf(" " #e " CRASHING\n"); exit(-1);
569 default: HAVE_PRINTED; printf(" ! CRASHING\n"); exit(-1);
589 r = glp_get_status(prob);
590 PRINTF(" status=%d", r);
602 double got = glp_get_obj_val(prob);
610 multicore_found_new_best();
612 if (best_prob) glp_delete_prob(best_prob);
615 free(best_adjmatrix);
616 best_adjmatrix = xalloc_adjmatrix();
617 memcpy(best_adjmatrix, adjmatrix, sizeof(*adjmatrix)*n);
625 glp_delete_prob(prob);
626 if (doprint) progress_eol();
627 if (doprint) multicore_check_for_new_best();
630 static void iterate_recurse(int i, AdjWord min) {
640 optimise(!(printcounter & 0xfff));
643 if (i >= multicore_iteration_boundary) {
644 multicore_outer_iteration(i, min);
647 for (adjmatrix[i] = min;
650 if (count_set_adj_bits(adjmatrix[i]) > maxhamweight)
652 if (i == 0 && (adjmatrix[i] & (1+adjmatrix[i])))
656 if (adjmatrix[i] & jbit)
658 for (int j = 0; j < m; j++)
659 if (weight[j] >= n_max_frags)
662 iterate_recurse(i+1, adjmatrix[i]);
666 if (adjmatrix[i] & jbit)
670 if (adjmatrix[i] == adjall)
675 static void iterate(void) {
676 for (maxhamweight=1; maxhamweight<=m; maxhamweight++) {
677 if (!maxhamweight_ok())
680 iterate_recurse(0, 1);
684 static void report(void) {
685 fprintf(stderr, "\n");
687 double min = glp_get_obj_val(best_prob);
690 for (i = 0; i < n; i++)
691 for (j = 0; j < m; j++)
693 cols = glp_get_num_cols(best_prob);
694 for (i = 1; i <= cols; i++) {
696 if (2 != sscanf(glp_get_col_name(best_prob, i), "mf %d,%d", &x, &y))
698 a[x][y] = min + glp_get_col_prim(best_prob, i);
700 printf("%d into %d: min fragment %g [%s]\n", n, m, min, VERSION);
701 for (i = 0; i < n; i++) {
702 for (j = 0; j < m; j++) {
704 printf(" %9.3f", a[i][j]);
711 if (ferror(stdout) || fclose(stdout)) { perror("stdout"); exit(-1); }
714 int main(int argc, char **argv) {
716 while ((opt = getopt(argc,argv,"j:")) >= 0) {
718 case 'j': ncpus = atoi(optarg); break;
719 case '+': assert(!"bad option");
732 if (ncpus) multicore();