-
Notifications
You must be signed in to change notification settings - Fork 5
/
combinations.html
2324 lines (2083 loc) · 72.8 KB
/
combinations.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Combinations and Permutations</title>
<style type="text/css">
p {text-align:justify}
li {text-align:justify}
blockquote.note
{
background-color:#E0E0E0;
padding-left: 15px;
padding-right: 15px;
padding-top: 1px;
padding-bottom: 1px;
}
ins {background-color:#A0FFA0}
del {background-color:#FFA0A0}
</style>
</head>
<body>
<address align=right>
Document number: Dxxxx=xx-xxxx<br>
<br>
<a href="mailto:howard.hinnant@gmail.com">Howard Hinnant</a><br>
2011-07-02
</address>
<hr>
<h1 align="center">Combinations and Permutations</h1>
<h2>Contents</h2>
<ul>
<li><a href="#Introduction">Introduction</a></li>
<li><a href="#Examples">Examples</a></li>
<li><a href="#Performance">Performance Considerations</a></li>
<li><a href="#Synopsis">Synopsis</a></li>
<li><a href="#Specification">Specification</a></li>
<li><a href="#Implementation">Implementation</a></li>
</ul>
<h2><a name="Introduction"></a>Introduction</h2>
<p>
It doesn't happen very often, but every once in awhile one needs to iterate over
all of the combinations or permutations of a set of objects. Or more
specifically, given a set of <tt>N</tt> objects, you want to consider <tt>r</tt>
of them at a time (for each combination or permutation). The standard library
offers <tt>next_permutation</tt>, but this offering alone has a few drawbacks:
</p>
<ul>
<li>
<tt>next_permutation</tt> only offers permutations of <tt>N</tt> objects taken
<tt>N</tt> at a time. If you only need to consider permutations of length
<tt>r</tt> chosen from a list of length <tt>N</tt> then you can save a factor of
<tt>(n-r)!</tt> by iterating over only the permutations you need. If <tt>r</tt>
is small compared to <tt>N</tt> this can easily be several orders of magnitude
faster than iterating over all <tt>N!</tt> permutations.
</li>
<li>
If one only needs permutations, but not the reverse permutation, a factor
of 2 can be saved by iterating only over reversible permutations.
</li>
<li>
If your permutations are of a circular nature, you can save a factor of <tt>r</tt>
by iterating over only distinct circular permutations.
</li>
<li>
If your permutations are of a circular nature <em>and</em> it doesn't matter
whether your permutation goes in a clockwise or counter-clockwise direction,
then iterating only over distinct reversible, circular permutations can save
a factor of <tt>2r</tt> iterations compared to iterating over all <tt>N!</tt>
permutations.
</li>
<li>
If you're examining permutations of length <tt>r</tt> out of a list of length
<tt>N</tt> and order doesn't matter at all in each list of length <tt>r</tt>,
then it is far cheaper to iterate only over combinations of the <tt>N</tt>
items taken <tt>r</tt> at a time (by a factor of <tt>r!</tt>).
</li>
<li>
The user interface of <tt>next_permutation</tt> is potentially expensive:
for each iteration the algorithm must do a search for the next iteration. When
iterating <tt>N</tt> items taken <tt>r</tt> at a time, and when the number of
iterations is far less than <tt>N!</tt> (as it will be for many practical
problems), then the time spent finding the next iteration using a
<tt>next_permutation</tt>-style interface can completely swamp the time you
spend actually visiting each permutation.
</li>
<li>
To use <tt>next_permutation</tt>, the sequence must be LessThanComparable
and in sorted order. These requirements can be inconvenient, even impractical,
and are completely unnecessary.
</li>
</ul>
<p>
Below is a solution to each of these problems and more. The following generic
algorithms permit a client to visit every combination or permuation of a
sequence of length <tt>N</tt>, <tt>r</tt> items at time.
</p>
<blockquote><pre>
template <class BidirIter, class Function>
Function
<b>for_each_permutation</b>(BidirIter first,
BidirIter mid,
BidirIter last,
Function f);
template <class BidirIter, class Function>
Function
<b>for_each_reversible_permutation</b>(BidirIter first,
BidirIter mid,
BidirIter last,
Function f);
template <class BidirIter, class Function>
Function
<b>for_each_circular_permutation</b>(BidirIter first,
BidirIter mid,
BidirIter last,
Function f);
template <class BidirIter, class Function>
Function
<b>for_each_reversible_circular_permutation</b>(BidirIter first,
BidirIter mid,
BidirIter last,
Function f);
template <class BidirIter, class Function>
Function
<b>for_each_combination</b>(BidirIter first,
BidirIter mid,
BidirIter last,
Function f);
</pre></blockquote>
<p>
These each follow a <tt>for_each</tt> style: The algorithm calls a user
supplied function object for each combination/permutation in the sequence:
<tt>f(begin, end)</tt>. That function object can of course maintain state. The
sequence need not be sorted, nor even contain unique objects. The algorithms do
not consider the value of the sequence elements at all. That is, the element
type need not support <tt>LessThanComparable</tt> nor
<tt>EqualityComparable</tt>. Furthermore the algorithms follow three additional
rules:
</p>
<ol>
<li>
On normal (non-exceptional) completion, the sequence is always left in the
original order.
</li>
<li>
<p>
The functor is always called with <tt>[first, mid)</tt>. This enables the
functor to also access the elements not in the sequence if it is aware of the
sequence: <tt>[mid, last)</tt>. This can come in handy when dealing
with nested combination/permutation problems where for each permutation you
<em>also</em> need to compute combinations and/or permutations on those elements
<em>not</em> selected.
</p>
</li>
<li>
<p>
The functor should return <tt>true</tt> or <tt>false</tt>:
</p>
<ul>
<li>
<tt>true</tt> if the functor wishes to break out of the <tt>for_each_</tt> loop.
</li>
<li>
Otherwise <tt>false</tt>.
</li>
</ul>
</li>
</ol>
<p>
The following generic algorithms take a (preferably unsigned) integral type and
return the number of combinations or permutations that exist. Traditionally
these functions represent functions such as <tt><sub>n</sub>C<sub>r</sub></tt>
and <tt><sub>n</sub>P<sub>r</sub></tt>. This API breaks with tradition
concerning the definition of <tt>n</tt>. These functions compute:
<tt><sub>d1+d2</sub>C<sub>d1</sub></tt>, and
<tt><sub>d1+d2</sub>P<sub>d1</sub></tt>, and the related variations for
reversible and circular permuations. The rationale for this API is to avoid
invalid inputs. For example if we input <tt>n</tt> and <tt>r</tt> from
<tt><sub>n</sub>C<sub>r</sub></tt>, then we would have to check to make sure
that the precondition <tt>n ≥ r</tt> is true, and if not throw an
<tt>invalid_argument</tt> exception. But with the inputs <tt>d1</tt> and
<tt>d2</tt>, which represent <tt>distance(first, mid)</tt> and
<tt>distance(mid, last)</tt> respectively, there is no opportunity for invalid
inputs as long as we stick to unsigned integral types. However overflow is a
very real possibility. And if signed integral types are input (or a type
emulating signed integral types), then negative arguments will result in an
<tt>invalid_argument</tt> exception.
</p>
<blockquote><pre>
template <class UInt>
UInt
<b>count_each_combination</b>(UInt d1, UInt d2);
template <class UInt>
UInt
<b>count_each_permutation</b>(UInt d1, UInt d2);
template <class UInt>
UInt
<b>count_each_circular_permutation</b>(UInt d1, UInt d2);
template <class UInt>
UInt
<b>count_each_reversible_permutation</b>(UInt d1, UInt d2);
template <class UInt>
UInt
<b>count_each_reversible_circular_permutation</b>(UInt d1, UInt d2);
</pre></blockquote>
<p>
Each of the above algorithms avoids intermediate overflow. That is, if the
final answer is representable as a <tt>UInt</tt>, then they will return the
correct answer. Otherwise they will throw a <tt>std::overflow_error</tt>. This
noisy overflow protection is necessary as these functions can easily overflow.
For example <tt>count_each_combination(33ull, 34ull)</tt> returns
14,226,520,737,620,288,370. But
<tt>count_each_combination(33ull, 35ull)</tt> overflows for a 64 bit
<tt>unsigned long long</tt>. Without overflow protection, the returned result
will look quite reasonable to the casual observer and overflow is likely to
happen accidentally, go unnoticed, and cause further problems in program logic
which will be more difficult to diagnose.
</p>
<p>
Furthermore the following convenience functions are provided in order to more
easily "preflight" ranges sent to the <tt>for_each_*</tt> algorithms. The
reason that the <tt>UInt</tt> overloads of these algorithms exist is so that you
don't <em>have</em> to create a range to compute
<tt><sub>3000</sub>C<sub>2</sub></tt>. Instead you can simply call
<tt>count_each_combination(2ull, 2998ull)</tt> (for example).
</p>
<blockquote><pre>
template <class BidirIter>
std::uintmax_t
<b>count_each_combination</b>(BidirIter first,
BidirIter mid,
BidirIter last);
template <class BidirIter>
std::uintmax_t
<b>count_each_permutation</b>(BidirIter first,
BidirIter mid,
BidirIter last);
template <class BidirIter>
std::uintmax_t
<b>count_each_circular_permutation</b>(BidirIter first,
BidirIter mid,
BidirIter last);
template <class BidirIter>
std::uintmax_t
<b>count_each_reversible_permutation</b>(BidirIter first,
BidirIter mid,
BidirIter last);
template <class BidirIter>
std::uintmax_t
<b>count_each_reversible_circular_permutation</b>(BidirIter first,
BidirIter mid,
BidirIter last);
</pre></blockquote>
<h2><a name="Examples"></a>Examples</h2>
<p>
Below an example simply fills a vector with consecutive integers, and calls
<tt>for_each_permutation</tt> on a functor that will print out the permutation.
The functor will also print out items not in the permutation after a trailing
<tt>'|'</tt>. The functor also counts the number of permutations visited so
that the client can query that amount after the call to
<tt>for_each_permutation</tt>.
</p>
<blockquote><pre>
#include <iostream>
#include <vector>
#include <numeric>
#include <cstdint>
#include <cassert>
<font color="#C80000">// print out a range separated by commas,</font>
<font color="#C80000">// return number of values printed.</font>
template <class It>
unsigned
display(It begin, It end)
{
unsigned r = 0;
if (begin != end)
{
std::cout << *begin;
++r;
for (++begin; begin != end; ++begin)
{
std::cout << ", " << *begin;
++r;
}
}
return r;
}
<font color="#C80000">// functor called for each permutation</font>
class f
{
unsigned len;
std::uint64_t count;
public:
explicit f(unsigned l) : len(l), count(0) {}
template <class It>
<b>bool operator()(It first, It last)</b> <font color="#C80000">// called for each permutation</font>
{
<font color="#C80000">// count the number of times this is called</font>
++count;
<font color="#C80000">// print out [first, mid) surrounded with [ ... ]</font>
std::cout << "[ ";
unsigned r = display(first, last);
<font color="#C80000">// If [mid, last) is not empty, then print it out too</font>
<font color="#C80000">// prefixed by " | "</font>
if (r < len)
{
std::cout << " | ";
display(last, std::next(last, len - r));
}
std::cout << " ]\n";
return false; <font color="#C80000">// Don't break out of the loop</font>
}
operator std::uint64_t() const {return count;}
};
int main()
{
const int r = 3;
const int n = 5;
std::vector<int> v(n);
std::iota(v.begin(), v.end(), 0);
std::uint64_t count = <b>for_each_permutation(v.begin(),
v.begin() + r,
v.end(),
f(v.size()));</b>
<font color="#C80000">// print out "---" to the correct length for the above output</font>
unsigned e = 3 * r + 2;
if (r < v.size())
e += 1 + 3 * (v.size() - r);
for (unsigned i = 0; i < e; ++i)
std::cout << '-';
<font color="#C80000">// print out the permuted vector to show that it has the original order</font>
std::cout << "\n[ ";
display(v.begin(), v.end());
std::cout << " ]\n";
<font color="#C80000">// sanity check</font>
assert(count == <b>count_each_permutation(v.begin(), v.begin() + r, v.end()));</b>
<font color="#C80000">// print out summary of what has happened,</font>
<font color="#C80000">// using 'count' from functor state returned from for_each_permutation algorithm.</font>
std::cout << "Found " << count << " permutations of " << v.size()
<< " objects taken " << r << " at a time.\n";
}
</pre></blockquote>
<p>
And this is the output of this program:
</p>
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, 4 ]
Found 30 permutations of 5 objects taken 3 at a time.
</pre></blockquote>
<p>
For example <tt>[ 2, 1, 0 ]</tt> is not found in the above list.
</p>
<p>
By instead calling:
</p>
<blockquote><pre>
for_each_circular_permutation(v.begin(), v.begin() + r, v.end(), f(v.size()));
</pre></blockquote>
<p>
the original list can be cut by a third:
</p>
<blockquote><pre>
[ 0, 1, 2 | 3, 4 ]
[ 0, 2, 1 | 3, 4 ]
[ 0, 1, 3 | 2, 4 ]
[ 0, 3, 1 | 2, 4 ]
[ 0, 1, 4 | 2, 3 ]
[ 0, 4, 1 | 2, 3 ]
[ 0, 2, 3 | 1, 4 ]
[ 0, 3, 2 | 1, 4 ]
[ 0, 2, 4 | 1, 3 ]
[ 0, 4, 2 | 1, 3 ]
[ 0, 3, 4 | 1, 2 ]
[ 0, 4, 3 | 1, 2 ]
[ 1, 2, 3 | 0, 4 ]
[ 1, 3, 2 | 0, 4 ]
[ 1, 2, 4 | 0, 3 ]
[ 1, 4, 2 | 0, 3 ]
[ 1, 3, 4 | 0, 2 ]
[ 1, 4, 3 | 0, 2 ]
[ 2, 3, 4 | 0, 1 ]
[ 2, 4, 3 | 0, 1 ]
------------------
[ 0, 1, 2, 3, 4 ]
Found 20 permutations of 5 objects taken 3 at a time.
</pre></blockquote>
<p>
For example you will not find the following in the above list:
</p>
<blockquote><pre>
[ 1, 2, 0 ] // rotate(0, 1, 3) of permutation 1
[ 2, 0, 1 ] // rotate(0, 2, 3) of permutation 1
</pre></blockquote>
<p>
And if your circular permutations are also reversible, your list (and time
spent) can be halved again:
</p>
<blockquote><pre>
for_each_reversible_circular_permutation(v.begin(), v.begin() + r, v.end(), f(v.size()));
[ 0, 1, 2 | 3, 4 ]
[ 0, 1, 3 | 2, 4 ]
[ 0, 1, 4 | 2, 3 ]
[ 0, 2, 3 | 1, 4 ]
[ 0, 2, 4 | 1, 3 ]
[ 0, 3, 4 | 1, 2 ]
[ 1, 2, 3 | 0, 4 ]
[ 1, 2, 4 | 0, 3 ]
[ 1, 3, 4 | 0, 2 ]
[ 2, 3, 4 | 0, 1 ]
------------------
[ 0, 1, 2, 3, 4 ]
Found 10 permutations of 5 objects taken 3 at a time.
</pre></blockquote>
<p>
For example you will not find the following in the above list:
</p>
<blockquote><pre>
[ 2, 1, 0 ] // reverse(0, 3) of permutation(1)
[ 1, 2, 0 ] // rotate(0, 1, 3) of permutation(1)
[ 0, 2, 1 ] // reverse of rotate(0, 1, 3) of permutation(1)
[ 2, 0, 1 ] // rotate(0, 2, 3) of permutation(1)
[ 1, 0, 2 ] // reverse of rotate(0, 2, 3) of permutation(1)
</pre></blockquote>
<p>
When <tt>r</tt> is 3 or less, then reversible circular permutations are the
exact same as combinations. In this case use of <tt>for_each_combination</tt>
should be preferred as it will be a little more efficient. Additionally when
<tt>r</tt> is 2 or less, <tt>for_each_combination</tt> produces the same result
as <tt>for_each_circular_permutation</tt> and
<tt>for_each_reversible_permutation</tt>. When <tt>r == 1</tt>, all five
algorithms produce the same <tt>N</tt> permutations. When <tt>r == 0</tt>, all
five algorithms call the functor once with the empty range <tt>[first,
first)</tt>.
</p>
<p>
<img align="right" hspace="10" vspace="10" height="800" src="fig1.tiff"/>
</p>
<h2><a name="Performance"></a>Performance Considerations</h2>
<p>
Hervé Brönnimann published
<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2639.pdf">N2639</a>
proposing functionality somewhat similar as to what is outlined herein,
including:
</p>
<blockquote><pre>
template <class BidirIter>
bool
next_partial_permutation(BidirIter first,
BidirIter mid,
BidirIter last);
template <class BidirIter >
bool
next_combination(BidirIter first,
BidirIter mid,
BidirIter last);
</pre></blockquote>
<p>
This interface follows the style of the existing <tt>std::next_permutation</tt>
algorithm. It is the inverse of the <tt>for_each</tt> style: The client calls
the functor directly, and then calls the algorithm to find the next iteration.
</p>
<p>
The problem with this interface is that it can get expensive to find the next
iteration. For example when calling <tt>for_each_permutation</tt> and
<tt>next_partial_permutation</tt> with <tt>r == 4</tt> and varying <tt>N</tt>
from 4 to 100, the time to iterate through the permutations skyrockets for
<tt>next_partial_permutation</tt>, but not for <tt>for_each_permutation</tt>. By
the time <tt>N == 100</tt>, <tt>for_each_permutation</tt> is running over 137
times faster than <tt>next_partial_permutation</tt> which takes 20 seconds to do
what <tt>for_each_permutation</tt> accomplishes in well under one sixth of a
second. This trend rapidly gets worse as <tt>N</tt> grows.
</p>
<p>
The same performance comparison can be made between <tt>next_combination</tt>
and <tt>for_each_combination</tt>. It should be stressed that this isn't a lack
of quality or care put into the
<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2639.pdf">N2639</a>
implementation. I've studied that implementation carefully and consider it very
high quality. It is simply that the number of comparisons that need to be done
to find out which swaps need to be done gets outrageously expensive. The number
of swaps actually performed in both algorithms is approximately the same. At <tt>N ==
100</tt> <tt>for_each_combination</tt> is running about 14 times faster
than <tt>next_combination</tt>. And that discrepancy only grows as the number
of combinations increases.
</p>
<h2><a name="Synopsis"></a>Synopsis</h2>
<blockquote><pre>
<font color="#C80000">// Integral-based count_each_*</font>
template <class UInt>
UInt
count_each_permutation(UInt d1, UInt d2);
template <class UInt>
UInt
count_each_reversible_permutation(UInt d1, UInt d2);
template <class UInt>
UInt
count_each_circular_permutation(UInt d1, UInt d2);
template <class UInt>
UInt
count_each_reversible_circular_permutation(UInt d1, UInt d2);
template <class UInt>
UInt
count_each_combination(UInt d1, UInt d2);
<font color="#C80000">// Iterator-based count_each_*</font>
template <class BidirIter>
std::uintmax_t
count_each_permutation(BidirIter first,
BidirIter mid,
BidirIter last);
template <class BidirIter>
std::uintmax_t
count_each_reversible_permutation(BidirIter first,
BidirIter mid,
BidirIter last);
template <class BidirIter>
std::uintmax_t
count_each_circular_permutation(BidirIter first,
BidirIter mid,
BidirIter last);
template <class BidirIter>
std::uintmax_t
count_each_reversible_circular_permutation(BidirIter first,
BidirIter mid,
BidirIter last);
template <class BidirIter>
std::uintmax_t
count_each_combination(BidirIter first,
BidirIter mid,
BidirIter last);
<font color="#C80000">// Iterator-based for_each_* algorithms</font>
template <class BidirIter, class Function>
Function
for_each_permutation(BidirIter first,
BidirIter mid,
BidirIter last,
Function f);
template <class BidirIter, class Function>
Function
for_each_reversible_permutation(BidirIter first,
BidirIter mid,
BidirIter last,
Function f);
template <class BidirIter, class Function>
Function
for_each_circular_permutation(BidirIter first,
BidirIter mid,
BidirIter last,
Function f);
template <class BidirIter, class Function>
Function
for_each_reversible_circular_permutation(BidirIter first,
BidirIter mid,
BidirIter last,
Function f);
template <class BidirIter, class Function>
Function
for_each_combination(BidirIter first,
BidirIter mid,
BidirIter last,
Function f);
</pre></blockquote>
<h2><a name="Specification"></a>Specification</h2>
<p>
<i>Remarks:</i> In this section a post-fix <tt>!</tt> indicates a
<a href="http://en.wikipedia.org/wiki/Factorial">factorial operator</a> and has
higher precedence than any other operator.
</p>
<blockquote><pre>
template <class UInt>
UInt
count_each_permutation(UInt d1, UInt d2);
</pre>
<blockquote>
<p>
<i>Requires:</i> <tt>Uint</tt> is an integral type or a type emulating an
integral type.
</p>
<p>
<i>Returns:</i> <tt>(d1 + d2)!/d2!</tt>.
</p>
<p>
<i>Throws:</i> If the computed value is not representable in the type
<tt>UInt</tt>, throws <tt>std::overflow_error</tt>. If <tt>d1 < UInt(0)</tt>
or <tt>d2 < UInt(0)</tt>, throws <tt>std::invalid_argument</tt>.
</p>
<p>
<i>Remarks:</i> If the computed value is representable in the type
<tt>UInt</tt>, returns the correct value. This algorithm avoids intermediate
overflow.
</p>
</blockquote>
</blockquote>
<blockquote><pre>
template <class UInt>
UInt
count_each_reversible_permutation(UInt d1, UInt d2);
</pre>
<blockquote>
<p>
<i>Requires:</i> <tt>Uint</tt> is an integral type or a type emulating an
integral type.
</p>
<p>
<i>Returns:</i> If <tt>d1 <= 1</tt> returns <tt>(d1 + d2)!/d2!</tt>. Else
returns <tt>(d1 + d2)!/(2*d2!)</tt>.
</p>
<p>
<i>Throws:</i> If the computed value is not representable in the type
<tt>UInt</tt>, throws <tt>std::overflow_error</tt>. If <tt>d1 < UInt(0)</tt>
or <tt>d2 < UInt(0)</tt>, throws <tt>std::invalid_argument</tt>.
</p>
<p>
<i>Remarks:</i> If the computed value is representable in the type
<tt>UInt</tt>, returns the correct value. This algorithm avoids intermediate
overflow.
</p>
</blockquote>
</blockquote>
<blockquote><pre>
template <class UInt>
UInt
count_each_circular_permutation(UInt d1, UInt d2);
</pre>
<blockquote>
<p>
<i>Requires:</i> <tt>Uint</tt> is an integral type or a type emulating an
integral type.
</p>
<p>
<i>Returns:</i> If <tt>d1 == 0</tt> returns 1. Else returns <tt>(d1 +
d2)!/(d1*d2!)</tt>.
</p>
<p>
<i>Throws:</i> If the computed value is not representable in the type
<tt>UInt</tt>, throws <tt>std::overflow_error</tt>. If <tt>d1 < UInt(0)</tt>
or <tt>d2 < UInt(0)</tt>, throws <tt>std::invalid_argument</tt>.
</p>
<p>
<i>Remarks:</i> If the computed value is representable in the type
<tt>UInt</tt>, returns the correct value. This algorithm avoids intermediate
overflow.
</p>
</blockquote>
</blockquote>
<blockquote><pre>
template <class UInt>
UInt
count_each_reversible_circular_permutation(UInt d1, UInt d2);
</pre>
<blockquote>
<p>
<i>Requires:</i> <tt>Uint</tt> is an integral type or a type emulating an
integral type.
</p>
<p>
<i>Returns:</i> If <tt>d1 == 0</tt> returns 1. Else if <tt>d1 <= 2</tt>
returns <tt>(d1 + d2)!/(d1*d2!)</tt>. Else returns <tt>(d1 +
d2)!/(2*d1*d2!)</tt>.
</p>
<p>
<i>Throws:</i> If the computed value is not representable in the type
<tt>UInt</tt>, throws <tt>std::overflow_error</tt>. If <tt>d1 < UInt(0)</tt>
or <tt>d2 < UInt(0)</tt>, throws <tt>std::invalid_argument</tt>.
</p>
<p>
<i>Remarks:</i> If the computed value is representable in the type
<tt>UInt</tt>, returns the correct value. This algorithm avoids intermediate
overflow.
</p>
</blockquote>
</blockquote>
<blockquote><pre>
template <class UInt>
UInt
count_each_combination(UInt d1, UInt d2);
</pre>
<blockquote>
<p>
<i>Requires:</i> <tt>Uint</tt> is an integral type or a type emulating an
integral type.
</p>
<p>
<i>Returns:</i> <tt>(d1 + d2)!/(d1!*d2!)</tt>.
</p>
<p>
<i>Throws:</i> If the computed value is not representable in the type
<tt>UInt</tt>, throws <tt>std::overflow_error</tt>. If <tt>d1 < UInt(0)</tt>
or <tt>d2 < UInt(0)</tt>, throws <tt>std::invalid_argument</tt>.
</p>
<p>
<i>Remarks:</i> If the computed value is representable in the type
<tt>UInt</tt>, returns the correct value. This algorithm avoids intermediate
overflow.
</p>
</blockquote>
</blockquote>
<blockquote><pre>
template <class FwdIter>
std::uintmax_t
count_each_permutation(FwdIter first,
FwdIter mid,
FwdIter last);
</pre>
<blockquote>
<p>
<i>Requires:</i> <tt>[first, mid)</tt> and <tt>[mid, last)</tt> are valid
ranges.
</p>
<p>
<i>Returns:</i>
<tt>count_each_permutation<std::uintmax_t>(std::distance(first, mid),
std::distance(mid, last))</tt>.
</p>
</blockquote>
</blockquote>
<blockquote><pre>
template <class FwdIter>
std::uintmax_t
count_each_reversible_permutation(FwdIter first,
FwdIter mid,
FwdIter last);
</pre>
<blockquote>
<p>
<i>Requires:</i> <tt>[first, mid)</tt> and <tt>[mid, last)</tt> are valid
ranges.
</p>
<p>
<i>Returns:</i>
<tt>count_each_reversible_permutation<std::uintmax_t>(std::distance(first, mid),
std::distance(mid, last))</tt>.
</p>
</blockquote>
</blockquote>
<blockquote><pre>
template <class FwdIter>
std::uintmax_t
count_each_circular_permutation(FwdIter first,
FwdIter mid,
FwdIter last);
</pre>
<blockquote>
<p>
<i>Requires:</i> <tt>[first, mid)</tt> and <tt>[mid, last)</tt> are valid
ranges.
</p>
<p>
<i>Returns:</i>
<tt>count_each_circular_permutation<std::uintmax_t>(std::distance(first, mid),
std::distance(mid, last))</tt>.
</p>
</blockquote>
</blockquote>
<blockquote><pre>
template <class FwdIter>
std::uintmax_t
count_each_reversible_circular_permutation(FwdIter first,
FwdIter mid,
FwdIter last);
</pre>
<blockquote>
<p>
<i>Requires:</i> <tt>[first, mid)</tt> and <tt>[mid, last)</tt> are valid
ranges.
</p>
<p>
<i>Returns:</i>
<tt>count_each_reversible_circular_permutation<std::uintmax_t>(std::distance(first, mid),
std::distance(mid, last))</tt>.
</p>
</blockquote>
</blockquote>
<blockquote><pre>
template <class FwdIter>