2022 AoC Day 1 – Calorie Counting

This is a solution to Advent of Code 2022 day 1, written in Raku and Rust.

https://adventofcode.com/2022/day/1

Part One

Find the Elf carrying the most Calories. How many total Calories is that Elf carrying?

The input text has several lines per Elf, with a single calorie value per line. The lines for each Elf are split by a double newline. We need to calculate the sum of the calorie values for each Elf and then find the maximum.

# Build a list of lists of calorie values per Elf.
# Split the input by Elf and then split again by line
my @elves = '1-input.txt'.IO.split("\n\n")>>.lines;

# Reduce each Elf list to its total and find the maximum
say max @elves>>.sum;
68923

Rust

use std::error::Error;
use std::fs;
fn main() -> Result<(), Box<dyn Error>> {
    let input = fs::read_to_string("/Users/donaldh/git/advent-of-code/2022/1-input.txt")?;
    let elves: Vec<Vec<u32>> = input
        .split("\n\n")
        .map(|x| x.lines().map(|x| x.parse::<u32>().unwrap()).collect())
        .collect();
    let calories: Vec<u32> = elves.iter().map(|x| x.iter().sum()).collect();
    let max = calories.iter().max().unwrap();
    println!("{:#?}", max);

    Ok(())
}
68923

Part Two

Find the top three Elves carrying the most Calories. How many Calories are those Elves carrying in total?

Instead of finding the maximum, we need to sort the list of totals and take the top three. Then we can report the sum of those three totals.

my @elves = '1-input.txt'.IO.split("\n\n")>>.lines;

# Reduce, sort and sum the top three
say @elves>>.sum.sort.tail(3).sum;
200044

Rust

use std::error::Error;
use std::fs;
fn main() -> Result<(), Box<dyn Error>> {
    let input = fs::read_to_string("/Users/donaldh/git/advent-of-code/2022/1-input.txt")?;
    let elves: Vec<Vec<u32>> = input
        .split("\n\n")
        .map(|x| x.lines().map(|x| x.parse::<u32>().unwrap()).collect())
        .collect();
    let mut calories: Vec<u32> = elves.iter().map(|x| x.iter().sum()).collect();
    calories.sort();
    let sum3: u32 = calories.iter().rev().take(3).sum();
    println!("{:#?}", sum3);

    Ok(())
}
200044
raku