summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorcos <cos>2022-12-01 16:59:14 +0000
committercos <cos>2022-12-01 17:27:26 +0000
commitb08254347f9d9d7812fb513f046918b0cd00c501 (patch)
tree9f9b9f712558437c6dd635fb69425a98d51ec236
parent1773627631cc873b6a09098dda1cac14c6ed03fa (diff)
downloadadventofcode-b08254347f9d9d7812fb513f046918b0cd00c501.zip
Add day01, 2022
-rw-r--r--2022/rust/Cargo.toml28
-rw-r--r--2022/rust/day01/src/main.rs64
2 files changed, 92 insertions, 0 deletions
diff --git a/2022/rust/Cargo.toml b/2022/rust/Cargo.toml
new file mode 100644
index 0000000..079c5ee
--- /dev/null
+++ b/2022/rust/Cargo.toml
@@ -0,0 +1,28 @@
+[workspace]
+members = [
+ "day01",
+# "day02",
+# "day03",
+# "day04",
+# "day05",
+# "day06",
+# "day07",
+# "day08",
+# "day09",
+# "day10",
+# "day11",
+# "day12",
+# "day13",
+# "day14",
+# "day15",
+# "day16",
+# "day17",
+# "day18",
+# "day19",
+# "day20",
+# "day21",
+# "day22",
+# "day23",
+# "day24",
+# "day25",
+]
diff --git a/2022/rust/day01/src/main.rs b/2022/rust/day01/src/main.rs
new file mode 100644
index 0000000..a0c5bae
--- /dev/null
+++ b/2022/rust/day01/src/main.rs
@@ -0,0 +1,64 @@
+use {
+ anyhow::{
+ anyhow,
+ Context,
+ Result,
+ },
+ std::{
+ env::args,
+ fs::File,
+ io::{
+ BufRead,
+ BufReader,
+ },
+ path::Path,
+ },
+};
+
+fn read_input<T: AsRef<Path>>(filename: T) -> Result<Vec<Vec<usize>>> {
+ let reader = BufReader::new(File::open(filename)?);
+
+ let mut elves = vec![vec![]];
+
+ for line in reader.lines() {
+ let s = line?;
+ if s.is_empty() {
+ elves.push(vec![]);
+ continue;
+ }
+ let elf = elves.last_mut().context("Invalid elves vector.")?;
+ let n = s.parse().context("Could not parse {s}")?;
+ elf.push(n);
+ }
+
+ Ok(elves)
+}
+
+fn part1<'a, I: IntoIterator<Item = &'a Vec<usize>>>(input: I) -> Result<usize> {
+ input.into_iter().map(|foodpacks| foodpacks.iter().sum()).max()
+ .context("Iterator chain in first part failed.")
+}
+
+fn part2<'a, I: IntoIterator<Item = &'a Vec<usize>>>(input: I) -> Result<usize> {
+ let mut calories: Vec<usize> = input.into_iter().map(|foodpacks| foodpacks.iter().sum())
+ .collect();
+ calories.sort();
+
+ Ok(calories.into_iter().rev().take(3).sum::<usize>())
+}
+
+fn main() -> Result<()> {
+ let ( do_part_1, do_part_2 ) = aoc::do_parts();
+
+ let filename = args().nth(1).ok_or_else(|| anyhow!("Missing input filename"))?;
+ let input = read_input(filename).context("Could not read input")?;
+ if do_part_1 {
+ let solution = part1(&input).context("No solution for part 1")?;
+ println!("Part1, solution found to be: {}", solution);
+ }
+ if do_part_2 {
+ let solution = part2(&input).context("No solution for part 2")?;
+ println!("Part2, solution found to be: {}", solution);
+ }
+ Ok(())
+}