Created
May 1, 2021 19:52
-
-
Save m1el/cf038f3c91f2ff71655bd890b7fd5a20 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Permutes the `slice` into the next permutation, where the set of all | |
/// permutations is ordered lexicographically. | |
/// Returns `true` if there is a next permutation. | |
/// | |
/// # Example | |
/// ```rust | |
/// let mut values: Vec<usize> = (0..3).collect(); | |
/// while next_permutation(&mut values) { | |
/// println!("current permutation: {:?}", values); | |
/// } | |
/// ``` | |
fn next_permutation<T: Ord>(slice: &mut [T]) -> bool { | |
let last = slice.len().saturating_sub(1); | |
if last == 0 { | |
return false; | |
} | |
let mut i = last; | |
loop { | |
let i1 = i; | |
i -= 1; | |
if slice[i] < slice[i1] { | |
let mut i2 = last; | |
while slice[i] >= slice[i2] { | |
i2 -= 1; | |
} | |
slice.swap(i, i2); | |
slice[i1..].reverse(); | |
return true; | |
} | |
if i == 0 { | |
slice.reverse(); | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment