summaryrefslogtreecommitdiff
path: root/2020/rust/day01
diff options
context:
space:
mode:
Diffstat (limited to '2020/rust/day01')
-rw-r--r--2020/rust/day01/Cargo.toml8
-rw-r--r--2020/rust/day01/src/main.rs72
2 files changed, 80 insertions, 0 deletions
diff --git a/2020/rust/day01/Cargo.toml b/2020/rust/day01/Cargo.toml
new file mode 100644
index 0000000..674217d
--- /dev/null
+++ b/2020/rust/day01/Cargo.toml
@@ -0,0 +1,8 @@
+[package]
+name = "day01"
+version = "0.1.0"
+authors = ["cos <cos>"]
+edition = "2018"
+
+[dependencies]
+anyhow = "1.0"
diff --git a/2020/rust/day01/src/main.rs b/2020/rust/day01/src/main.rs
new file mode 100644
index 0000000..38f25d2
--- /dev/null
+++ b/2020/rust/day01/src/main.rs
@@ -0,0 +1,72 @@
+use anyhow::Result;
+use std::env::args;
+use std::fs::File;
+use std::io::{BufRead, BufReader};
+use std::path::Path;
+
+const SUM: usize = 2020;
+
+fn read_input<T: AsRef<Path>>(filename: T) -> Result<Vec<usize>> {
+ let f = File::open(filename)?;
+ let reader = BufReader::new(f);
+
+ let values = reader.lines()
+ .map(|v| v.unwrap().parse::<usize>().unwrap()).collect();
+
+ Ok(values)
+}
+
+fn part1(input: &[usize]) -> Option<usize> {
+ for first in input {
+ for second in input {
+ if first + second == SUM {
+ return Some(first * second);
+ }
+ }
+ }
+
+ None
+}
+
+fn part2(input: &[usize]) -> Option<usize> {
+ for first in input {
+ for second in input {
+ for third in input {
+ if first + second + third == SUM {
+ return Some(first * second * third);
+ }
+ }
+ }
+ }
+
+ None
+}
+
+fn main() {
+ let filename = match args().nth(1) {
+ Some(f) => f,
+ None => {
+ eprintln!("Missing input filename");
+ std::process::exit(1);
+ },
+ };
+ match read_input(filename) {
+ Ok(input) => {
+ match part1(&input) {
+ Some(solution) => println!("Part1, product found to be: {}", solution),
+ None => {
+ eprintln!("Part1, no solution found");
+ std::process::exit(1);
+ }
+ };
+ match part2(&input) {
+ Some(solution) => println!("Part2, product found to be: {}", solution),
+ None => {
+ eprintln!("Part2, no solution found");
+ std::process::exit(1);
+ }
+ };
+ },
+ Err(err) => eprintln!("Could not read input: {}", err),
+ }
+}