chiark / gitweb /
report something to stdout even if no answer
[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, m_max_frags;
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   for (;;) {
267     mc_rwvsetup_outer();
268     ssize_t r = readv(mc_work[0], mc_iov, mc_niovs);
269     if (r == 0) break;
270     assert(r == mc_iovlen);
271     
272     bool ok = maxhamweight_ok();
273     if (!ok) continue;
274
275     ok = preconsider_ok(multicore_iteration_boundary, 1);
276     progress_eol();
277     if (!ok) continue;
278
279     /* stop iterate_recurse from trying to run multicore_outer_iteration */
280     int mc_org_it_bound = multicore_iteration_boundary;
281     multicore_iteration_boundary = INT_MAX;
282     iterate_recurse(mc_org_it_bound, mc_iter_min);
283     multicore_iteration_boundary = mc_org_it_bound;
284   }
285   if (best_adjmatrix) {
286     LPRINTF("worker %2d reporting",mc_us->w);
287     adjmatrix = best_adjmatrix;
288     mc_rwvsetup_full();
289     ssize_t r = writev(fileno(mc_us->results), mc_iov, mc_niovs);
290     assert(r == mc_iovlen);
291   }
292   LPRINTF("worker %2d ending",mc_us->w);
293   exit(0);
294 }
295
296 static void multicore(void) {
297   Worker *mc_workers;
298   int w;
299   pid_t genpid;
300
301   multicore_iteration_boundary = n / 2;
302
303   FILE *busf = tmpfile();  assert(busf);
304   mc_bus = fileno(busf);
305   int r = fcntl(mc_bus, F_GETFL);  assert(r >= 0);
306   r |= O_APPEND;
307   r = fcntl(mc_bus, F_SETFL, r);  assert(r >= 0);
308
309   r = pipe(mc_work);  assert(!r);
310
311   mc_workers = xmalloc(sizeof(*mc_workers) * ncpus);
312   for (w=0; w<ncpus; w++) {
313     mc_workers[w].w = w;
314     mc_workers[w].results = tmpfile();  assert(mc_workers[w].results);
315     mc_workers[w].pid = fork();  assert(mc_workers[w].pid >= 0);
316     if (!mc_workers[w].pid) {
317       mc_us = &mc_workers[w];
318       close(mc_work[1]);
319       LPRINTF("worker %2d running", w);
320       mc_iterate_worker();
321       exit(0);
322     }
323   }
324
325   close(mc_work[0]);
326
327   genpid = fork();  assert(genpid >= 0);
328   if (!genpid) {
329     mc_am_generator = 1;
330     LPRINTF("generator running");
331     iterate();
332     exit(0);
333   }
334
335   close(mc_work[1]);
336   mc_awaitpid(-1, genpid);
337   for (w=0; w<ncpus; w++)
338     mc_awaitpid(w, mc_workers[w].pid);
339
340   for (w=0; w<ncpus; w++) {
341     mc_rwvsetup_full();
342     LPRINTF("reading report from %2d",w);
343     ssize_t sr = preadv(fileno(mc_workers[w].results), mc_iov, mc_niovs, 0);
344     if (!sr) continue;
345     LPRINTF("got report from %2d",w);
346     maxhamweight = 0;
347     optimise(1);
348   }
349 }
350
351 static void multicore_check_for_new_best(void) {
352   if (!(mc_us || mc_am_generator))
353     return;
354
355   for (;;) {
356     double msg;
357     ssize_t got = pread(mc_bus, &msg, sizeof(msg), mc_bus_read);
358     if (!got) break;
359     assert(got == sizeof(msg));
360     if (msg > best)
361       set_best(msg);
362     mc_bus_read += sizeof(msg);
363   }
364 }
365
366 static void multicore_found_new_best(void) {
367   if (!mc_us)
368     return;
369
370   if (mc_us /* might be master */) fprintf(stderr,"    w%-2d ",mc_us->w);
371   ssize_t wrote = write(mc_bus, &best, sizeof(best));
372   assert(wrote == sizeof(best));
373 }
374
375 /*----- end of multicore support -----*/
376
377 static AdjWord *xalloc_adjmatrix(void) {
378   return xmalloc(sizeof(*adjmatrix)*n);
379 }
380
381 static void prep(void) {
382   adjall = ~((~(AdjWord)0) << m);
383   adjmatrix = xalloc_adjmatrix();
384   glp_term_out(GLP_OFF);
385   setlinebuf(stderr);
386   weight = calloc(sizeof(*weight), m);  assert(weight);
387   n_max_frags = INT_MAX;
388   m_max_frags = INT_MAX;
389 }
390
391 #if 0
392 static AdjWord one_adj_bit(int bitnum) {
393   return (AdjWord)1 << bitnum;
394 }
395 #endif
396
397 static int count_set_adj_bits(AdjWord w) {
398   int j, total = 0;
399   AdjWord jbit;
400   FOR_BITS(j,m)
401     total += !!(w & jbit);
402   return total;
403 }
404
405 #define PRINTF(...) if (!doprint) ; else fprintf(stderr, __VA_ARGS__)
406
407 static int totalfrags;
408
409 static bool maxhamweight_ok(void) {
410   return maxhamweight <= m_max_frags;
411 }
412
413 static bool preconsider_ok(int nwords, bool doprint) {
414   int i;
415
416   PRINTF("%2d ", maxhamweight);
417
418   bool had_max = 0;
419   for (i=0, totalfrags=0; i<nwords; i++) {
420     int frags = count_set_adj_bits(adjmatrix[i]);
421     PRINTF("%"PRADJ" ", adjmatrix[i]);
422     if (frags > m_max_frags) {
423       PRINTF(" too fine");
424       goto out;
425     }
426     had_max += (frags >= maxhamweight);
427     totalfrags += frags;
428   }
429   if (!had_max) {
430     /* Skip this candidate as its max hamming weight is lower than
431      * we're currently looking for (which means we must have done it
432      * already).  (The recursive iteration ensures that none of the
433      * words have more than the max hamming weight.) */
434     PRINTF(" nomaxham");
435     goto out;
436   }
437   return 1;
438
439  out:
440   return 0;
441 }
442
443 static void optimise(bool doprint) {
444   /* Consider the best answer (if any) for a given adjacency matrix */
445   glp_prob *prob = 0;
446   int i, j;
447   AdjWord jbit;
448
449   /*
450    * Up to a certain point, optimise() can be restarted.  We use this
451    * to go back and print the debugging output if it turns out that we
452    * have an interesting case.  The HAVE_PRINTED macro does this: its
453    * semantics are to go back in time and make sure that we have
454    * printed the description of the search case.
455    */
456 #define HAVE_PRINTED ({                                         \
457       if (!doprint) { doprint = 1; goto retry_with_print; }     \
458     })
459  retry_with_print:
460   if (prob) {
461     glp_delete_prob(prob);
462     prob = 0;
463   }
464
465   bool ok = preconsider_ok(n, doprint);
466   if (!ok)
467     goto out;
468
469   /*
470    * We formulate our problem as an LP problem as follows.
471    * In this file "n" and "m" are the matchstick numbers.
472    *
473    * Each set bit in the adjacency matrix corresponds to taking a
474    * fragment from old match i and making it part of new match j.
475    *
476    * The structural variables (columns) are:
477    *   x_minimum        minimum size of any fragment (bounded below by 0)
478    *   x_morefrag_i_j   the amount by which the size of the fragment
479    *                     i,j exceeds the minimum size (bounded below by 0)
480    *
481    * The auxiliary variables (rows) are:
482    *   x_total_i       total length for each input match (fixed variable)
483    *   x_total_j       total length for each output match (fixed variable)
484    *
485    * The objective function is simply
486    *   maximise x_minimum
487    *
488    * We use X_ and Y_ to refer to GLPK's (1-based) column and row indices.
489    * ME_ refers to entries in the list of constraint matrix elements
490    * which we build up as we go.
491    */
492
493   prob = glp_create_prob();
494
495   int Y_totals_i = glp_add_rows(prob, n);
496   int Y_totals_j = glp_add_rows(prob, m);
497   int X_minimum = glp_add_cols(prob, 1);
498
499   {
500   int next_matrix_entry = 1; /* wtf GLPK! */
501   int matrix_entries_size = next_matrix_entry + n + m + totalfrags*2;
502   double matrix_entries[matrix_entries_size];
503   int matrix_entries_XY[2][matrix_entries_size];
504
505 #define ADD_MATRIX_ENTRY(Y,X) ({                        \
506       assert(next_matrix_entry < matrix_entries_size);  \
507       matrix_entries_XY[0][next_matrix_entry] = (X);    \
508       matrix_entries_XY[1][next_matrix_entry] = (Y);    \
509       matrix_entries[next_matrix_entry] = 0;            \
510       next_matrix_entry++;                              \
511     })
512
513   int ME_totals_i__minimum = next_matrix_entry;
514   for (i=0; i<n; i++) ADD_MATRIX_ENTRY(Y_totals_i+i, X_minimum);
515
516   int ME_totals_j__minimum = next_matrix_entry;
517   for (j=0; j<m; j++) ADD_MATRIX_ENTRY(Y_totals_j+j, X_minimum);
518
519   /* \forall_i x_total_i = m */
520   /* \forall_i x_total_j = n */
521   for (i=0; i<n; i++) glp_set_row_bnds(prob, Y_totals_i+i, GLP_FX, m,m);
522   for (j=0; j<m; j++) glp_set_row_bnds(prob, Y_totals_j+j, GLP_FX, n,n);
523
524   /* x_minimum >= 0 */
525   glp_set_col_bnds(prob, X_minimum, GLP_LO, 0, 0);
526   glp_set_col_name(prob, X_minimum, "minimum");
527
528   /* objective is maximising x_minimum */
529   glp_set_obj_dir(prob, GLP_MAX);
530   glp_set_obj_coef(prob, X_minimum, 1);
531
532   for (i=0; i<n; i++) {
533     FOR_BITS(j,m) {
534       if (!(adjmatrix[i] & jbit))
535         continue;
536       /* x_total_i += x_minimum */
537       /* x_total_j += x_minimum */
538       matrix_entries[ ME_totals_i__minimum + i ] ++;
539       matrix_entries[ ME_totals_j__minimum + j ] ++;
540
541       /* x_morefrag_i_j >= 0 */
542       int X_morefrag_i_j = glp_add_cols(prob, 1);
543       glp_set_col_bnds(prob, X_morefrag_i_j, GLP_LO, 0, 0);
544       if (doprint) {
545         char buf[255];
546         snprintf(buf,sizeof(buf),"mf %d,%d",i,j);
547         glp_set_col_name(prob, X_morefrag_i_j, buf);
548       }
549
550       /* x_total_i += x_morefrag_i_j */
551       /* x_total_j += x_morefrag_i_j */
552       int ME_totals_i__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_i+i, X_morefrag_i_j);
553       int ME_totals_j__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_j+j, X_morefrag_i_j);
554       matrix_entries[ME_totals_i__mf_i_j] = 1;
555       matrix_entries[ME_totals_j__mf_i_j] = 1;
556     }
557   }
558
559   assert(next_matrix_entry == matrix_entries_size);
560
561   glp_load_matrix(prob, matrix_entries_size-1,
562                   matrix_entries_XY[1], matrix_entries_XY[0],
563                   matrix_entries);
564
565   int r = glp_simplex(prob, NULL);
566   PRINTF(" glp=%d", r);
567
568 #define OKERR(e) \
569   case e: PRINTF(" " #e ); goto out;
570 #define BADERR(e) \
571   case e: HAVE_PRINTED; printf(" " #e " CRASHING\n"); exit(-1);
572 #define DEFAULT \
573   default: HAVE_PRINTED; printf(" ! CRASHING\n"); exit(-1);
574
575   switch (r) {
576   OKERR(GLP_ESING);
577   OKERR(GLP_ECOND);
578   OKERR(GLP_EBOUND);
579   OKERR(GLP_EFAIL);
580   OKERR(GLP_ENOPFS);
581   OKERR(GLP_ENODFS);
582   BADERR(GLP_EBADB);
583   BADERR(GLP_EOBJLL);
584   BADERR(GLP_EOBJUL);
585   BADERR(GLP_EITLIM);
586   BADERR(GLP_ETMLIM);
587   BADERR(GLP_EINSTAB);
588   BADERR(GLP_ENOCVG);
589   case 0: break;
590   DEFAULT;
591   }
592
593   r = glp_get_status(prob);
594   PRINTF(" status=%d", r);
595
596   switch (r) {
597   OKERR(GLP_NOFEAS);
598   OKERR(GLP_UNDEF);
599   BADERR(GLP_FEAS);
600   BADERR(GLP_INFEAS);
601   BADERR(GLP_UNBND);
602   case GLP_OPT: break;
603   DEFAULT;
604   }
605
606   double got = glp_get_obj_val(prob);
607   PRINTF("  %g", got);
608   if (got <= best)
609     goto out;
610
611   HAVE_PRINTED;
612
613   set_best(got);
614   multicore_found_new_best();
615
616   if (best_prob) glp_delete_prob(best_prob);
617   best_prob = prob;
618
619   free(best_adjmatrix);
620   best_adjmatrix = xalloc_adjmatrix();
621   memcpy(best_adjmatrix, adjmatrix, sizeof(*adjmatrix)*n);
622
623   PRINTF(" BEST        \n");
624   return;
625
626   }
627  out:
628   if (prob)
629     glp_delete_prob(prob);
630   if (doprint) progress_eol();
631   if (doprint) multicore_check_for_new_best();
632 }
633
634 static void iterate_recurse(int i, AdjWord min) {
635   int j;
636   AdjWord jbit;
637
638   if (i >= n) {
639     for (j=0; j<m; j++)
640       if (weight[j] < 2)
641         return;
642
643     printcounter++;
644     optimise(!(printcounter & 0xfff));
645     return;
646   }
647   if (i >= multicore_iteration_boundary) {
648     multicore_outer_iteration(i, min);
649     return;
650   }
651   for (adjmatrix[i] = min;
652        ;
653        adjmatrix[i]++) {
654     if (count_set_adj_bits(adjmatrix[i]) > maxhamweight)
655       goto again;
656     if (i == 0 && (adjmatrix[i] & (1+adjmatrix[i])))
657       goto again;
658
659     FOR_BITS(j,m)
660       if (adjmatrix[i] & jbit)
661         weight[j]++;
662     for (int j = 0; j < m; j++)
663       if (weight[j] >= n_max_frags)
664         goto takeout;
665
666     iterate_recurse(i+1, adjmatrix[i]);
667
668   takeout:
669     FOR_BITS(j,m)
670       if (adjmatrix[i] & jbit)
671         weight[j]--;
672
673   again:
674     if (adjmatrix[i] == adjall)
675       return;
676   }
677 }
678
679 static void iterate(void) {
680   for (maxhamweight=1; maxhamweight<=m; maxhamweight++) {
681     if (!maxhamweight_ok())
682       continue;
683
684     iterate_recurse(0, 1);
685   }
686 }
687
688 static void report(void) {
689   fprintf(stderr, "\n");
690   if (best_adjmatrix) {
691     int i;
692     fprintf(stderr,"  ");
693     for (i=0; i<n; i++) fprintf(stderr, " %"PRADJ, best_adjmatrix[i]);
694   }
695   fprintf(stderr, " best=%-12.8f nf<=%d mf<=%d\n",
696           best, n_max_frags, m_max_frags);
697   printf("%d into %d: ", n, m);
698   if (best_prob) {
699     double min = glp_get_obj_val(best_prob);
700     double a[n][m];
701     int i, j, cols;
702     for (i = 0; i < n; i++)
703       for (j = 0; j < m; j++)
704         a[i][j] = 0;
705     cols = glp_get_num_cols(best_prob);
706     for (i = 1; i <= cols; i++) {
707       int x, y;
708       if (2 != sscanf(glp_get_col_name(best_prob, i), "mf %d,%d", &x, &y))
709         continue;
710       a[x][y] = min + glp_get_col_prim(best_prob, i);
711     }
712     printf("min fragment %g", min);
713     for (i = 0; i < n; i++) {
714       for (j = 0; j < m; j++) {
715         if (a[i][j])
716           printf(" %9.3f", a[i][j]);
717         else
718           printf("          ");
719       }
720       printf("\n");
721     }
722   } else {
723     printf(" none better than %9.3f ", best);
724   }
725   printf("   [%s]\n", VERSION);
726   if (ferror(stdout) || fclose(stdout)) { perror("stdout"); exit(-1); }
727 }
728  
729 int main(int argc, char **argv) {
730   int opt;
731   while ((opt = getopt(argc,argv,"j:")) >= 0) {
732     switch (opt) {
733     case 'j': ncpus = atoi(optarg); break;
734     case 'b': set_best(atof(optarg)); break;
735     case '+': assert(!"bad option");
736     default: abort();
737     }
738   }
739   argc -= optind-1;
740   argv += optind-1;
741   assert(argc==3);
742   n = atoi(argv[1]);
743   m = atoi(argv[2]);
744   assert(n > m);
745
746   prep();
747
748   if (ncpus) multicore();
749   else iterate();
750
751   report();
752   return 0;
753 }