From ed450df09489f1cde664c203fc3a303080c042c1 Mon Sep 17 00:00:00 2001 From: uesugi6111 <59960488+uesugi6111@users.noreply.github.com> Date: Sat, 2 Dec 2023 15:06:19 +0000 Subject: [PATCH 1/2] impl --- src/math/permutation.rs | 55 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/src/math/permutation.rs b/src/math/permutation.rs index 496895d..32a49fd 100644 --- a/src/math/permutation.rs +++ b/src/math/permutation.rs @@ -37,6 +37,45 @@ fn push_recusive( vvec } +pub struct Permutation +where + T: Clone, +{ + p: Vec, + init: bool, +} + +impl Permutation +where + T: Clone, +{ + pub fn new(p: &[T]) -> Self { + Self { + p: p.to_vec(), + init: false, + } + } +} +impl Iterator for Permutation +where + T: Clone + Ord, +{ + type Item = Vec; + + fn next(&mut self) -> Option { + if !self.init { + self.p.sort(); + self.init = true; + return Some(self.p.clone()); + } + let Some(i) = (0..&self.p.len() - 1).rfind(|&i| self.p[i] < self.p[i + 1]) else { return None; }; + let j = self.p.iter().rposition(|x| x > &self.p[i]).unwrap(); + self.p.swap(i, j); + self.p[i + 1..].reverse(); + Some(self.p.clone()) + } +} + #[cfg(test)] mod tests { use super::*; @@ -45,4 +84,20 @@ mod tests { let vv = make_permutation(4); assert_eq!(0, vv[0][0]); } + #[test] + fn test_struct() { + let expect = [ + &[0, 1, 2], + &[0, 2, 1], + &[1, 0, 2], + &[1, 2, 0], + &[2, 0, 1], + &[2, 1, 0], + ]; + let a = Permutation::new(&[0, 1, 2]); + + for (i, v) in a.enumerate() { + assert_eq!(v, expect[i]); + } + } } From 2c0507ec042f037ff2cbd9376baefa0bbb5e038e Mon Sep 17 00:00:00 2001 From: uesugi6111 <59960488+uesugi6111@users.noreply.github.com> Date: Sat, 2 Dec 2023 15:56:17 +0000 Subject: [PATCH 2/2] format --- src/math/permutation.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/math/permutation.rs b/src/math/permutation.rs index 32a49fd..62b0731 100644 --- a/src/math/permutation.rs +++ b/src/math/permutation.rs @@ -68,7 +68,9 @@ where self.init = true; return Some(self.p.clone()); } - let Some(i) = (0..&self.p.len() - 1).rfind(|&i| self.p[i] < self.p[i + 1]) else { return None; }; + let Some(i) = (0..&self.p.len() - 1).rfind(|&i| self.p[i] < self.p[i + 1]) else { + return None; + }; let j = self.p.iter().rposition(|x| x > &self.p[i]).unwrap(); self.p.swap(i, j); self.p[i + 1..].reverse();