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

use std::marker::PhantomData;
use std::ops::{
    AddAssign,
    MulAssign,
    Sub,
    Mul,
    SubAssign,
    DivAssign,
    Div,
};
use std::convert::TryInto;
use std::fmt::Debug;

use num::BigUint;

use Construct;
use Data;
use Of;
use space::Space;

/// Dimension is natural number, position is a list of numbers.
pub struct Permutation<T = Data>(PhantomData<T>);

impl<T> Construct for Permutation<T> {
    fn new() -> Self { Permutation(PhantomData) }
}

impl Space<usize> for Permutation<Data> {
    type Dim = usize;
    type Pos = Vec<usize>;
    fn count(&self, dim: &usize) -> usize {
        let mut res = 1;
        for x in 1..dim + 1 {
            res *= x;
        }
        res
    }
    fn zero(&self, dim: &usize) -> Vec<usize> {
        vec![0; *dim]
    }
    fn to_index(&self, dim: &usize, pos: &Vec<usize>) -> usize {
        let mut index = 0;
        let mut count = 1;
        for (i, &x) in pos.iter().enumerate().rev() {
            let lower = pos[..i].iter().filter(|&&y| y < x).count();
            index += count * (x - lower);
            count *= dim - i;
        }
        index
    }
    fn to_pos(&self, dim: &usize, mut index: usize, pos: &mut Vec<usize>) {
        unsafe { pos.set_len(0); }

        let mut count = 1;
        for (j, x) in (1..dim + 1).enumerate() {
            count *= x;
            pos.push(j);
        }

        for i in 0..*dim {
            let block = count / (dim - i);
            let ind = index / block;
            let item = pos.remove(ind);
            pos.push(item);
            count /= dim - i;
            index -= ind * block;
        }
    }
}

impl Space<BigUint> for Permutation<Data> {
    type Dim = BigUint;
    type Pos = Vec<BigUint>;
    fn count(&self, dim: &BigUint) -> BigUint {
        let _1: BigUint = 1usize.into();
        let mut res: BigUint = _1.clone();
        let mut x = _1.clone();
        loop {
            if &x > dim {break}
            res *= &x;
            x += &_1;
        }
        res
    }
    fn zero(&self, dim: &BigUint) -> Vec<BigUint> {
        let dim: usize = dim.try_into().unwrap();
        vec![0usize.into(); dim]
    }
    fn to_index(&self, dim: &Self::Dim, pos: &Self::Pos) -> BigUint {
        let mut index: BigUint = 0usize.into();
        let mut count: BigUint = 1usize.into();
        for (i, x) in pos.iter().enumerate().rev() {
            let lower = pos[..i].iter().filter(|&y| y < x).count();
            index += &count * (x - lower);
            count *= dim - i;
        }
        index
    }
    fn to_pos(&self, dim: &Self::Dim, mut index: BigUint, pos: &mut Self::Pos) {
        pos.clear();

        let mut count: BigUint = 1usize.into();
        let dim: usize = dim.try_into().unwrap();
        for (j, x) in (1usize..dim + 1).enumerate() {
            count *= x;
            pos.push(j.into());
        }

        let dim: usize = dim.try_into().unwrap();
        for i in 0..dim {
            let block = &count / (dim - i);
            let ind: BigUint = &index / &block;
            let item = pos.remove((&ind).try_into().unwrap());
            pos.push(item);
            count /= dim - i;
            index -= &ind * block;
        }
    }
}

impl<N, T> Space<N> for Permutation<Of<T>>
    where T: Space<N>,
          T::Pos: Clone,
          N: Clone +
             From<usize> +
             TryInto<usize> +
             for<'a> AddAssign<&'a N> +
             for<'a> MulAssign<&'a N> +
             Sub<usize, Output = N> +
             SubAssign +
             DivAssign<usize> +
             MulAssign<usize> +
             PartialOrd,
          <N as TryInto<usize>>::Error: Debug,
          for<'a> &'a N: Sub<usize, Output = N> +
                         Mul<&'a N, Output = N> +
                         Div<usize, Output = N> +
                         Div<&'a N, Output = N> +,
          <N as TryInto<usize>>::Error: Debug,
{
    type Dim = T::Dim;
    type Pos = Vec<T::Pos>;
    fn count(&self, dim: &Self::Dim) -> N {
        let of: T = Construct::new();
        let _1: N = 1usize.into();
        let mut x = _1.clone();
        let mut res = _1.clone();
        let of_count = of.count(dim);
        loop {
            if &x > &of_count {break}
            res *= &x;
            x += &_1;
        }
        res
    }
    fn zero(&self, dim: &Self::Dim) -> Self::Pos {
        let of: T = Construct::new();
        let count = match of.count(dim).try_into() {
            Ok(x) => x,
            Err(_) => panic!("Out of range"),
        };
        vec![of.zero(dim); count]
    }
    fn to_index(&self, dim: &Self::Dim, pos: &Self::Pos) -> N {
        let of: T = Construct::new();
        let mut index: N = 0usize.into();
        let dim_count = of.count(dim);
        let mut count: N = 1usize.into();
        for (i, x) in pos.iter()
            .map(|x| of.to_index(dim, x))
            .enumerate().rev() {
            let lower = pos[..i].iter()
                .map(|y| of.to_index(dim, y))
                .filter(|y| y < &x).count();
            index += &(&count * &(x - lower));
            count *= &(&dim_count - i);
        }
        index
    }
    fn to_pos(&self, dim: &Self::Dim, mut index: N, pos: &mut Self::Pos) {
        let of: T = Construct::new();
        let of_count: usize = of.count(dim).try_into().unwrap();
        pos.clear();

        let mut count: N = 1usize.into();
        for (j, x) in (1..of_count + 1).enumerate() {
            count *= x;
            let mut new_pos: T::Pos = of.zero(&dim);
            of.to_pos(dim, j.into(), &mut new_pos);
            pos.push(new_pos);
        }

        for i in 0..of_count {
            let diff = of_count - i;
            let block = &count / diff;
            let ind = &index / &block;
            index -= &ind * &block;
            let item = pos.remove(ind.try_into().unwrap());
            pos.push(item);
            count /= diff;
        }
    }
}

#[cfg(test)]
mod test {
    use super::super::*;

    #[test]
    fn features() {
        is_complete::<usize, Permutation>();
        is_complete::<usize, Permutation<Of<Pair>>>();
    }

    #[test]
    fn data() {
        let permutation: Permutation = Construct::new();
        assert_eq!(permutation.count(&1), 1);
        assert_eq!(permutation.count(&2), 2);
        assert_eq!(permutation.count(&3), 6);
        assert_eq!(permutation.count(&4), 24);

        let mut pos = Vec::new();
        let ref dim = 4;
        let count = permutation.count(dim);
        for i in 0..count {
            permutation.to_pos(dim, i, &mut pos);
            let index = permutation.to_index(dim, &pos);
            assert_eq!(index, i);
        }
    }

    #[test]
    fn data_big() {
        use std::convert::TryInto;

        let permutation: Permutation = Construct::new();
        let ins: Vec<BigUint> = vec![
            1usize.into(),
            2usize.into(),
            3usize.into(),
            4usize.into(),
        ];
        let outs: Vec<BigUint> = vec![
            1usize.into(),
            2usize.into(),
            6usize.into(),
            24usize.into(),
        ];
        for i in 0..ins.len() {
            assert_eq!(permutation.count(&ins[i]), outs[i]);
        }

        let mut pos: Vec<BigUint> = Vec::new();
        let ref dim: BigUint = 4usize.into();
        let count: usize = permutation.count(dim).try_into().unwrap();
        for i in 0usize..count {
            permutation.to_pos(dim, i.into(), &mut pos);
            let index = permutation.to_index(dim, &pos);
            assert_eq!(index, i.into());
        }
    }

    #[test]
    fn of() {
        let space: Permutation<Of<Pair>> = Construct::new();
        let ref dim = 3;
        let count = space.count(dim);
        let mut pos = space.zero(dim);
        for i in 0..count {
            space.to_pos(dim, i, &mut pos);
            let index = space.to_index(dim, &pos);
            assert_eq!(index, i);
        }
    }

    #[test]
    fn of_big() {
        use std::convert::TryInto;

        let space: Permutation<Of<Pair>> = Construct::new();
        let ref dim: BigUint = 3usize.into();
        let count: usize = space.count(dim).try_into().unwrap();
        let mut pos = space.zero(dim);
        for i in 0..count {
            space.to_pos(dim, i.into(), &mut pos);
            let index = space.to_index(dim, &pos);
            assert_eq!(index, i.into());
        }
    }
}