DEV Community

Discussion on: Daily Challenge #12 - Next Larger Number

Collapse
 
coreyja profile image
Corey Alexander

Took a long drive up for vacation yesterday so I wasn't able to get this types out! I think I know what I'm gonna implement so just gotta see if I can't type it out today! Can't get oo far behind on these challenges! I owe two now !

Collapse
 
coreyja profile image
Corey Alexander

Got it done! Was able to write out what I was thinking last night without too much hassle, pretty happy with how it came out.

Could have tried not converting to chars in the middle, but it worked out pretty nicely still I think!

pub fn next_largest(n: u32) -> Option<u32> {
    let s = n.to_string();

    let mut chars: Vec<_> = s.chars().collect();

    for i in (0..chars.len() - 1).rev() {
        let first = chars[i].to_digit(10).unwrap();
        let second = chars[i + 1].to_digit(10).unwrap();

        if second > first {
            chars.swap(i, i + 1);
            let s: String = chars.iter().collect();

            return Some(s.parse().unwrap());
        }
    }

    None
}

#[cfg(test)]
mod tests {
    use crate::*;

    #[test]
    fn it_works_for_examples_that_have_no_largest() {
        assert_eq!(next_largest(4), None);
        assert_eq!(next_largest(100), None);
        assert_eq!(next_largest(9876), None);
    }

    #[test]
    fn it_works_for_the_examples() {
        assert_eq!(next_largest(12), Some(21));
        assert_eq!(next_largest(2019), Some(2091));
        assert_eq!(next_largest(513), Some(531));
    }

    #[test]
    fn it_works_for_large_numebrs() {
        assert_eq!(next_largest(36852367), Some(36852376));
        assert_eq!(next_largest(123456789), Some(123456798));
        assert_eq!(next_largest(5010), Some(5100));
    }
}
Collapse
 
coreyja profile image
Corey Alexander

I notice a lot of people did theirs differently so I thought I'd explain what I did!

One of the things I noticed that led to my solution, was the fast that the next largest number, was 1 'sort' away from the number we had. What I mean is if we imagine our number as an array of its digits, the number we wanted was 1 swap away AND would make our 'array' more sorted than it was before!

This made me realize that a modified bubble sort was exactly what I was looking for! So below I conconted something loosely based on a bubble sort. It starts at the end of the number and moves backward seeing if it can make a swap. If it does, it returns the swapped value. If we make it to the beggining of the list we know there wasn't a larger number and simply return None!

Collapse
 
oscherler profile image
Olivier “Ölbaum” Scherler

I wanted to do it like this (in Erlang), but didn’t figure out how to. Nice.

Thread Thread
 
oscherler profile image
Olivier “Ölbaum” Scherler

I think you have a mistake: next_largest(351) should return 513, and you return 531.

That’s where I gave up with the swapping approach.