How to resolve the algorithm Next highest int from digits step by step in the Rust programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Next highest int from digits step by step in the Rust programming language

Table of Contents

Problem Statement

Given a zero or positive integer, the task is to generate the next largest integer using only the given digits*1.

The above could prove slow and memory hungry for numbers with large numbers of digits, but should be easy to reason about its correctness.

E.g.: This second algorithm is faster and more memory efficient, but implementations may be harder to test. One method of testing, (as used in developing the task),   is to compare results from both algorithms for random numbers generated from a range that the first algorithm can handle.

Calculate the next highest int from the digits of the following numbers:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Next highest int from digits step by step in the Rust programming language

Source code in the rust programming language

fn next_permutation<T: PartialOrd>(array: &mut [T]) -> bool {
    let len = array.len();
    if len < 2 {
        return false;
    }
    let mut i = len - 1;
    while i > 0 {
        let j = i;
        i -= 1;
        if array[i] < array[j] {
            let mut k = len - 1;
            while array[i] >= array[k] {
                k -= 1;
            }
            array.swap(i, k);
            array[j..len].reverse();
            return true;
        }
    }
    false
}

fn next_highest_int(n: u128) -> u128 {
    use std::iter::FromIterator;
    let mut chars: Vec<char> = n.to_string().chars().collect();
    if !next_permutation(&mut chars) {
        return 0;
    }    
    String::from_iter(chars).parse::<u128>().unwrap()
}

fn main() {
    for n in &[0, 9, 12, 21, 12453, 738440, 45072010, 95322020, 9589776899767587796600] {
        println!("{} -> {}", n, next_highest_int(*n));
    }
}


  

You may also check:How to resolve the algorithm Same fringe step by step in the Ada programming language
You may also check:How to resolve the algorithm Van der Corput sequence step by step in the Ada programming language
You may also check:How to resolve the algorithm Loops/Foreach step by step in the WDTE programming language
You may also check:How to resolve the algorithm Variables step by step in the Eiffel programming language
You may also check:How to resolve the algorithm Call a function in a shared library step by step in the Maple programming language