I am translating this next permutation algorithm in C++:
template<class BidirIt> bool next_permutation(BidirIt first, BidirIt last) { if (first == last) return false; BidirIt i = last; if (first == --i) return false; while (true) { BidirIt i1, i2; i1 = i; if (*--i < *i1) { i2 = last; while (!(*i < *--i2)) ; std::iter_swap(i, i2); std::reverse(i1, last); return true; } if (i == first) { std::reverse(first, last); return false; } } }
Into this Rust code:
struct Solution;
impl Solution {
pub fn next_permutation(nums: &mut Vec<i32>) -> bool{
if nums.len() < 2 {
return false;
}
let first = 0;
let last = nums.len();
let mut i = last - 1;
loop {
let i1 = i;
i -= 1;
if nums[i] < nums[i1] {
let mut i2 = last;
loop {
i2 -= 1;
if nums[i] < nums[i2] {
break;
}
}
let tmp = nums[i];
nums[i] = nums[i2];
nums[i2] = tmp;
nums[i1..last].reverse();
return true;
}
if i == first {
nums[first..last].reverse();
return false;
}
}
}
}
Though it works, I think it's not very good-looking. I am a beginner in Rust; any improvement will be welcome!