chiark / gitweb /
0967442c5a425f5d7c414c39be6b971b571753fc
[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  */
15
16 /*
17  * matchsticks/main.c  Copyright 2014 Ian Jackson
18  *
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.
23  *
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.
28  */
29
30 #define _GNU_SOURCE
31
32 #include <publib.h>
33
34 #include <stdio.h>
35 #include <stdint.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <assert.h>
39 #include <unistd.h>
40 #include <stdbool.h>
41 #include <inttypes.h>
42 #include <math.h>
43 #include <sys/types.h>
44 #include <sys/wait.h>
45 #include <sys/uio.h>
46 #include <sys/fcntl.h>
47
48 #include <glpk.h>
49
50 #ifndef VERSION
51 #define VERSION "(unknown-version)"
52 #endif
53
54 /*
55  * Algorithm.
56  *
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.
63  *
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
67  * stick.
68  *
69  * However, there are a couple of wrinkles:
70  *
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.
76  *
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.
83  *
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.
89  *
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
95  * the input ones.
96  *
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
101  * full LP.
102  */
103
104 typedef uint32_t AdjWord;
105 #define PRADJ "08"PRIx32
106
107 #define FOR_BITS(j,m) for (j=0, j##bit=1; j < (m); j++, j##bit<<=1)
108
109 static int n, m, maxhamweight;
110 static AdjWord *adjmatrix;
111 static AdjWord adjall;
112
113 static double best;
114 static glp_prob *best_prob;
115 static AdjWord *best_adjmatrix;
116
117 static int n_max_frags, m_max_frags;
118 static int *weight;
119
120 static unsigned printcounter;
121
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);
127
128 static void progress_eol(void) {
129   fprintf(stderr,"        \r");
130   fflush(stderr);
131 }
132
133 static void set_best(double new_best) {
134   best = new_best;
135   /*
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
138    * want
139    *             frags <      n / best
140    *                        _          _
141    *   <=>       frags <   |  n / best  |
142    *                        _          _
143    *   <=>       frags <=  |  n / best  | - 1
144    *
145    * But best values from glpk are slightly approximate, so we
146    * subtract a fudge factor from our target.
147    */
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;
151 }
152
153 /*----- multicore support -----*/
154
155 /*
156  * Multicore protocol
157  *
158  * We fork into:
159  *   - master (parent)
160  *   - generator
161  *   - ncpu workers
162  *
163  * ipc facilities:
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
167  *
168  * generator runs iterate_recurse to a certain depth and writes the
169  * candidates to a pipe
170  *
171  * workers read candidates from the pipe and resume iterate_recurse
172  * halfway through the recursion
173  *
174  * whenever a worker does a doprint, it checks the bus for new best
175  * value; actual best values are appended
176  *
177  * master waits for generator and all workers to finish and then
178  * runs optimise() for each worker's best, then prints
179  */ 
180
181 static int ncpus = 0, multicore_iteration_boundary = INT_MAX;
182
183 static int mc_bus, mc_work[2];
184 static off_t mc_bus_read;
185
186 typedef struct {
187   int w;
188   FILE *results;
189   pid_t pid;
190 } Worker;
191 static Worker *mc_us;
192 static bool mc_am_generator;
193
194 static void multicore_check_for_new_best(void);
195
196 #define MAX_NIOVS 4
197 static AdjWord mc_iter_min;
198 static int mc_niovs;
199 static size_t mc_iovlen;
200 static struct iovec mc_iov[MAX_NIOVS];
201
202 #define IOV0 (mc_niovs = mc_iovlen = 0)
203
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;              \
209     mc_niovs++;                                         \
210   })
211
212 static void mc_rwvsetup_outer(void) {
213   IOV0;
214   IOV(maxhamweight, 1);
215   IOV(mc_iter_min, 1);
216   IOV(*adjmatrix, multicore_iteration_boundary);
217   IOV(*weight, m);
218 }
219
220 static void mc_rwvsetup_full(void) {
221   IOV0;
222   IOV(*adjmatrix, n);
223 }
224
225 static void vlprintf(const char *fmt, va_list al) {
226   vfprintf(stderr,fmt,al);
227   progress_eol();
228 }
229
230 static void LPRINTF(const char *fmt, ...) {
231   va_list al;
232   va_start(al,fmt);
233   vlprintf(fmt,al);
234   va_end(al);
235 }
236
237 static void mc_awaitpid(int wnum, pid_t pid) {
238   LPRINTF("master awaiting %2d [%ld]",wnum,(long)pid);
239   int status;
240   pid_t got = waitpid(pid, &status, 0);
241   assert(got == pid);
242   if (status) {
243     fprintf(stderr,"\nFAILED SUBPROC %2d [%ld] %d\n",
244             wnum, (long)pid, status);
245     exit(-1);
246   }
247 }
248
249 static void multicore_outer_iteration(int i, AdjWord min) {
250   static unsigned check_counter;
251
252   assert(i == multicore_iteration_boundary);
253   mc_iter_min = min;
254   mc_rwvsetup_outer();
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 */
259
260   if (!(check_counter++ & 0xff))
261     multicore_check_for_new_best();
262 }
263
264 static void mc_iterate_worker(void) {
265   for (;;) {
266     mc_rwvsetup_outer();
267     ssize_t r = readv(mc_work[0], mc_iov, mc_niovs);
268     if (r == 0) break;
269     assert(r == mc_iovlen);
270     
271     bool ok = maxhamweight_ok();
272     if (!ok) continue;
273
274     ok = preconsider_ok(multicore_iteration_boundary, 1);
275     progress_eol();
276     if (!ok) continue;
277
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;
283   }
284   if (best_adjmatrix) {
285     LPRINTF("worker %2d reporting",mc_us->w);
286     adjmatrix = best_adjmatrix;
287     mc_rwvsetup_full();
288     ssize_t r = writev(fileno(mc_us->results), mc_iov, mc_niovs);
289     assert(r == mc_iovlen);
290   }
291   LPRINTF("worker %2d ending",mc_us->w);
292   exit(0);
293 }
294
295 static void multicore(void) {
296   Worker *mc_workers;
297   int w;
298   pid_t genpid;
299
300   multicore_iteration_boundary = n / 2;
301
302   FILE *busf = tmpfile();  assert(busf);
303   mc_bus = fileno(busf);
304   int r = fcntl(mc_bus, F_GETFL);  assert(r >= 0);
305   r |= O_APPEND;
306   r = fcntl(mc_bus, F_SETFL, r);  assert(r >= 0);
307
308   r = pipe(mc_work);  assert(!r);
309
310   mc_workers = xmalloc(sizeof(*mc_workers) * ncpus);
311   for (w=0; w<ncpus; w++) {
312     mc_workers[w].w = 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];
317       close(mc_work[1]);
318       LPRINTF("worker %2d running", w);
319       mc_iterate_worker();
320       exit(0);
321     }
322   }
323
324   close(mc_work[0]);
325
326   genpid = fork();  assert(genpid >= 0);
327   if (!genpid) {
328     mc_am_generator = 1;
329     LPRINTF("generator running");
330     iterate();
331     exit(0);
332   }
333
334   close(mc_work[1]);
335   mc_awaitpid(-1, genpid);
336   for (w=0; w<ncpus; w++)
337     mc_awaitpid(w, mc_workers[w].pid);
338
339   for (w=0; w<ncpus; w++) {
340     mc_rwvsetup_full();
341     LPRINTF("reading report from %2d",w);
342     ssize_t sr = preadv(fileno(mc_workers[w].results), mc_iov, mc_niovs, 0);
343     if (!sr) continue;
344     LPRINTF("got report from %2d",w);
345     maxhamweight = 0;
346     optimise(1);
347   }
348 }
349
350 static void multicore_check_for_new_best(void) {
351   if (!(mc_us || mc_am_generator))
352     return;
353
354   for (;;) {
355     double msg;
356     ssize_t got = pread(mc_bus, &msg, sizeof(msg), mc_bus_read);
357     if (!got) break;
358     assert(got == sizeof(msg));
359     if (msg > best)
360       set_best(msg);
361     mc_bus_read += sizeof(msg);
362   }
363 }
364
365 static void multicore_found_new_best(void) {
366   if (!mc_us)
367     return;
368
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));
372 }
373
374 /*----- end of multicore support -----*/
375
376 static AdjWord *xalloc_adjmatrix(void) {
377   return xmalloc(sizeof(*adjmatrix)*n);
378 }
379
380 static void prep(void) {
381   adjall = ~((~(AdjWord)0) << m);
382   adjmatrix = xalloc_adjmatrix();
383   glp_term_out(GLP_OFF);
384   setlinebuf(stderr);
385   weight = calloc(sizeof(*weight), m);  assert(weight);
386   n_max_frags = INT_MAX;
387   m_max_frags = INT_MAX;
388 }
389
390 #if 0
391 static AdjWord one_adj_bit(int bitnum) {
392   return (AdjWord)1 << bitnum;
393 }
394 #endif
395
396 static int count_set_adj_bits(AdjWord w) {
397   int j, total = 0;
398   AdjWord jbit;
399   FOR_BITS(j,m)
400     total += !!(w & jbit);
401   return total;
402 }
403
404 #define PRINTF(...) if (!doprint) ; else fprintf(stderr, __VA_ARGS__)
405
406 static int totalfrags;
407
408 static bool maxhamweight_ok(void) {
409   return maxhamweight <= m_max_frags;
410 }
411
412 static bool preconsider_ok(int nwords, bool doprint) {
413   int i;
414
415   PRINTF("%2d ", maxhamweight);
416
417   bool had_max = 0;
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) {
422       PRINTF(" too fine");
423       goto out;
424     }
425     had_max += (frags >= maxhamweight);
426     totalfrags += frags;
427   }
428   if (!had_max) {
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.) */
433     PRINTF(" nomaxham");
434     goto out;
435   }
436   return 1;
437
438  out:
439   return 0;
440 }
441
442 static void optimise(bool doprint) {
443   /* Consider the best answer (if any) for a given adjacency matrix */
444   glp_prob *prob = 0;
445   int i, j;
446   AdjWord jbit;
447
448   /*
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.
454    */
455 #define HAVE_PRINTED ({                                         \
456       if (!doprint) { doprint = 1; goto retry_with_print; }     \
457     })
458  retry_with_print:
459   if (prob) {
460     glp_delete_prob(prob);
461     prob = 0;
462   }
463
464   bool ok = preconsider_ok(n, doprint);
465   if (!ok)
466     goto out;
467
468   /*
469    * We formulate our problem as an LP problem as follows.
470    * In this file "n" and "m" are the matchstick numbers.
471    *
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.
474    *
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)
479    *
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)
483    *
484    * The objective function is simply
485    *   maximise x_minimum
486    *
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.
490    */
491
492   prob = glp_create_prob();
493
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);
497
498   {
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];
503
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++;                              \
510     })
511
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);
514
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);
517
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);
522
523   /* x_minimum >= 0 */
524   glp_set_col_bnds(prob, X_minimum, GLP_LO, 0, 0);
525   glp_set_col_name(prob, X_minimum, "minimum");
526
527   /* objective is maximising x_minimum */
528   glp_set_obj_dir(prob, GLP_MAX);
529   glp_set_obj_coef(prob, X_minimum, 1);
530
531   for (i=0; i<n; i++) {
532     FOR_BITS(j,m) {
533       if (!(adjmatrix[i] & jbit))
534         continue;
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 ] ++;
539
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);
543       if (doprint) {
544         char buf[255];
545         snprintf(buf,sizeof(buf),"mf %d,%d",i,j);
546         glp_set_col_name(prob, X_morefrag_i_j, buf);
547       }
548
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;
555     }
556   }
557
558   assert(next_matrix_entry == matrix_entries_size);
559
560   glp_load_matrix(prob, matrix_entries_size-1,
561                   matrix_entries_XY[1], matrix_entries_XY[0],
562                   matrix_entries);
563
564   int r = glp_simplex(prob, NULL);
565   PRINTF(" glp=%d", r);
566
567 #define OKERR(e) \
568   case e: PRINTF(" " #e ); goto out;
569 #define BADERR(e) \
570   case e: HAVE_PRINTED; printf(" " #e " CRASHING\n"); exit(-1);
571 #define DEFAULT \
572   default: HAVE_PRINTED; printf(" ! CRASHING\n"); exit(-1);
573
574   switch (r) {
575   OKERR(GLP_ESING);
576   OKERR(GLP_ECOND);
577   OKERR(GLP_EBOUND);
578   OKERR(GLP_EFAIL);
579   OKERR(GLP_ENOPFS);
580   OKERR(GLP_ENODFS);
581   BADERR(GLP_EBADB);
582   BADERR(GLP_EOBJLL);
583   BADERR(GLP_EOBJUL);
584   BADERR(GLP_EITLIM);
585   BADERR(GLP_ETMLIM);
586   BADERR(GLP_EINSTAB);
587   BADERR(GLP_ENOCVG);
588   case 0: break;
589   DEFAULT;
590   }
591
592   r = glp_get_status(prob);
593   PRINTF(" status=%d", r);
594
595   switch (r) {
596   OKERR(GLP_NOFEAS);
597   OKERR(GLP_UNDEF);
598   BADERR(GLP_FEAS);
599   BADERR(GLP_INFEAS);
600   BADERR(GLP_UNBND);
601   case GLP_OPT: break;
602   DEFAULT;
603   }
604
605   double got = glp_get_obj_val(prob);
606   PRINTF("  %g", got);
607   if (got <= best)
608     goto out;
609
610   HAVE_PRINTED;
611
612   set_best(got);
613   multicore_found_new_best();
614
615   if (best_prob) glp_delete_prob(best_prob);
616   best_prob = prob;
617
618   free(best_adjmatrix);
619   best_adjmatrix = xalloc_adjmatrix();
620   memcpy(best_adjmatrix, adjmatrix, sizeof(*adjmatrix)*n);
621
622   PRINTF(" BEST        \n");
623   return;
624
625   }
626  out:
627   if (prob)
628     glp_delete_prob(prob);
629   if (doprint) progress_eol();
630   if (doprint) multicore_check_for_new_best();
631 }
632
633 static void iterate_recurse(int i, AdjWord min) {
634   int j;
635   AdjWord jbit;
636
637   if (i >= n) {
638     for (j=0; j<m; j++)
639       if (weight[j] < 2)
640         return;
641
642     printcounter++;
643     optimise(!(printcounter & 0xfff));
644     return;
645   }
646   if (i >= multicore_iteration_boundary) {
647     multicore_outer_iteration(i, min);
648     return;
649   }
650   for (adjmatrix[i] = min;
651        ;
652        adjmatrix[i]++) {
653     if (count_set_adj_bits(adjmatrix[i]) > maxhamweight)
654       goto again;
655     if (i == 0 && (adjmatrix[i] & (1+adjmatrix[i])))
656       goto again;
657
658     FOR_BITS(j,m)
659       if (adjmatrix[i] & jbit)
660         weight[j]++;
661     for (int j = 0; j < m; j++)
662       if (weight[j] >= n_max_frags)
663         goto takeout;
664
665     iterate_recurse(i+1, adjmatrix[i]);
666
667   takeout:
668     FOR_BITS(j,m)
669       if (adjmatrix[i] & jbit)
670         weight[j]--;
671
672   again:
673     if (adjmatrix[i] == adjall)
674       return;
675   }
676 }
677
678 static void iterate(void) {
679   for (maxhamweight=1; maxhamweight<=m; maxhamweight++) {
680     if (!maxhamweight_ok())
681       continue;
682
683     iterate_recurse(0, 1);
684   }
685 }
686
687 static void report(void) {
688   fprintf(stderr, "\n");
689   if (best_prob) {
690     double min = glp_get_obj_val(best_prob);
691     double a[n][m];
692     int i, j, cols;
693     for (i = 0; i < n; i++)
694       for (j = 0; j < m; j++)
695         a[i][j] = 0;
696     cols = glp_get_num_cols(best_prob);
697     for (i = 1; i <= cols; i++) {
698       int x, y;
699       if (2 != sscanf(glp_get_col_name(best_prob, i), "mf %d,%d", &x, &y))
700         continue;
701       a[x][y] = min + glp_get_col_prim(best_prob, i);
702     }
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++) {
706         if (a[i][j])
707           printf(" %9.3f", a[i][j]);
708         else
709           printf("          ");
710       }
711       printf("\n");
712     }
713   }
714   if (ferror(stdout) || fclose(stdout)) { perror("stdout"); exit(-1); }
715 }
716  
717 int main(int argc, char **argv) {
718   int opt;
719   while ((opt = getopt(argc,argv,"j:")) >= 0) {
720     switch (opt) {
721     case 'j': ncpus = atoi(optarg); break;
722     case '+': assert(!"bad option");
723     default: abort();
724     }
725   }
726   argc -= optind-1;
727   argv += optind-1;
728   assert(argc==3);
729   n = atoi(argv[1]);
730   m = atoi(argv[2]);
731   assert(n > m);
732
733   prep();
734
735   if (ncpus) multicore();
736   else iterate();
737
738   report();
739   return 0;
740 }