chiark / gitweb /
a57bd7231a60248d0b9b81c1df24600c12c26d6e
[matchsticks-search.git] / main.c
1 /*
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
4  * as possible.
5  *
6  * Invoke as   ./main n m
7  *
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
11  *
12  * Options:
13  *  -j<jobs>     run in parallel on <jobs> cores
14  *  -b<best>     search only for better than <best>
15  */
16
17 /*
18  * matchsticks/main.c  Copyright 2014 Ian Jackson
19  *
20  * This program is free software: you can redistribute it and/or modify
21  * it under the terms of the GNU General Public License as published by
22  * the Free Software Foundation, either version 3 of the License, or
23  * (at your option) any later version.
24  *
25  * This program is distributed in the hope that it will be useful,
26  * but WITHOUT ANY WARRANTY; without even the implied warranty of
27  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
28  * GNU General Public License for more details.
29  */
30
31 #define _GNU_SOURCE
32
33 #include <publib.h>
34
35 #include <stdio.h>
36 #include <stdint.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <assert.h>
40 #include <unistd.h>
41 #include <stdbool.h>
42 #include <inttypes.h>
43 #include <math.h>
44 #include <sys/types.h>
45 #include <sys/wait.h>
46 #include <sys/uio.h>
47 #include <sys/fcntl.h>
48
49 #include <glpk.h>
50
51 #ifndef VERSION
52 #define VERSION "(unknown-version)"
53 #endif
54
55 /*
56  * Algorithm.
57  *
58  * Each input match contributes, or does not contribute, to each
59  * output match; we do not need to consider multiple fragments
60  * relating to the same input/output pair this gives an n*m adjacency
61  * matrix (bitmap).  Given such an adjacency matrix, the problem of
62  * finding the best sizes for the fragments can be expressed as a
63  * linear programming problem.
64  *
65  * We search all possible adjacency matrices, and for each one we run
66  * GLPK's simplex solver.  We represent the adjacency matrix as an
67  * array of bitmaps: one word per input stick, with one bit per output
68  * stick.
69  *
70  * However, there are a couple of wrinkles:
71  *
72  * To best represent the problem as a standard LP problem, we separate
73  * out the size of each fragment into a common minimum size variable,
74  * plus a fragment-specific extra size variable.  This reduces the LP
75  * problem size at the cost of making the problem construction, and
76  * interpretation of the results, a bit fiddly.
77  *
78  * Many of the adjacency matrices are equivalent.  In particular,
79  * permutations of the columns, or of the rows, do not change the
80  * meaning.  It is only necessasry to consider any one permutation.
81  * We make use of this by considering only adjacency matrices whose
82  * bitmap array contains bitmap words whose numerical values are
83  * nondecreasing in array order.
84  *
85  * Once we have a solution, we also avoid considering any candidate
86  * which involves dividing one of the input sticks into so many
87  * fragment that the smallest fragment would necessarily be no bigger
88  * than our best solution.  That is, we reject candidates where any of
89  * the hamming weights of the adjacency bitmap words are too large.
90  *
91  * We further winnow the set of possible adjacency matrices, by
92  * ensuring the same bit is not set in too many entries of adjmatrix
93  * (ie, as above, only considering output sticks); and by ensuring
94  * that it is not set in too few: each output stick must consist
95  * of at least two fragments since the output sticks are longer than
96  * the input ones.
97  *
98  * And, we want to do the search in order of increasing maximum
99  * hamming weight.  This is because in practice optimal solutions tend
100  * to have low hamming weight, and having found a reasonable solution
101  * early allows us to eliminate a lot of candidates without doing the
102  * full LP.
103  */
104
105 typedef uint32_t AdjWord;
106 #define PRADJ "08"PRIx32
107
108 #define FOR_BITS(j,m) for (j=0, j##bit=1; j < (m); j++, j##bit<<=1)
109
110 static int n, m, maxhamweight;
111 static AdjWord *adjmatrix;
112 static AdjWord adjall;
113
114 static double best;
115 static glp_prob *best_prob;
116 static AdjWord *best_adjmatrix;
117
118 static int n_max_frags=INT_MAX, m_max_frags=INT_MAX;
119 static int *weight;
120
121 static unsigned printcounter;
122
123 static void iterate(void);
124 static void iterate_recurse(int i, AdjWord min);
125 static bool preconsider_ok(int nwords, bool doprint);
126 static bool maxhamweight_ok(void);
127 static void optimise(bool doprint);
128
129 static void progress_eol(void) {
130   fprintf(stderr,"        \r");
131   fflush(stderr);
132 }
133
134 static void set_best(double new_best) {
135   best = new_best;
136   /*
137    * When computing n_max_frags, we want to set a value that will skip
138    * anything that won't provide strictly better solutions.  So we
139    * want
140    *             frags <      n / best
141    *                        _          _
142    *   <=>       frags <   |  n / best  |
143    *                        _          _
144    *   <=>       frags <=  |  n / best  | - 1
145    *
146    * But best values from glpk are slightly approximate, so we
147    * subtract a fudge factor from our target.
148    */
149   double near_best = best * 0.98 - 0.02;
150   n_max_frags = ceil(n / near_best) - 1;
151   m_max_frags = ceil(m / near_best) - 1;
152 }
153
154 /*----- multicore support -----*/
155
156 /*
157  * Multicore protocol
158  *
159  * We fork into:
160  *   - master (parent)
161  *   - generator
162  *   - ncpu workers
163  *
164  * ipc facilities:
165  *   - one pipe ("work") from generator to workers
166  *   - ever-extending file ("bus") containing new "best" values
167  *   - one file for each worker giving maxhamweight and adjmatrix for best
168  *
169  * generator runs iterate_recurse to a certain depth and writes the
170  * candidates to a pipe
171  *
172  * workers read candidates from the pipe and resume iterate_recurse
173  * halfway through the recursion
174  *
175  * whenever a worker does a doprint, it checks the bus for new best
176  * value; actual best values are appended
177  *
178  * master waits for generator and all workers to finish and then
179  * runs optimise() for each worker's best, then prints
180  */ 
181
182 static int ncpus = 0, multicore_iteration_boundary = INT_MAX;
183
184 static int mc_bus, mc_work[2];
185 static off_t mc_bus_read;
186
187 typedef struct {
188   int w;
189   FILE *results;
190   pid_t pid;
191 } Worker;
192 static Worker *mc_us;
193 static bool mc_am_generator;
194
195 static void multicore_check_for_new_best(void);
196
197 #define MAX_NIOVS 4
198 static AdjWord mc_iter_min;
199 static int mc_niovs;
200 static size_t mc_iovlen;
201 static struct iovec mc_iov[MAX_NIOVS];
202
203 #define IOV0 (mc_niovs = mc_iovlen = 0)
204
205 #define IOV(obj, count) ({                              \
206     assert(mc_niovs < MAX_NIOVS);                       \
207     mc_iov[mc_niovs].iov_base = &(obj);                 \
208     mc_iov[mc_niovs].iov_len = sizeof(obj) * (count);   \
209     mc_iovlen += mc_iov[mc_niovs].iov_len;              \
210     mc_niovs++;                                         \
211   })
212
213 static void mc_rwvsetup_outer(void) {
214   IOV0;
215   IOV(maxhamweight, 1);
216   IOV(mc_iter_min, 1);
217   IOV(*adjmatrix, multicore_iteration_boundary);
218   IOV(*weight, m);
219 }
220
221 static void mc_rwvsetup_full(void) {
222   IOV0;
223   IOV(*adjmatrix, n);
224 }
225
226 static void vlprintf(const char *fmt, va_list al) {
227   vfprintf(stderr,fmt,al);
228   progress_eol();
229 }
230
231 static void LPRINTF(const char *fmt, ...) {
232   va_list al;
233   va_start(al,fmt);
234   vlprintf(fmt,al);
235   va_end(al);
236 }
237
238 static void mc_awaitpid(int wnum, pid_t pid) {
239   LPRINTF("master awaiting %2d [%ld]",wnum,(long)pid);
240   int status;
241   pid_t got = waitpid(pid, &status, 0);
242   assert(got == pid);
243   if (status) {
244     fprintf(stderr,"\nFAILED SUBPROC %2d [%ld] %d\n",
245             wnum, (long)pid, status);
246     exit(-1);
247   }
248 }
249
250 static void multicore_outer_iteration(int i, AdjWord min) {
251   static unsigned check_counter;
252
253   assert(i == multicore_iteration_boundary);
254   mc_iter_min = min;
255   mc_rwvsetup_outer();
256   ssize_t r = writev(mc_work[1], mc_iov, mc_niovs);
257   assert(r == mc_iovlen);
258   /* effectively, this writev arranges to transfers control
259    * to some worker's instance of iterate_recurse via mc_iterate_worker */
260
261   if (!(check_counter++ & 0xff))
262     multicore_check_for_new_best();
263 }
264
265 static void mc_iterate_worker(void) {
266   static time_t lastprint;
267
268   for (;;) {
269     mc_rwvsetup_outer();
270     ssize_t r = readv(mc_work[0], mc_iov, mc_niovs);
271     if (r == 0) break;
272     assert(r == mc_iovlen);
273     
274     bool ok = maxhamweight_ok();
275     if (!ok) continue;
276
277     time_t now = time(0);
278     bool doprint = now != lastprint;
279     lastprint = now;
280
281     ok = preconsider_ok(multicore_iteration_boundary, doprint);
282     if (doprint) progress_eol();
283     if (!ok) continue;
284
285     /* stop iterate_recurse from trying to run multicore_outer_iteration */
286     int mc_org_it_bound = multicore_iteration_boundary;
287     multicore_iteration_boundary = INT_MAX;
288     iterate_recurse(mc_org_it_bound, mc_iter_min);
289     multicore_iteration_boundary = mc_org_it_bound;
290   }
291   if (best_adjmatrix) {
292     LPRINTF("worker %2d reporting",mc_us->w);
293     adjmatrix = best_adjmatrix;
294     mc_rwvsetup_full();
295     ssize_t r = writev(fileno(mc_us->results), mc_iov, mc_niovs);
296     assert(r == mc_iovlen);
297   }
298   LPRINTF("worker %2d ending",mc_us->w);
299   exit(0);
300 }
301
302 static void multicore(void) {
303   Worker *mc_workers;
304   int w;
305   pid_t genpid;
306
307   multicore_iteration_boundary = n / 2;
308
309   FILE *busf = tmpfile();  assert(busf);
310   mc_bus = fileno(busf);
311   int r = fcntl(mc_bus, F_GETFL);  assert(r >= 0);
312   r |= O_APPEND;
313   r = fcntl(mc_bus, F_SETFL, r);  assert(r >= 0);
314
315   r = pipe(mc_work);  assert(!r);
316
317   mc_workers = xmalloc(sizeof(*mc_workers) * ncpus);
318   for (w=0; w<ncpus; w++) {
319     mc_workers[w].w = w;
320     mc_workers[w].results = tmpfile();  assert(mc_workers[w].results);
321     mc_workers[w].pid = fork();  assert(mc_workers[w].pid >= 0);
322     if (!mc_workers[w].pid) {
323       mc_us = &mc_workers[w];
324       close(mc_work[1]);
325       LPRINTF("worker %2d running", w);
326       mc_iterate_worker();
327       exit(0);
328     }
329   }
330
331   close(mc_work[0]);
332
333   genpid = fork();  assert(genpid >= 0);
334   if (!genpid) {
335     mc_am_generator = 1;
336     LPRINTF("generator running");
337     iterate();
338     exit(0);
339   }
340
341   close(mc_work[1]);
342   mc_awaitpid(-1, genpid);
343   for (w=0; w<ncpus; w++)
344     mc_awaitpid(w, mc_workers[w].pid);
345
346   for (w=0; w<ncpus; w++) {
347     mc_rwvsetup_full();
348     LPRINTF("reading report from %2d",w);
349     ssize_t sr = preadv(fileno(mc_workers[w].results), mc_iov, mc_niovs, 0);
350     if (!sr) continue;
351     LPRINTF("got report from %2d",w);
352     maxhamweight = 0;
353     optimise(1);
354   }
355 }
356
357 static void multicore_check_for_new_best(void) {
358   if (!(mc_us || mc_am_generator))
359     return;
360
361   for (;;) {
362     double msg;
363     ssize_t got = pread(mc_bus, &msg, sizeof(msg), mc_bus_read);
364     if (!got) break;
365     assert(got == sizeof(msg));
366     if (msg > best)
367       set_best(msg);
368     mc_bus_read += sizeof(msg);
369   }
370 }
371
372 static void multicore_found_new_best(void) {
373   if (!mc_us)
374     return;
375
376   if (mc_us /* might be master */) fprintf(stderr,"    w%-2d ",mc_us->w);
377   ssize_t wrote = write(mc_bus, &best, sizeof(best));
378   assert(wrote == sizeof(best));
379 }
380
381 /*----- end of multicore support -----*/
382
383 static AdjWord *xalloc_adjmatrix(void) {
384   return xmalloc(sizeof(*adjmatrix)*n);
385 }
386
387 static void prep(void) {
388   adjall = ~((~(AdjWord)0) << m);
389   adjmatrix = xalloc_adjmatrix();
390   glp_term_out(GLP_OFF);
391   setlinebuf(stderr);
392   weight = calloc(sizeof(*weight), m);  assert(weight);
393 }
394
395 #if 0
396 static AdjWord one_adj_bit(int bitnum) {
397   return (AdjWord)1 << bitnum;
398 }
399 #endif
400
401 static int count_set_adj_bits(AdjWord w) {
402   int j, total = 0;
403   AdjWord jbit;
404   FOR_BITS(j,m)
405     total += !!(w & jbit);
406   return total;
407 }
408
409 #define PRINTF(...) if (!doprint) ; else fprintf(stderr, __VA_ARGS__)
410
411 static int totalfrags;
412
413 static bool maxhamweight_ok(void) {
414   return maxhamweight <= m_max_frags;
415 }
416
417 static bool preconsider_ok(int nwords, bool doprint) {
418   int i;
419
420   PRINTF("%2d ", maxhamweight);
421
422   bool had_max = 0;
423   for (i=0, totalfrags=0; i<nwords; i++) {
424     int frags = count_set_adj_bits(adjmatrix[i]);
425     PRINTF("%"PRADJ" ", adjmatrix[i]);
426     if (frags > m_max_frags) {
427       PRINTF(" too fine");
428       goto out;
429     }
430     had_max += (frags >= maxhamweight);
431     totalfrags += frags;
432   }
433   if (!had_max) {
434     /* Skip this candidate as its max hamming weight is lower than
435      * we're currently looking for (which means we must have done it
436      * already).  (The recursive iteration ensures that none of the
437      * words have more than the max hamming weight.) */
438     PRINTF(" nomaxham");
439     goto out;
440   }
441   return 1;
442
443  out:
444   return 0;
445 }
446
447 static void optimise(bool doprint) {
448   /* Consider the best answer (if any) for a given adjacency matrix */
449   glp_prob *prob = 0;
450   int i, j;
451   AdjWord jbit;
452
453   /*
454    * Up to a certain point, optimise() can be restarted.  We use this
455    * to go back and print the debugging output if it turns out that we
456    * have an interesting case.  The HAVE_PRINTED macro does this: its
457    * semantics are to go back in time and make sure that we have
458    * printed the description of the search case.
459    */
460 #define HAVE_PRINTED ({                                         \
461       if (!doprint) { doprint = 1; goto retry_with_print; }     \
462     })
463  retry_with_print:
464   if (prob) {
465     glp_delete_prob(prob);
466     prob = 0;
467   }
468
469   bool ok = preconsider_ok(n, doprint);
470   if (!ok)
471     goto out;
472
473   /*
474    * We formulate our problem as an LP problem as follows.
475    * In this file "n" and "m" are the matchstick numbers.
476    *
477    * Each set bit in the adjacency matrix corresponds to taking a
478    * fragment from old match i and making it part of new match j.
479    *
480    * The structural variables (columns) are:
481    *   x_minimum        minimum size of any fragment (bounded below by 0)
482    *   x_morefrag_i_j   the amount by which the size of the fragment
483    *                     i,j exceeds the minimum size (bounded below by 0)
484    *
485    * The auxiliary variables (rows) are:
486    *   x_total_i       total length for each input match (fixed variable)
487    *   x_total_j       total length for each output match (fixed variable)
488    *
489    * The objective function is simply
490    *   maximise x_minimum
491    *
492    * We use X_ and Y_ to refer to GLPK's (1-based) column and row indices.
493    * ME_ refers to entries in the list of constraint matrix elements
494    * which we build up as we go.
495    */
496
497   prob = glp_create_prob();
498
499   int Y_totals_i = glp_add_rows(prob, n);
500   int Y_totals_j = glp_add_rows(prob, m);
501   int X_minimum = glp_add_cols(prob, 1);
502
503   {
504   int next_matrix_entry = 1; /* wtf GLPK! */
505   int matrix_entries_size = next_matrix_entry + n + m + totalfrags*2;
506   double matrix_entries[matrix_entries_size];
507   int matrix_entries_XY[2][matrix_entries_size];
508
509 #define ADD_MATRIX_ENTRY(Y,X) ({                        \
510       assert(next_matrix_entry < matrix_entries_size);  \
511       matrix_entries_XY[0][next_matrix_entry] = (X);    \
512       matrix_entries_XY[1][next_matrix_entry] = (Y);    \
513       matrix_entries[next_matrix_entry] = 0;            \
514       next_matrix_entry++;                              \
515     })
516
517   int ME_totals_i__minimum = next_matrix_entry;
518   for (i=0; i<n; i++) ADD_MATRIX_ENTRY(Y_totals_i+i, X_minimum);
519
520   int ME_totals_j__minimum = next_matrix_entry;
521   for (j=0; j<m; j++) ADD_MATRIX_ENTRY(Y_totals_j+j, X_minimum);
522
523   /* \forall_i x_total_i = m */
524   /* \forall_i x_total_j = n */
525   for (i=0; i<n; i++) glp_set_row_bnds(prob, Y_totals_i+i, GLP_FX, m,m);
526   for (j=0; j<m; j++) glp_set_row_bnds(prob, Y_totals_j+j, GLP_FX, n,n);
527
528   /* x_minimum >= 0 */
529   glp_set_col_bnds(prob, X_minimum, GLP_LO, 0, 0);
530   glp_set_col_name(prob, X_minimum, "minimum");
531
532   /* objective is maximising x_minimum */
533   glp_set_obj_dir(prob, GLP_MAX);
534   glp_set_obj_coef(prob, X_minimum, 1);
535
536   for (i=0; i<n; i++) {
537     FOR_BITS(j,m) {
538       if (!(adjmatrix[i] & jbit))
539         continue;
540       /* x_total_i += x_minimum */
541       /* x_total_j += x_minimum */
542       matrix_entries[ ME_totals_i__minimum + i ] ++;
543       matrix_entries[ ME_totals_j__minimum + j ] ++;
544
545       /* x_morefrag_i_j >= 0 */
546       int X_morefrag_i_j = glp_add_cols(prob, 1);
547       glp_set_col_bnds(prob, X_morefrag_i_j, GLP_LO, 0, 0);
548       if (doprint) {
549         char buf[255];
550         snprintf(buf,sizeof(buf),"mf %d,%d",i,j);
551         glp_set_col_name(prob, X_morefrag_i_j, buf);
552       }
553
554       /* x_total_i += x_morefrag_i_j */
555       /* x_total_j += x_morefrag_i_j */
556       int ME_totals_i__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_i+i, X_morefrag_i_j);
557       int ME_totals_j__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_j+j, X_morefrag_i_j);
558       matrix_entries[ME_totals_i__mf_i_j] = 1;
559       matrix_entries[ME_totals_j__mf_i_j] = 1;
560     }
561   }
562
563   assert(next_matrix_entry == matrix_entries_size);
564
565   glp_load_matrix(prob, matrix_entries_size-1,
566                   matrix_entries_XY[1], matrix_entries_XY[0],
567                   matrix_entries);
568
569   int r = glp_simplex(prob, NULL);
570   PRINTF(" glp=%d", r);
571
572 #define OKERR(e) \
573   case e: PRINTF(" " #e ); goto out;
574 #define BADERR(e) \
575   case e: HAVE_PRINTED; printf(" " #e " CRASHING\n"); exit(-1);
576 #define DEFAULT \
577   default: HAVE_PRINTED; printf(" ! CRASHING\n"); exit(-1);
578
579   switch (r) {
580   OKERR(GLP_ESING);
581   OKERR(GLP_ECOND);
582   OKERR(GLP_EBOUND);
583   OKERR(GLP_EFAIL);
584   OKERR(GLP_ENOPFS);
585   OKERR(GLP_ENODFS);
586   BADERR(GLP_EBADB);
587   BADERR(GLP_EOBJLL);
588   BADERR(GLP_EOBJUL);
589   BADERR(GLP_EITLIM);
590   BADERR(GLP_ETMLIM);
591   BADERR(GLP_EINSTAB);
592   BADERR(GLP_ENOCVG);
593   case 0: break;
594   DEFAULT;
595   }
596
597   r = glp_get_status(prob);
598   PRINTF(" status=%d", r);
599
600   switch (r) {
601   OKERR(GLP_NOFEAS);
602   OKERR(GLP_UNDEF);
603   BADERR(GLP_FEAS);
604   BADERR(GLP_INFEAS);
605   BADERR(GLP_UNBND);
606   case GLP_OPT: break;
607   DEFAULT;
608   }
609
610   double got = glp_get_obj_val(prob);
611   PRINTF("  %g", got);
612   if (got <= best)
613     goto out;
614
615   HAVE_PRINTED;
616
617   set_best(got);
618   multicore_found_new_best();
619
620   if (best_prob) glp_delete_prob(best_prob);
621   best_prob = prob;
622
623   free(best_adjmatrix);
624   best_adjmatrix = xalloc_adjmatrix();
625   memcpy(best_adjmatrix, adjmatrix, sizeof(*adjmatrix)*n);
626
627   PRINTF(" BEST        \n");
628   return;
629
630   }
631  out:
632   if (prob)
633     glp_delete_prob(prob);
634   if (doprint) progress_eol();
635   if (doprint) multicore_check_for_new_best();
636 }
637
638 static void iterate_recurse(int i, AdjWord min) {
639   int j;
640   AdjWord jbit;
641
642   if (i >= n) {
643     for (j=0; j<m; j++)
644       if (weight[j] < 2)
645         return;
646
647     printcounter++;
648     optimise(!(printcounter & 0xfff));
649     return;
650   }
651   if (i >= multicore_iteration_boundary) {
652     multicore_outer_iteration(i, min);
653     return;
654   }
655   for (adjmatrix[i] = min;
656        ;
657        adjmatrix[i]++) {
658     if (count_set_adj_bits(adjmatrix[i]) > maxhamweight)
659       goto again;
660     if (i == 0 && (adjmatrix[i] & (1+adjmatrix[i])))
661       goto again;
662
663     FOR_BITS(j,m)
664       if (adjmatrix[i] & jbit)
665         weight[j]++;
666     for (int j = 0; j < m; j++)
667       if (weight[j] >= n_max_frags)
668         goto takeout;
669
670     iterate_recurse(i+1, adjmatrix[i]);
671
672   takeout:
673     FOR_BITS(j,m)
674       if (adjmatrix[i] & jbit)
675         weight[j]--;
676
677   again:
678     if (adjmatrix[i] == adjall)
679       return;
680   }
681 }
682
683 static void iterate(void) {
684   for (maxhamweight=1; maxhamweight<=m; maxhamweight++) {
685     if (!maxhamweight_ok())
686       continue;
687
688     iterate_recurse(0, 1);
689   }
690 }
691
692 static void report(void) {
693   fprintf(stderr, "\n");
694   if (best_adjmatrix) {
695     int i;
696     fprintf(stderr,"  ");
697     for (i=0; i<n; i++) fprintf(stderr, " %"PRADJ, best_adjmatrix[i]);
698   }
699   fprintf(stderr, " best=%-12.8f nf<=%d mf<=%d\n",
700           best, n_max_frags, m_max_frags);
701   printf("%d into %d: ", n, m);
702   if (best_prob) {
703     double min = glp_get_obj_val(best_prob);
704     double a[n][m];
705     int i, j, cols;
706     for (i = 0; i < n; i++)
707       for (j = 0; j < m; j++)
708         a[i][j] = 0;
709     cols = glp_get_num_cols(best_prob);
710     for (i = 1; i <= cols; i++) {
711       int x, y;
712       if (2 != sscanf(glp_get_col_name(best_prob, i), "mf %d,%d", &x, &y))
713         continue;
714       a[x][y] = min + glp_get_col_prim(best_prob, i);
715     }
716     printf("min fragment %g   [%s]\n", min, VERSION);
717     for (i = 0; i < n; i++) {
718       for (j = 0; j < m; j++) {
719         if (a[i][j])
720           printf(" %9.3f", a[i][j]);
721         else
722           printf("          ");
723       }
724       printf("\n");
725     }
726   } else {
727     printf(" none better than %9.3f    [%s]\n", best, VERSION);
728   }
729   if (ferror(stdout) || fclose(stdout)) { perror("stdout"); exit(-1); }
730 }
731  
732 int main(int argc, char **argv) {
733   int opt;
734   while ((opt = getopt(argc,argv,"j:b:")) >= 0) {
735     switch (opt) {
736     case 'j': ncpus = atoi(optarg); break;
737     case 'b': set_best(atof(optarg)); break;
738     case '+': assert(!"bad option");
739     default: abort();
740     }
741   }
742   argc -= optind-1;
743   argv += optind-1;
744   assert(argc==3);
745   n = atoi(argv[1]);
746   m = atoi(argv[2]);
747   assert(n > m);
748
749   prep();
750
751   if (ncpus) multicore();
752   else iterate();
753
754   report();
755   return 0;
756 }