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
//! Permutations as elements in symmetric groups.

use std::collections::{HashMap, HashSet, VecDeque};
use std::fmt;
use std::hash::Hash;
use std::ops::Mul;

use anyhow::{self, format_err};
use bitvec::prelude::*;
use derive_builder::Builder;
use factorial::Factorial;
use indexmap::IndexSet;
use num::{integer::lcm, Integer, Unsigned};
use num_traits::{Inv, Pow, PrimInt};
use serde::{Deserialize, Serialize};

use crate::group::FiniteOrder;

mod permutation_group;
mod permutation_symbols;

#[cfg(test)]
mod permutation_tests;

// =================
// Trait definitions
// =================

/// Trait defining a permutable collection consisting of discrete and distinguishable items that
/// can be permuted.
pub trait PermutableCollection
where
    Self: Sized,
    Self::Rank: PermutationRank,
{
    /// The type of the rank of the permutation.
    type Rank;

    /// Determines the permutation, if any, that maps `self` to `other`.
    fn get_perm_of(&self, other: &Self) -> Option<Permutation<Self::Rank>>;

    /// Permutes the items in the current collection by `perm` and returns a new collection with
    /// the permuted items.
    fn permute(&self, perm: &Permutation<Self::Rank>) -> Result<Self, anyhow::Error>;

    /// Permutes in-place the items in the current collection by `perm`.
    fn permute_mut(&mut self, perm: &Permutation<Self::Rank>) -> Result<(), anyhow::Error>;
}

/// Trait defining an action on a permutable collection that can be converted into an equivalent
/// permutation acting on that collection.
pub trait IntoPermutation<C: PermutableCollection> {
    /// Determines the permutation of `rhs` considered as a collection induced by the action of
    /// `self` on `rhs` considered as an element in its domain. If no such permutation could be
    /// found, `None` is returned.
    fn act_permute(&self, rhs: &C) -> Option<Permutation<C::Rank>>;
}

/// Trait for generic permutation rank types.
pub trait PermutationRank:
    Integer + Unsigned + BitStore + PrimInt + Hash + TryFrom<usize> + Into<usize> + Serialize
{
}

/// Blanket implementation of `PermutationRank`.
impl<T> PermutationRank for T
where
    T: Integer + Unsigned + BitStore + PrimInt + Hash + TryFrom<usize> + Into<usize> + Serialize,
    <T as TryFrom<usize>>::Error: fmt::Debug,
    std::ops::Range<T>: Iterator + DoubleEndedIterator,
    Vec<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    VecDeque<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    IndexSet<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
{
}

// ==================
// Struct definitions
// ==================

/// Structure to manage permutation actions of a finite set.
#[derive(Builder, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Permutation<T: PermutationRank> {
    /// If the permutation is to act on an ordered sequence of $`n`$ integers, $`0, 1, \ldots, n`$,
    /// then this gives the result of the action.
    #[builder(setter(custom))]
    image: Vec<T>,
}

impl<T: PermutationRank> PermutationBuilder<T> {
    /// If the permutation is to act on an ordered sequence of $`n`$ integers, $`0, 1, \ldots, n`$,
    /// then this gives the result of the action.
    pub fn image(&mut self, perm: Vec<T>) -> &mut Self {
        let mut uniq = HashSet::<T>::new();
        // assert!(
        //     perm.iter().all(move |x| uniq.insert(*x)),
        //     "The permutation image `{perm:?}` contains repeated elements."
        // );
        if perm.iter().all(move |x| uniq.insert(*x)) {
            // The permutation contains all distinct elements.
            self.image = Some(perm);
        }
        self
    }
}

impl<T: PermutationRank> Permutation<T> {
    /// Returns a builder to construct a new permutation.
    #[must_use]
    fn builder() -> PermutationBuilder<T> {
        PermutationBuilder::default()
    }

    /// Constructs a permutation from the image of its action on an ordered sequence of integers,
    /// $`0, 1, \ldots`$.
    ///
    /// # Arguments
    ///
    /// * `image` - The image of the permutation when acting on an ordered sequence of integers,
    /// $`0, 1, \ldots`$.
    ///
    /// # Returns
    ///
    /// The corresponding permutation.
    ///
    /// # Panics
    ///
    /// Panics if `image` contains repeated elements.
    pub fn from_image(image: Vec<T>) -> Result<Self, anyhow::Error> {
        Self::builder()
            .image(image.clone())
            .build()
            .map_err(|err| format_err!(err))
    }

    /// Constructs a permutation from its disjoint cycles.
    ///
    /// # Arguments
    ///
    /// * `cycles` - The disjoint cycles defining the permutation.
    ///
    /// # Returns
    ///
    /// The corresponding permutation.
    ///
    /// # Panics
    ///
    /// Panics if the cycles in `cycles` contain repeated elements.
    pub fn from_cycles(cycles: &[Vec<T>]) -> Result<Self, anyhow::Error> {
        let mut uniq = HashSet::<T>::new();
        assert!(
            cycles.iter().flatten().all(move |x| uniq.insert(*x)),
            "The permutation cycles `{cycles:?}` contains repeated elements."
        );
        let mut image_map = cycles
            .iter()
            .flat_map(|cycle| {
                let start = *cycle.first().expect("Empty cycles are not permitted.");
                let end = *cycle.last().expect("Empty cycles are not permitted.");
                cycle
                    .windows(2)
                    .map(|pair| {
                        let idx = pair[0];
                        let img = pair[1];
                        (idx, img)
                    })
                    .chain([(end, start)])
            })
            .collect::<Vec<(T, T)>>();
        image_map.sort();
        let image = image_map
            .into_iter()
            .map(|(_, img)| img)
            .collect::<Vec<T>>();
        Self::from_image(image)
    }

    /// Constructs a permutation from its Lehmer encoding.
    ///
    /// See [here](https://en.wikipedia.org/wiki/Lehmer_code) for additional information.
    pub fn from_lehmer(lehmer: Vec<T>) -> Result<Self, anyhow::Error>
    where
        <T as TryFrom<usize>>::Error: fmt::Debug,
        std::ops::Range<T>: Iterator,
        VecDeque<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    {
        let n = T::try_from(lehmer.len()).expect("Unable to convert the `lehmer` length to `u8`.");
        let mut remaining = (T::zero()..n).collect::<VecDeque<T>>();
        let image = lehmer
            .iter()
            .map(|&k| {
                remaining.remove(k.into()).unwrap_or_else(|| {
                    panic!("Unable to retrieve element index `{k:?}` from `{remaining:?}`.")
                })
            })
            .collect::<Vec<_>>();
        Self::from_image(image)
    }

    /// Constructs a permutation from the integer index obtained from a Lehmer encoding.
    ///
    /// See [here](https://en.wikipedia.org/wiki/Lehmer_code) and
    /// Korf, R. E. Linear-time disk-based implicit graph search. *J. ACM* **55**, 1–40 (2008).
    /// for additional information.
    ///
    /// # Arguments
    ///
    /// * `index` - An integer index.
    /// * `rank` - A rank for the permutation to be constructed.
    ///
    /// # Returns
    ///
    /// Returns the corresponding permutation.
    ///
    /// # Errors
    ///
    /// If `index` is not valid for a permutation of rank `rank`.
    pub fn from_lehmer_index(index: usize, rank: T) -> Result<Self, anyhow::Error>
    where
        <T as TryFrom<usize>>::Error: fmt::Debug,
        std::ops::Range<T>: Iterator,
        VecDeque<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    {
        let mut quotient = index;
        let mut lehmer: VecDeque<T> = VecDeque::new();
        let mut i = 1usize;
        while quotient != 0 {
            if i == 1 {
                lehmer.push_front(T::zero());
            } else {
                lehmer.push_front(T::try_from(quotient.rem_euclid(i)).unwrap());
                quotient = quotient.div_euclid(i);
            }
            i += 1;
        }
        if lehmer.len() > rank.into() {
            Err(format_err!("The Lehmer encode length is larger than the rank of the permutation."))
        } else {
            while lehmer.len() < rank.into() {
                lehmer.push_front(T::zero());
            }
            Self::from_lehmer(lehmer.into_iter().collect::<Vec<_>>())
        }
    }

    /// The rank of the permutation.
    pub fn rank(&self) -> T {
        T::try_from(self.image.len()).unwrap_or_else(|_| {
            panic!(
                "The rank of `{:?}` is too large to be represented as `u8`.",
                self.image
            )
        })
    }

    /// If the permutation is to act on an ordered sequence of integers, $`0, 1, \ldots`$, then
    /// this gives the result of the action.
    pub fn image(&self) -> &Vec<T> {
        &self.image
    }

    /// Obtains the cycle representation of the permutation.
    pub fn cycles(&self) -> Vec<Vec<T>>
    where
        std::ops::Range<T>: Iterator + DoubleEndedIterator,
        Vec<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
        IndexSet<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    {
        let image = &self.image;
        let rank = self.rank();
        let mut remaining_indices = (T::zero()..rank).rev().collect::<IndexSet<T>>();
        let mut cycles: Vec<Vec<T>> = Vec::with_capacity(rank.into());
        while !remaining_indices.is_empty() {
            let start = remaining_indices
                .pop()
                .expect("`remaining_indices` should not be empty.");
            let mut cycle: Vec<T> = Vec::with_capacity(remaining_indices.len());
            cycle.push(start);
            let mut idx = start;
            while image[idx.into()] != start {
                idx = image[idx.into()];
                assert!(remaining_indices.shift_remove(&idx));
                cycle.push(idx);
            }
            cycle.shrink_to_fit();
            cycles.push(cycle);
        }
        cycles.shrink_to_fit();
        cycles.sort_by_key(|cycle| (!cycle.len(), cycle.clone()));
        cycles
    }

    /// Returns the pattern of the cycle representation of the permutation.
    pub fn cycle_pattern(&self) -> Vec<T>
    where
        <T as TryFrom<usize>>::Error: fmt::Debug,
        std::ops::Range<T>: Iterator + DoubleEndedIterator,
        Vec<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
        IndexSet<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    {
        self.cycles()
            .iter()
            .map(|cycle| {
                T::try_from(cycle.len()).expect("Some cycle lengths are too long for `u8`.")
            })
            .collect::<Vec<T>>()
    }

    /// Returns `true` if this permutation is the identity permutation for this rank.
    pub fn is_identity(&self) -> bool
    where
        <T as TryFrom<usize>>::Error: fmt::Debug,
    {
        self.lehmer_index(None) == 0
    }

    /// Returns the Lehmer encoding of the permutation.
    ///
    /// # Arguments
    ///
    /// * `count_ones_opt` - An optional hashmap containing the number of ones in each of the
    /// possible bit vectors of length [`Self::rank`].
    ///
    /// # Returns
    ///
    /// The Lehmer encoding of this permutation. See
    /// [here](https://en.wikipedia.org/wiki/Lehmer_code) for additional information.
    pub fn lehmer(&self, count_ones_opt: Option<&HashMap<BitVec<T, Lsb0>, T>>) -> Vec<T>
    where
        <T as TryFrom<usize>>::Error: fmt::Debug,
    {
        let mut bv: BitVec<T, Lsb0> = bitvec![T, Lsb0; 0; self.rank().into()];
        let n = self.rank();
        self.image
            .iter()
            .enumerate()
            .map(|(i, &k)| {
                let flipped_bv_k = !bv[k.into()];
                bv.set(k.into(), flipped_bv_k);
                if i == 0 {
                    k
                } else if i == (n - T::one()).into() {
                    T::zero()
                } else {
                    let mut bv_k = bv.clone();
                    bv_k.shift_right((n - k).into());
                    k - if let Some(count_ones) = count_ones_opt {
                        *(count_ones.get(&bv_k).unwrap_or_else(|| {
                            panic!("Unable to count the number of ones in `{bv}`.")
                        }))
                    } else {
                        T::try_from(bv_k.count_ones())
                            .expect("Unable to convert the number of ones to `u8`.")
                    }
                }
            })
            .collect::<Vec<T>>()
    }

    /// Returns the integer corresponding to the Lehmer encoding of this permutation.
    ///
    /// See [here](https://en.wikipedia.org/wiki/Lehmer_code) and
    /// Korf, R. E. Linear-time disk-based implicit graph search. *J. ACM* **55**, 1–40 (2008).
    /// for additional information.
    ///
    /// # Arguments
    ///
    /// * `count_ones_opt` - An optional hashmap containing the number of ones in each of the
    /// possible bit vectors of length [`Self::rank`].
    ///
    /// # Returns
    ///
    /// Returns the integer corresponding to the Lehmer encoding of this permutation.
    pub fn lehmer_index(&self, count_ones_opt: Option<&HashMap<BitVec<T, Lsb0>, T>>) -> usize
    where
        <T as TryFrom<usize>>::Error: fmt::Debug,
    {
        let lehmer = self.lehmer(count_ones_opt);
        let n = self.rank().into() - 1;
        if n == 0 {
            0
        } else {
            lehmer
                .into_iter()
                .enumerate()
                .map(|(i, l)| {
                    l.into()
                        * (n - i).checked_factorial().unwrap_or_else(|| {
                            panic!("The factorial of `{}` cannot be correctly computed.", n - i)
                        })
                })
                .sum()
        }
    }
}

// =====================
// Trait implementations
// =====================

// -------
// Display
// -------
impl<T: PermutationRank + fmt::Display> fmt::Display for Permutation<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "π({})",
            self.image
                .iter()
                .map(|i| i.to_string())
                .collect::<Vec<_>>()
                .join(".")
        )
    }
}

// ---
// Mul
// ---
impl<T: PermutationRank> Mul<&'_ Permutation<T>> for &Permutation<T>
where
    std::ops::Range<T>: Iterator + DoubleEndedIterator,
    Vec<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    VecDeque<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    <T as TryFrom<usize>>::Error: fmt::Debug,
    IndexSet<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
{
    type Output = Permutation<T>;

    fn mul(self, rhs: &Permutation<T>) -> Self::Output {
        assert_eq!(
            self.rank(),
            rhs.rank(),
            "The ranks of two multiplying permutations do not match."
        );
        Self::Output::builder()
            .image(
                rhs.image
                    .iter()
                    .map(|&ri| self.image[ri.into()])
                    .collect::<Vec<T>>(),
            )
            .build()
            .expect("Unable to construct a product `Permutation`.")
    }
}

impl<T: PermutationRank> Mul<&'_ Permutation<T>> for Permutation<T>
where
    std::ops::Range<T>: Iterator + DoubleEndedIterator,
    Vec<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    VecDeque<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    <T as TryFrom<usize>>::Error: fmt::Debug,
    IndexSet<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
{
    type Output = Permutation<T>;

    fn mul(self, rhs: &Permutation<T>) -> Self::Output {
        &self * rhs
    }
}

impl<T: PermutationRank> Mul<Permutation<T>> for Permutation<T>
where
    std::ops::Range<T>: Iterator + DoubleEndedIterator,
    Vec<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    VecDeque<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    <T as TryFrom<usize>>::Error: fmt::Debug,
    IndexSet<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
{
    type Output = Permutation<T>;

    fn mul(self, rhs: Permutation<T>) -> Self::Output {
        &self * &rhs
    }
}

impl<T: PermutationRank> Mul<Permutation<T>> for &Permutation<T>
where
    std::ops::Range<T>: Iterator + DoubleEndedIterator,
    Vec<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    VecDeque<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    <T as TryFrom<usize>>::Error: fmt::Debug,
    IndexSet<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
{
    type Output = Permutation<T>;

    fn mul(self, rhs: Permutation<T>) -> Self::Output {
        self * &rhs
    }
}

// ---
// Inv
// ---
impl<T: PermutationRank> Inv for &Permutation<T>
where
    std::ops::Range<T>: Iterator + DoubleEndedIterator,
    Vec<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    VecDeque<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    <T as TryFrom<usize>>::Error: fmt::Debug,
    IndexSet<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
{
    type Output = Permutation<T>;

    fn inv(self) -> Self::Output {
        let mut image_inv = (T::zero()..self.rank()).collect::<Vec<T>>();
        image_inv.sort_by_key(|&i| self.image[i.into()]);
        Self::Output::builder()
            .image(image_inv)
            .build()
            .expect("Unable to construct an inverse `Permutation`.")
    }
}

impl<T: PermutationRank> Inv for Permutation<T>
where
    std::ops::Range<T>: Iterator + DoubleEndedIterator,
    Vec<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    VecDeque<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    <T as TryFrom<usize>>::Error: fmt::Debug,
    IndexSet<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
{
    type Output = Permutation<T>;

    fn inv(self) -> Self::Output {
        (&self).inv()
    }
}

// ---
// Pow
// ---
impl<T: PermutationRank> Pow<i32> for &Permutation<T>
where
    std::ops::Range<T>: Iterator + DoubleEndedIterator,
    Vec<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    VecDeque<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    <T as TryFrom<usize>>::Error: fmt::Debug,
    IndexSet<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
{
    type Output = Permutation<T>;

    fn pow(self, rhs: i32) -> Self::Output {
        if rhs == 0 {
            Self::Output::builder()
                .image((T::zero()..self.rank()).collect::<Vec<T>>())
                .build()
                .expect("Unable to construct an identity `Permutation`.")
        } else if rhs > 0 {
            self * self.pow(rhs - 1)
        } else {
            let rhs_p = -rhs;
            (self * self.pow(rhs_p - 1)).inv()
        }
    }
}

impl<T: PermutationRank> Pow<i32> for Permutation<T>
where
    std::ops::Range<T>: Iterator + DoubleEndedIterator,
    Vec<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    VecDeque<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    <T as TryFrom<usize>>::Error: fmt::Debug,
    IndexSet<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
{
    type Output = Permutation<T>;

    fn pow(self, rhs: i32) -> Self::Output {
        (&self).pow(rhs)
    }
}

// -----------
// FiniteOrder
// -----------
impl<T: PermutationRank + fmt::Display> FiniteOrder for Permutation<T>
where
    u32: From<T>,
    std::ops::Range<T>: Iterator + DoubleEndedIterator,
    Vec<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    VecDeque<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
    <T as TryFrom<usize>>::Error: fmt::Debug,
    IndexSet<T>: FromIterator<<std::ops::Range<T> as Iterator>::Item>,
{
    type Int = u32;

    /// Calculates the order of this permutation. This is the lowest common multiplier of the
    /// lengths of the disjoint cycles constituting this permutation.
    fn order(&self) -> Self::Int {
        u32::try_from(
            self.cycle_pattern()
                .iter()
                .cloned()
                .reduce(lcm)
                .unwrap_or_else(|| {
                    panic!("Unable to determine the permutation order of `{self}`.")
                }),
        )
        .expect("Unable to convert the permutation order to `u32`.")
    }
}

// =========
// Functions
// =========
/// Permutes the items in a vector in-place.
///
/// # Arguments
///
/// * `vec` - An exclusive reference to a vector of items to be permuted.
/// * `perm` - A shared reference to a permutation determining how the items are to be permuted.
pub(crate) fn permute_inplace<T>(vec: &mut Vec<T>, perm: &Permutation<usize>) {
    assert_eq!(
        perm.rank(),
        vec.len(),
        "The permutation rank does not match the number of items in the vector."
    );
    let mut image = perm.image().clone();
    for idx in 0..vec.len() {
        if image[idx] != idx {
            let mut current_idx = idx;
            loop {
                let target_idx = image[current_idx];
                image[current_idx] = current_idx;
                if image[target_idx] == target_idx {
                    break;
                }
                vec.swap(current_idx, target_idx);
                current_idx = target_idx;
            }
        }
    }
}