Skip to content

Instantly share code, notes, and snippets.

@ritesh
Created December 9, 2022 10:15
Show Gist options
  • Save ritesh/c8ef0e432e5e7ab3c17d5241501ceb12 to your computer and use it in GitHub Desktop.
Save ritesh/c8ef0e432e5e7ab3c17d5241501ceb12 to your computer and use it in GitHub Desktop.
day1.rs
use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
use std::str::FromStr;
fn main() {
let mut calories: Vec<u64> = Vec::new();
let mut caloriesum = 0;
let mut maxcalories = 0;
// File hosts must exist in current path before this produces output
if let Ok(lines) = read_lines("./input") {
// Consumes the iterator, returns an (Optional) String
for line in lines {
if let Ok(ip) = line {
if let Ok(cals) = u32::from_str(&ip) {
//println!("found a number");
caloriesum += cals;
} else {
if caloriesum > maxcalories {
maxcalories = caloriesum;
};
calories.push(caloriesum as u64);
caloriesum = 0;
}
}
}
}
if caloriesum > maxcalories {
maxcalories = caloriesum;
}
calories.push(caloriesum as u64);
println!("{:?}", calories);
println!("Max calories {}", maxcalories);
let elfnumber = calories.iter().position(|&x| x == maxcalories as u64);
println!("elf number: {}", elfnumber.unwrap());
//End of part one of the challenge. For part 2 we start with the vec of calories, need to find
//the top 3
//
calories.sort();
let top3:u64 = calories.iter().rev().take(3).sum();
println!("top 3 {}", top3);
}
// The output is wrapped in a Result to allow matching on errors
// Returns an Iterator to the Reader of the lines of the file.
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where P: AsRef<Path>, {
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment