Day 3: Lobby

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

FAQ

  • urandom@lemmy.world
    link
    fedilink
    English
    arrow-up
    2
    ·
    edit-2
    1 month ago

    I’m still struggling to learn Rust, and also to figure out a good solution to these problems, but here’s mine anyway:

    #[allow(dead_code)]
    pub fn part1(input: Lines<BufReader<File>>) {
        let mut sum = 0;
        for line in input.map_while(Result::ok) {
            let total = find_joltage(line.as_bytes(), 2, false);
            let res = str::from_utf8(total.as_slice()).unwrap();
    
            sum += res.parse::<u32>().unwrap();
        }
    
        println!("{}", sum);
    }
    
    #[allow(dead_code)]
    pub fn part2(input: Lines<BufReader<File>>) {
        let mut sum = 0;
        for (_, line) in input.map_while(Result::ok).enumerate() {
            let total = find_joltage(line.as_bytes(), 12, false);
            let res = str::from_utf8(total.as_slice()).unwrap();
    
            sum += res.parse::<u64>().unwrap();
        }
    
        println!("{}", sum);
    }
    
    fn find_joltage(b: &[u8], size: usize, debug: bool) -> Vec<u8> {
        if size == 0 {
            return vec![];
        }
    
        let mut max: u8 = 0;
        let mut max_i = 0;
        for i in (0..=b.len() - size).rev() {
            if b[i] >= max {
                max = b[i];
                max_i = i;
            }
        }
    
        if debug {
            println!("max = {}, i = {}", max as char, max_i);
        }
        let mut rest = find_joltage(&b[max_i + 1..], size - 1, debug);
    
        rest.insert(0, max);
        rest
    }