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