diff --git a/.gitignore b/.gitignore index c487889..37ae6f8 100644 --- a/.gitignore +++ b/.gitignore @@ -24,3 +24,5 @@ docs/site/ # environment. Manifest.toml +target +Cargo.lock diff --git a/day1/Cargo.toml b/day1/Cargo.toml new file mode 100644 index 0000000..a3c4e52 --- /dev/null +++ b/day1/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "day1" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/day1/example.txt b/day1/example.txt new file mode 100644 index 0000000..2094f91 --- /dev/null +++ b/day1/example.txt @@ -0,0 +1,14 @@ +1000 +2000 +3000 + +4000 + +5000 +6000 + +7000 +8000 +9000 + +10000 diff --git a/day1/src/main.rs b/day1/src/main.rs new file mode 100644 index 0000000..ca414eb --- /dev/null +++ b/day1/src/main.rs @@ -0,0 +1,62 @@ +// From rust by example + +use std::fs::File; +use std::io::{self, BufRead}; +use std::path::Path; + +fn aoc_day1(path : &str, n : i64) -> i64 { + let mut max_calories : [i64; 3] = [0, 0, 0]; + let mut calories : i64 = 0; + if let Ok(lines) = read_lines(path) { + for line in lines { + if let Ok(scalories) = line { + println!("{}", scalories); + println!("[{}, {}, {}]", max_calories[0], max_calories[1], max_calories[2]); + if scalories.len() == 0 { + if calories > max_calories[0] { + max_calories[0] = calories; + max_calories.sort(); + } + calories = 0; + } else { + let snack_calories = scalories.parse::().unwrap(); + calories += snack_calories; + } + } + } + // eof + if calories > max_calories[0] { + max_calories[0] = calories; + max_calories.sort(); + } + } + if n == 1 { + return max_calories[2]; + } else { + return max_calories.iter().sum(); + } +} + +// 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

(filename: P) -> io::Result>> +where P: AsRef, { + let file = File::open(filename)?; + Ok(io::BufReader::new(file).lines()) +} + +fn main() { + aoc_day1("day1input.txt", 1); +} + +#[test] +fn day1input() { + assert_eq!(aoc_day1("day1input.txt", 1), 69206); + assert_eq!(aoc_day1("day1input.txt", 3), 197400); +} + +#[test] +fn example() { + assert_eq!(aoc_day1("example.txt", 1), 24000); + assert_eq!(aoc_day1("example.txt", 3), 45000); +}