From f44158d941198d175c26ef8f74e80e4d4d0fa7a2 Mon Sep 17 00:00:00 2001 From: cos Date: Tue, 1 Dec 2020 08:01:25 +0100 Subject: Add day01, 2020 --- 2020/rust/day01/Cargo.toml | 8 +++++ 2020/rust/day01/src/main.rs | 72 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 2020/rust/day01/Cargo.toml create mode 100644 2020/rust/day01/src/main.rs (limited to '2020/rust/day01') 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 "] +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>(filename: T) -> Result> { + let f = File::open(filename)?; + let reader = BufReader::new(f); + + let values = reader.lines() + .map(|v| v.unwrap().parse::().unwrap()).collect(); + + Ok(values) +} + +fn part1(input: &[usize]) -> Option { + for first in input { + for second in input { + if first + second == SUM { + return Some(first * second); + } + } + } + + None +} + +fn part2(input: &[usize]) -> Option { + 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), + } +} -- cgit v1.2.3