Advent of Rust // Day 1

Today is December 1st and thus the first day of Advent of Code. This year I decided to give Rust a try. As with my attempt with Haskell two years ago, I come unprepared with virtually zero knowledge about Rust. The only things I did beforehand were install the Rust compiler, the IntelliJ Rust plugin, and run the canonical “hello world” program.

The puzzle was dead simple, but it still took me over half an hour, mostly because I had no idea what I was doing and the Rust compiler was yelling at me. I suppose I could’ve winged it more easily using a loop and a mutable vector, but I like immutability, splitting and mapping. After solving the first part, I learned that there’s no built-in way to sort an immutable vector. I finished the second part by making the vector mutable, but eventually went back to reserach and discovered the itertools crate. My final solution looks like this:

use std::fs;  
use itertools::Itertools;  
fn main() {  
    let input = fs::read_to_string("input/day01.txt").unwrap();  
    let calories_per_elf: Vec<u32> = input  
        .map(|items| items.split("\n").map(|x| -> u32 { x.parse().unwrap() }).sum())  
    println!("Part One: {}", calories_per_elf.iter().max().unwrap());  
    println!("Part Two: {}", calories_per_elf.iter().take(3).sum::<u32>());  

I’m not sure how far I am from a solid, idiomatic Rust solution. It doesn’t look horrible to me, but what do I know after about an hour with the language. If you have any tips, a comment is much appreciated.

PS: You can find my code on github in the advent-of-rust-2022 repository.

See also in Advent of Rust


You can leave a comment by replying to this post on Mastodon.