Skip to content

Commit

Permalink
Add Rust permutations (#196)
Browse files Browse the repository at this point in the history
  • Loading branch information
indy256 authored Jul 7, 2024
1 parent 1f87908 commit 724a847
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
4 changes: 4 additions & 0 deletions rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
20 changes: 20 additions & 0 deletions rust/combinatorics/permutations.rs
Original file line number Diff line number Diff line change
@@ -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(()));
}
}

0 comments on commit 724a847

Please sign in to comment.