Add day 2 solution.

This commit is contained in:
Anna Rose 2024-02-15 15:34:35 +00:00
parent e04df4b548
commit 5b3a5d829d
4 changed files with 2573 additions and 0 deletions

7
2022/day02/Cargo.lock generated Normal file
View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "day02"
version = "0.1.0"

8
2022/day02/Cargo.toml Normal file
View File

@ -0,0 +1,8 @@
[package]
name = "day02"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

2500
2022/day02/input.txt Normal file

File diff suppressed because it is too large Load Diff

58
2022/day02/src/main.rs Normal file
View File

@ -0,0 +1,58 @@
use std::io;
use std::io::prelude::*;
use std::fs::File;
fn read_lines(filename: &str) -> io::Result<io::Lines<io::BufReader<File>>> {
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
fn print_step(step: i8, value: u64) {
println!("Step {} solution: {}", step, value);
}
fn main() -> Result<(), io::Error> {
let mut score1: u64 = 0;
let mut score2: u64 = 0;
for line in read_lines("input.txt")? {
let text = line?;
let opp = parse_move(text.chars().nth(0).unwrap());
score1 += step1(opp, text.chars().nth(2).unwrap());
score2 += step2(opp, text.chars().nth(2).unwrap());
}
print_step(1, score1);
print_step(2, score2);
Ok(())
}
fn step1(opp: i8, text: char) -> u64 {
let me = parse_move(text);
return match me - opp {
1 | -2 => me + 6,
0 => me + 3,
-1 | 2 => me,
_ => panic!("Received impossible result in a match."),
} as u64;
}
fn step2(opp: i8, text: char) -> u64 {
return match text {
'X' => ((opp + 4) % 3) + 1,
'Y' => opp + 3,
'Z' => (opp % 3) + 7,
_ => panic!("Received impossible strategy code."),
} as u64;
}
// Parses the second command in the input incorrectly.
fn parse_move(x: char) -> i8 {
return match x {
'A' | 'X' => 1,
'B' | 'Y' => 2,
'C' | 'Z' => 3,
_ => 0,
};
}