Don't like ads? PRO users don't see any ads ;-)

# Untitled

By: a guest on Jun 11th, 2012  |  syntax: D  |  size: 1.65 KB  |  hits: 32  |  expires: Never
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
1. module test;
2.
3. import std.algorithm;
4. import std.stdio;
5. import std.traits;
6. import std.range;
7.
8. struct Permutations(R) {
9.     ElementType!R[] _input, _perm;
10.     size_t k, n;
11.
12.     this(R r) {
13.         _input = array(r);
14.         _perm = array(r);
15.         n = _perm.length;
16.         k = n;
17.     }
18.
19.     this(R r, size_t elems) {
20.         _input = array(r);
21.         _perm = array(r);
22.         n = min(elems, _perm.length);
23.         k = n;
24.     }
25.
26.     ElementType!R[] front() { return _perm;}
27.     bool empty() { return (n == 1 && k == 0 )|| (n>1 && k <=1);}
28.     @property Permutations save() { return this;}
29.     void popFront() {
30.         k = n;
31.         if (k==0) { n=1;} // permutation of an empty range or of zero elements
32.         else {
33.             C3: _perm = _perm[1..k] ~ _perm[0] ~ _perm[k..\$];
34.             if (_perm[k-1] == _input[k-1]) {
35.                 k--;
36.                 if (k > 1) goto C3;
37.             }
38.         }
39.     }
40. }
41.
42. /// ditto
43. Permutations!R permutations(R)(R r) if (isDynamicArray!R) {
44.     return Permutations!R(r);
45. }
46.
47. /// ditto
48. Permutations!R permutations(R)(R r, size_t n) if (isDynamicArray!R) {
49.     return Permutations!R(r, n);
50. }
51.
52. /// ditto
53. Permutations!(ElementType!R[]) permutations(R)(R r) if (!isDynamicArray!R && isForwardRange!R && !isInfinite!R) {
54.     return Permutations!(ElementType!R[])(array(r));
55. }
56.
57. /// ditto
58. Permutations!(ElementType!R[]) permutations(R)(R r, size_t n) if (!isDynamicArray!R && isForwardRange!R && !isInfinite!R) {
59.     return Permutations!(ElementType!R[])(array(r), n);
60. }
61.
62.
63. void main()
64. {
65.     string[] words = ["foo", "bar", "doo"];
66.     auto p1 = permutations(words);
67.     writeln(p1);
68. }