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.
37 #include <sys/types.h>
40 #include <sys/fcntl.h>
47 * Each input match contributes, or does not contribute, to each
48 * output match; we do not need to consider multiple fragments
49 * relating to the same input/output pair this gives an n*m adjacency
50 * matrix (bitmap). Given such an adjacency matrix, the problem of
51 * finding the best sizes for the fragments can be expressed as a
52 * linear programming problem.
54 * We search all possible adjacency matrices, and for each one we run
55 * GLPK's simplex solver. We represent the adjacency matrix as an
58 * However, there are a couple of wrinkles:
60 * To best represent the problem as a standard LP problem, we separate
61 * out the size of each fragment into a common minimum size variable,
62 * plus a fragment-specific extra size variable. This reduces the LP
63 * problem size at the cost of making the problem construction, and
64 * interpretation of the results, a bit fiddly.
66 * Many of the adjacency matrices are equivalent. In particular,
67 * permutations of the columns, or of the rows, do not change the
68 * meaning. It is only necessasry to consider any one permutation.
69 * We make use of this by considering only adjacency matrices whose
70 * bitmap array contains bitmap words whose numerical values are
71 * nondecreasing in array order.
73 * Once we have a solution, we also avoid considering any candidate
74 * which involves dividing one of the output sticks into so many
75 * fragment that the smallest fragment would necessarily be no bigger
76 * than our best solution. That is, we reject candidates where any of
77 * the hamming weights of the adjacency bitmap words are too large.
79 * And, we want to do the search in order of increasing maximum
80 * hamming weight. This is because in practice optimal solutions tend
81 * to have low hamming weight, and having found a reasonable solution
82 * early allows us to eliminate a lot of candidates without doing the
86 typedef uint32_t AdjWord;
87 #define PRADJ "08"PRIx32
89 static int n, m, maxhamweight;
90 static AdjWord *adjmatrix;
91 static AdjWord adjall;
94 static glp_prob *best_prob;
95 static AdjWord *best_adjmatrix;
97 static unsigned printcounter;
99 static void iterate(void);
100 static void iterate_recurse(int i, AdjWord min);
101 static bool preconsider_ok(int nwords, bool doprint);
102 static bool maxhamweight_ok(void);
103 static void optimise(bool doprint);
105 static void progress_eol(void) {
106 fprintf(stderr," \r");
110 /*----- multicore support -----*/
121 * - one pipe ("work") from generator to workers
122 * - ever-extending file ("bus") containing new "best" values
123 * - one file for each worker giving maxhamweight and adjmatrix for best
125 * generator runs iterate_recurse to a certain depth and writes the
126 * candidates to a pipe
128 * workers read candidates from the pipe and resume iterate_recurse
129 * halfway through the recursion
131 * whenever a worker does a doprint, it checks the bus for new best
132 * value; actual best values are appended
134 * master waits for generator and all workers to finish and then
135 * runs optimise() for each worker's best, then prints
138 static int ncpus = 0, multicore_iteration_boundary = INT_MAX;
140 static int mc_bus, mc_work[2];
141 static off_t mc_bus_read;
148 static Worker *mc_us;
150 static void multicore_check_for_new_best(void);
153 static AdjWord mc_iter_min;
155 static size_t mc_iovlen;
156 static struct iovec mc_iov[MAX_NIOVS];
158 #define IOV0 (mc_niovs = mc_iovlen = 0)
160 #define IOV(obj, count) ({ \
161 assert(mc_niovs < MAX_NIOVS); \
162 mc_iov[mc_niovs].iov_base = &(obj); \
163 mc_iov[mc_niovs].iov_len = sizeof(obj) * (count); \
164 mc_iovlen += mc_iov[mc_niovs].iov_len; \
168 static void mc_rwvsetup_outer(void) {
170 IOV(maxhamweight, 1);
172 IOV(*adjmatrix, multicore_iteration_boundary);
175 static void mc_rwvsetup_full(void) {
180 static void vlprintf(const char *fmt, va_list al) {
181 vfprintf(stderr,fmt,al);
185 static void LPRINTF(const char *fmt, ...) {
192 static void mc_awaitpid(int wnum, pid_t pid) {
193 LPRINTF("master awaiting %2d [%ld]",wnum,(long)pid);
195 pid_t got = waitpid(pid, &status, 0);
198 fprintf(stderr,"\nFAILED SUBPROC %2d [%ld] %d\n",
199 wnum, (long)pid, status);
204 static void multicore_outer_iteration(int i, AdjWord min) {
205 static unsigned check_counter;
207 assert(i == multicore_iteration_boundary);
210 ssize_t r = writev(mc_work[1], mc_iov, mc_niovs);
211 assert(r == mc_iovlen);
212 /* effectively, this writev arranges to transfers control
213 * to some worker's instance of iterate_recurse via mc_iterate_worker */
215 if (!(check_counter++ & 0xff))
216 multicore_check_for_new_best();
219 static void mc_iterate_worker(void) {
222 ssize_t r = readv(mc_work[0], mc_iov, mc_niovs);
224 assert(r == mc_iovlen);
226 bool ok = maxhamweight_ok();
229 ok = preconsider_ok(multicore_iteration_boundary, 1);
233 /* stop iterate_recurse from trying to run multicore_outer_iteration */
234 int mc_org_it_bound = multicore_iteration_boundary;
235 multicore_iteration_boundary = INT_MAX;
236 iterate_recurse(mc_org_it_bound, mc_iter_min);
237 multicore_iteration_boundary = mc_org_it_bound;
239 LPRINTF("worker %2d reporting",mc_us->w);
240 if (best_adjmatrix) {
241 adjmatrix = best_adjmatrix;
243 ssize_t r = writev(fileno(mc_us->results), mc_iov, mc_niovs);
244 assert(r == mc_iovlen);
246 LPRINTF("worker %2d ending",mc_us->w);
250 static void multicore(void) {
255 multicore_iteration_boundary = n / 2;
257 FILE *busf = tmpfile(); assert(busf);
258 mc_bus = fileno(busf);
259 int r = fcntl(mc_bus, F_GETFL); assert(r >= 0);
261 r = fcntl(mc_bus, F_SETFL, r); assert(r >= 0);
263 r = pipe(mc_work); assert(!r);
265 mc_workers = xmalloc(sizeof(*mc_workers) * ncpus);
266 for (w=0; w<ncpus; w++) {
268 mc_workers[w].results = tmpfile(); assert(mc_workers[w].results);
269 mc_workers[w].pid = fork(); assert(mc_workers[w].pid >= 0);
270 if (!mc_workers[w].pid) {
271 mc_us = &mc_workers[w];
273 LPRINTF("worker %2d running", w);
281 genpid = fork(); assert(genpid >= 0);
283 LPRINTF("generator running");
289 mc_awaitpid(-1, genpid);
290 for (w=0; w<ncpus; w++)
291 mc_awaitpid(w, mc_workers[w].pid);
293 for (w=0; w<ncpus; w++) {
295 LPRINTF("reading report from %2d",w);
296 ssize_t sr = preadv(fileno(mc_workers[w].results), mc_iov, mc_niovs, 0);
303 static void multicore_check_for_new_best(void) {
308 ssize_t got = pread(mc_bus, &msg, sizeof(msg), mc_bus_read);
310 assert(got == sizeof(msg));
313 mc_bus_read += sizeof(msg);
317 static void multicore_found_new_best(void) {
320 if (mc_us /* might be master */) fprintf(stderr," w%-2d ",mc_us->w);
321 ssize_t wrote = write(mc_bus, &best, sizeof(best));
322 assert(wrote == sizeof(best));
325 /*----- end of multicore support -----*/
327 static AdjWord *xalloc_adjmatrix(void) {
328 return xmalloc(sizeof(*adjmatrix)*n);
331 static void prep(void) {
332 adjall = ~((~(AdjWord)0) << m);
333 adjmatrix = xalloc_adjmatrix();
334 glp_term_out(GLP_OFF);
338 static AdjWord one_adj_bit(int bitnum) {
339 return (AdjWord)1 << bitnum;
342 static int count_set_adj_bits(AdjWord w) {
344 for (j=0, total=0; j<m; j++)
345 total += !!(w & one_adj_bit(j));
349 #define PRINTF(...) if (!doprint) ; else fprintf(stderr, __VA_ARGS__)
351 static int totalfrags;
353 static bool maxhamweight_ok(void) {
354 double maxminsize = (double)m / maxhamweight;
355 return maxminsize > best;
358 static bool preconsider_ok(int nwords, bool doprint) {
361 PRINTF("%2d ", maxhamweight);
364 for (i=0, totalfrags=0; i<nwords; i++) {
365 int frags = count_set_adj_bits(adjmatrix[i]);
366 had_max += (frags >= maxhamweight);
368 PRINTF("%"PRADJ" ", adjmatrix[i]);
369 double maxminsize = (double)m / frags;
370 if (maxminsize <= best) {
376 /* Skip this candidate as its max hamming weight is lower than
377 * we're currently looking for (which means we must have done it
378 * already). (The recursive iteration ensures that none of the
379 * words have more than the max hamming weight.) */
389 static void optimise(bool doprint) {
390 /* Consider the best answer (if any) for a given adjacency matrix */
395 * Up to a certain point, optimise() can be restarted. We use this
396 * to go back and print the debugging output if it turns out that we
397 * have an interesting case. The HAVE_PRINTED macro does this: its
398 * semantics are to go back in time and make sure that we have
399 * printed the description of the search case.
401 #define HAVE_PRINTED ({ \
402 if (!doprint) { doprint = 1; goto retry_with_print; } \
406 glp_delete_prob(prob);
410 bool ok = preconsider_ok(n, doprint);
415 * We formulate our problem as an LP problem as follows.
416 * In this file "n" and "m" are the matchstick numbers.
418 * Each set bit in the adjacency matrix corresponds to taking a
419 * fragment from old match i and making it part of new match j.
421 * The structural variables (columns) are:
422 * x_minimum minimum size of any fragment (bounded below by 0)
423 * x_morefrag_i_j the amount by which the size of the fragment
424 * i,j exceeds the minimum size (bounded below by 0)
426 * The auxiliary variables (rows) are:
427 * x_total_i total length for each input match (fixed variable)
428 * x_total_j total length for each output match (fixed variable)
430 * The objective function is simply
433 * We use X_ and Y_ to refer to GLPK's (1-based) column and row indices.
434 * ME_ refers to entries in the list of constraint matrix elements
435 * which we build up as we go.
438 prob = glp_create_prob();
440 int Y_totals_i = glp_add_rows(prob, n);
441 int Y_totals_j = glp_add_rows(prob, m);
442 int X_minimum = glp_add_cols(prob, 1);
445 int next_matrix_entry = 1; /* wtf GLPK! */
446 int matrix_entries_size = next_matrix_entry + n + m + totalfrags*2;
447 double matrix_entries[matrix_entries_size];
448 int matrix_entries_XY[2][matrix_entries_size];
450 #define ADD_MATRIX_ENTRY(Y,X) ({ \
451 assert(next_matrix_entry < matrix_entries_size); \
452 matrix_entries_XY[0][next_matrix_entry] = (X); \
453 matrix_entries_XY[1][next_matrix_entry] = (Y); \
454 matrix_entries[next_matrix_entry] = 0; \
455 next_matrix_entry++; \
458 int ME_totals_i__minimum = next_matrix_entry;
459 for (i=0; i<n; i++) ADD_MATRIX_ENTRY(Y_totals_i+i, X_minimum);
461 int ME_totals_j__minimum = next_matrix_entry;
462 for (j=0; j<m; j++) ADD_MATRIX_ENTRY(Y_totals_j+j, X_minimum);
464 /* \forall_i x_total_i = m */
465 /* \forall_i x_total_j = n */
466 for (i=0; i<n; i++) glp_set_row_bnds(prob, Y_totals_i+i, GLP_FX, m,m);
467 for (j=0; j<m; j++) glp_set_row_bnds(prob, Y_totals_j+j, GLP_FX, n,n);
470 glp_set_col_bnds(prob, X_minimum, GLP_LO, 0, 0);
471 glp_set_col_name(prob, X_minimum, "minimum");
473 /* objective is maximising x_minimum */
474 glp_set_obj_dir(prob, GLP_MAX);
475 glp_set_obj_coef(prob, X_minimum, 1);
477 for (i=0; i<n; i++) {
478 for (j=0; j<m; j++) {
479 if (!(adjmatrix[i] & one_adj_bit(j)))
481 /* x_total_i += x_minimum */
482 /* x_total_j += x_minimum */
483 matrix_entries[ ME_totals_i__minimum + i ] ++;
484 matrix_entries[ ME_totals_j__minimum + j ] ++;
486 /* x_morefrag_i_j >= 0 */
487 int X_morefrag_i_j = glp_add_cols(prob, 1);
488 glp_set_col_bnds(prob, X_morefrag_i_j, GLP_LO, 0, 0);
491 snprintf(buf,sizeof(buf),"mf %d,%d",i,j);
492 glp_set_col_name(prob, X_morefrag_i_j, buf);
495 /* x_total_i += x_morefrag_i_j */
496 /* x_total_j += x_morefrag_i_j */
497 int ME_totals_i__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_i+i, X_morefrag_i_j);
498 int ME_totals_j__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_j+j, X_morefrag_i_j);
499 matrix_entries[ME_totals_i__mf_i_j] = 1;
500 matrix_entries[ME_totals_j__mf_i_j] = 1;
504 assert(next_matrix_entry == matrix_entries_size);
506 glp_load_matrix(prob, matrix_entries_size-1,
507 matrix_entries_XY[1], matrix_entries_XY[0],
510 int r = glp_simplex(prob, NULL);
511 PRINTF(" glp=%d", r);
514 case e: PRINTF(" " #e ); goto out;
516 case e: HAVE_PRINTED; printf(" " #e " CRASHING\n"); exit(-1);
518 default: HAVE_PRINTED; printf(" ! CRASHING\n"); exit(-1);
538 r = glp_get_status(prob);
539 PRINTF(" status=%d", r);
551 double got = glp_get_obj_val(prob);
559 multicore_found_new_best();
561 if (best_prob) glp_delete_prob(best_prob);
564 free(best_adjmatrix);
565 best_adjmatrix = xalloc_adjmatrix();
566 memcpy(best_adjmatrix, adjmatrix, sizeof(*adjmatrix)*n);
574 glp_delete_prob(prob);
575 if (doprint) progress_eol();
576 if (doprint) multicore_check_for_new_best();
579 static void iterate_recurse(int i, AdjWord min) {
582 optimise(!(printcounter & 0xfff));
585 if (i >= multicore_iteration_boundary) {
586 multicore_outer_iteration(i, min);
589 for (adjmatrix[i] = min;
592 if (count_set_adj_bits(adjmatrix[i]) > maxhamweight)
594 if (i == 0 && (adjmatrix[i] & (1+adjmatrix[i])))
597 iterate_recurse(i+1, adjmatrix[i]);
600 if (adjmatrix[i] == adjall)
605 static void iterate(void) {
606 for (maxhamweight=1; maxhamweight<=m; maxhamweight++) {
607 if (!maxhamweight_ok())
610 iterate_recurse(0, 1);
614 static void report(void) {
615 fprintf(stderr, "\n");
617 double min = glp_get_obj_val(best_prob);
620 for (i = 0; i < n; i++)
621 for (j = 0; j < m; j++)
623 cols = glp_get_num_cols(best_prob);
624 for (i = 1; i <= cols; i++) {
626 if (2 != sscanf(glp_get_col_name(best_prob, i), "mf %d,%d", &x, &y))
628 a[x][y] = min + glp_get_col_prim(best_prob, i);
630 printf("%d into %d: min fragment %g\n", n, m, min);
631 for (i = 0; i < n; i++) {
632 for (j = 0; j < m; j++) {
634 printf(" %9.3f", a[i][j]);
641 if (ferror(stdout) || fclose(stdout)) { perror("stdout"); exit(-1); }
644 int main(int argc, char **argv) {
646 while ((opt = getopt(argc,argv,"j:")) >= 0) {
648 case 'j': ncpus = atoi(optarg); break;
649 case '+': assert(!"bad option");
661 if (ncpus) multicore();