From e534f1013463f1214631374bc9d467e938aa6567 Mon Sep 17 00:00:00 2001 From: David Ashby Date: Fri, 2 Dec 2022 07:46:29 -0500 Subject: [PATCH] day two --- 01/main.rs | 2 +- 02/main.rs | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++ main.rs.tmpl | 2 +- 3 files changed, 72 insertions(+), 2 deletions(-) create mode 100644 02/main.rs diff --git a/01/main.rs b/01/main.rs index 7788c29..3d0f432 100644 --- a/01/main.rs +++ b/01/main.rs @@ -14,7 +14,7 @@ fn main() { println!( "p1: {}ms, p2: {}ms", part_one_duration.as_millis(), - part_two_duration.as_millis() + (part_two_duration - part_one_duration).as_millis() ); } diff --git a/02/main.rs b/02/main.rs new file mode 100644 index 0000000..5e2748a --- /dev/null +++ b/02/main.rs @@ -0,0 +1,70 @@ +#![allow(dead_code)] +use std::fs::File; +use std::io; +use std::io::BufRead; +use std::path::Path; +use std::time::Instant; + +fn main() { + let now = Instant::now(); + part_one(); + let part_one_duration = now.elapsed(); + part_two(); + let part_two_duration = now.elapsed(); + println!( + "p1: {}ms, p2: {}ms", + part_one_duration.as_millis(), + (part_two_duration - part_one_duration).as_millis() + ); +} + +fn read_lines

(filename: P) -> io::Result>> +where + P: AsRef, +{ + // note that this discards a final newline + let file = File::open(filename)?; + Ok(io::BufReader::new(file).lines()) +} + +fn part_one() { + if let Ok(lines) = read_lines("./inputs/input") { + let mut score = 0; + for line in lines { + let l = line.unwrap(); + let them = l.chars().nth(0).unwrap() as u32 - 64; + let you = l.chars().nth(2).unwrap() as u32 - 87; + score += you; + // 1 is Rock + // 2 is Paper + // 3 is Scissors + if you == them { + score += 3; + } else if them == 1 && you == 2 { + score += 6 + } else if them == 2 && you == 3 { + score += 6 + } else if them == 3 && you == 1 { + score += 6 + } + } + println!("{}", score) + } +} + +fn part_two() { + if let Ok(lines) = read_lines("./inputs/input") { + let mut score = 0; + for line in lines { + let l = line.unwrap(); + let them = l.chars().nth(0).unwrap() as u32 - 64; + let outcome = l.chars().nth(2).unwrap() as u32 - 87; + // 1 is Rock / you lose + // 2 is Paper / you tie + // 3 is Scissors / you win + // compute what you throw plus the score of the round + score += ((them + outcome) % 3) + 1 + (outcome - 1) * 3; + } + println!("{}", score) + } +} diff --git a/main.rs.tmpl b/main.rs.tmpl index 84da41e..5f73851 100644 --- a/main.rs.tmpl +++ b/main.rs.tmpl @@ -14,7 +14,7 @@ fn main() { println!( "p1: {}ms, p2: {}ms", part_one_duration.as_millis(), - part_two_duration.as_millis() + (part_two_duration - part_one_duration).as_millis() ); }