1
0

Optimized Day 2 part 2

This commit is contained in:
Ishan Jain 2022-12-02 12:11:26 +05:30
parent 468b1c142a
commit c658d2b1cf
Signed by: ishan
GPG Key ID: 0506DB2A1CC75C27

View File

@ -1,31 +1,30 @@
#![feature(test)]
extern crate test;
const INPUTS: [&str; 2] = [ const INPUTS: [&str; 2] = [
include_str!("../inputs/sample.txt"), include_str!("../inputs/sample.txt"),
include_str!("../inputs/input.txt"), include_str!("../inputs/input.txt"),
]; ];
fn parse(input: &'static str) -> Vec<(Move, Outcome)> { fn parse(input: &'static str) -> impl Iterator<Item = (Move, Outcome)> {
input input.trim().lines().map(|set| {
.trim() let mut set = set.chars();
.lines() let (a, b) = (set.next().unwrap(), set.nth(1).unwrap());
.map(|set| {
let set = set.trim();
let (a, b) = set.split_at(1);
let x = match a.trim() { let x = match a {
"A" => Move::Rock, 'A' => Move::Rock,
"B" => Move::Paper, 'B' => Move::Paper,
"C" => Move::Scissors, 'C' => Move::Scissors,
_ => unreachable!(), _ => unreachable!(),
}; };
let y = match b.trim() { let y = match b {
"X" => Outcome::X, 'X' => Outcome::X,
"Y" => Outcome::Y, 'Y' => Outcome::Y,
"Z" => Outcome::Z, 'Z' => Outcome::Z,
_ => unreachable!(), _ => unreachable!(),
}; };
(x, y) (x, y)
}) })
.collect()
} }
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
@ -42,7 +41,8 @@ enum Outcome {
Z = 6, Z = 6,
} }
fn calc_move(d1: Outcome, m1: Move) -> Move { #[inline]
const fn calc_move(d1: Outcome, m1: Move) -> Move {
match (d1, m1) { match (d1, m1) {
(Outcome::X, Move::Rock) => Move::Scissors, (Outcome::X, Move::Rock) => Move::Scissors,
(Outcome::X, Move::Paper) => Move::Rock, (Outcome::X, Move::Paper) => Move::Rock,
@ -57,13 +57,27 @@ fn calc_move(d1: Outcome, m1: Move) -> Move {
fn main() { fn main() {
for input in INPUTS.iter() { for input in INPUTS.iter() {
let output = parse(input); let output = parse(input);
let mut score = 0; let score = solution(output);
for (a, b) in output {
score += b as i32;
score += calc_move(b, a) as i32;
}
println!("{:?}", score); println!("{:?}", score);
} }
} }
fn solution(input: impl Iterator<Item = (Move, Outcome)>) -> i32 {
let mut score = 0;
for (a, b) in input {
score += b as i32;
score += calc_move(b, a) as i32;
}
score
}
#[bench]
fn solution_bench(b: &mut test::Bencher) {
b.iter(|| {
let input = parse(INPUTS[1]);
let result = solution(input);
test::black_box(result);
})
}