Find the next smaller positive integer containing the same digits

Finding the Next Smaller Positive Integer with the Same Digits in Rust

To find the next smaller positive integer containing the same digits in Rust, you can follow these steps:

  1. Convert the positive integer to a string.
  2. Convert the string to a character array.
  3. Iterate over the character array from right to left until you find a digit that is smaller than the digit to its right.
  4. Swap the smaller digit with the smallest digit to its right that is larger than it.
  5. Sort the digits to the right of the swapped digit in ascending order.
  6. Convert the character array back to a string and parse it as an integer.

Here's an example implementation in Rust:

fn find_next_smaller_integer(n: u32) -> Option<u32> {
    let mut digits: Vec<char> = n.to_string().chars().collect();

    let mut i = digits.len() - 1;
    while i > 0 && digits[i - 1] <= digits[i] {
        i -= 1;
    }

    if i == 0 {
        return None; // No smaller integer with the same digits found
    }

    let mut j = digits.len() - 1;
    while digits[j] >= digits[i - 1] {
        j -= 1;
    }

    digits.swap(i - 1, j);
    digits[i..].sort();

    let result: String = digits.into_iter().collect();
    result.parse().ok()
}

fn main() {
    let n = 12345;
    if let Some(next_smaller) = find_next_smaller_integer(n) {
        println!("Next smaller integer with the same digits: {}", next_smaller);
    } else {
        println!("No smaller integer with the same digits found");
    }
}

This implementation uses a greedy algorithm to find the next smaller integer with the same digits. It has a time complexity of O(d), where d is the number of digits in the input integer.

I hope this helps! Let me know if you have any further questions.