DEV Community

Discussion on: Daily Challenge #251 - Largest Number in a Sequence

Collapse
 
qm3ster profile image
Mihail Malo • Edited

Rust

🔗 the below code in a runnable playground

"imperative"

fn bige(input: u64) -> u64 {
    let mut current = input;
    let mut max = 0;
    for _ in 0..16 {
        let five = current % 100_000;
        if five > max {
            max = five;
        }
        current /= 10;
        // // optional optimization, might be harmful, but division is slow
        // // I wonder if dividing zero is fast though? Probably.
        // if current == 0 {
        //     break;
        // }
    }
    max
}

iterator

unwrapping is safe, because even with 0 we will have at least one element
(actually we will consider 0 15 times)

fn bige_iter(input: u64) -> u64 {
    let mut current = input;
    std::iter::from_fn(|| {
        let yeld = current;
        current /= 10;
        Some(yeld)
    })
    .take(15)
    .map(|x| x % 100_000)
    .max()
    .unwrap()
}

immutable

bad: leads to dividing bigger numbers

fn bige_imut(input: u64) -> u64 {
    (0..16)
        .into_iter()
        .map(|i| (input / 10_u64.pow(i)) % 100_000)
        .max()
        .unwrap()
}

strings

good: can be longer than u64

fn bige_string(input: &str) -> u32 {
    // use use atoi::FromRadix10; in real life to avoid checking for utf8 first.
    input
        .as_bytes()
        .windows(5)
        .filter_map(|x| std::str::from_utf8(x).ok()?.parse::<u32>().ok())
        .max()
        .unwrap()
}

usage

fn main() {
    dbg!(bige(18446744073709551615));
    dbg!(bige_iter(18446744073709551615));
    dbg!(bige_imut(18446744073709551615));
    dbg!(bige_iter(0));
    dbg!(bige_imut(0));
    dbg!(bige_string("18446744073709551615"));
}