Add day 2 solution.
This commit is contained in:
parent
e04df4b548
commit
5b3a5d829d
7
2022/day02/Cargo.lock
generated
Normal file
7
2022/day02/Cargo.lock
generated
Normal 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
8
2022/day02/Cargo.toml
Normal 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
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
58
2022/day02/src/main.rs
Normal 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,
|
||||||
|
};
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user