Calorie Counting
These problems were simple enough to solve by thinking through them, the challenge was the rust.
Part 1
We are asked to take the input and total the calories in each grouped number and find the largest sum. The input data looks like the following and was 2266 lines long. Obviously I started with the sample data from the puzzle description:
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
The first thing to do was to create the input file and read that data in. Rust has a handy convention for that. I then split the elements on the double newline to create an array or list of the groups.
fn main() {
let input: &str = include_str!("./day1_1_input.txt");
let lines = input.split("\n\n");
/* ... */
}
After a bit of googling and trial and error I landed on this little gem of a line to parse the groups into numbers u32
and then total them, returning a list of totaled amounts.
I then sorted the collection and printed the top one, which is the largest.
let mut linesParse: Vec<u32> = lines.map(|line|line.split("\n").flat_map(|num|num.parse::<u32>()).sum::<u32>()).collect();
linesParse.sort_by(|a,b|b.cmp(a));
println!("{:?}", linesParse.iter().take(1).sum::<u32>());
Part 2
For part 2 we needed to find the total of the top 3 elves which was easy since I had struck google-gold with the Part 1 piece.
All I had to do was take(3)
and it was ready to go!
println!("{:?}", linesParse.iter().take(3).sum::<u32>());
Final Solution
Here is the whole file after I was done:
fn main() {
let input: &str = include_str!("./day1_1_input.txt");
let lines = input.split("\n\n");
let mut linesParse: Vec<u32> = lines.map(|line|line.split("\n").flat_map(|num|num.parse::<u32>()).sum::<u32>()).collect();
linesParse.sort_by(|a,b|b.cmp(a));
println!("{:?}", linesParse.iter().take(3).sum::<u32>());
}