From 724a84753cecb17261d2332ee60acb71fa0c3240 Mon Sep 17 00:00:00 2001 From: Andrei Navumenka Date: Sat, 6 Jul 2024 20:27:58 -0400 Subject: [PATCH] Add Rust permutations (#196) --- rust/Cargo.toml | 4 ++++ rust/combinatorics/permutations.rs | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 rust/combinatorics/permutations.rs diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 2d2daf48..ea28a970 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -4,6 +4,10 @@ version = "0.1.0" edition = "2021" +[[bin]] +name = "permutations" +path = "combinatorics/permutations.rs" + [[bin]] name = "topological_sort" path = "graphs/dfs/topological_sort.rs" diff --git a/rust/combinatorics/permutations.rs b/rust/combinatorics/permutations.rs new file mode 100644 index 00000000..2f112427 --- /dev/null +++ b/rust/combinatorics/permutations.rs @@ -0,0 +1,20 @@ +pub fn next_permutation(p: &mut [usize]) -> Option<()> { + let a = (0..p.len() - 1).rfind(|&i| p[i] < p[i + 1])?; + let b = (a + 1..p.len()).rfind(|&i| p[a] < p[i]).unwrap(); + p.swap(a, b); + p[a + 1..].reverse(); + Some(()) +} + +#[cfg(test)] +mod tests { + use crate::next_permutation; + + #[test] + fn basic_test() { + let mut p: [usize; 4] = [0, 3, 2, 1]; + let res = next_permutation(&mut p); + assert_eq!(p, [1, 0, 2, 3]); + assert_eq!(res, Some(())); + } +}