Skip to content

Commit 0866e42

Browse files
committed
Day 2: Rock Paper Scissors
1 parent 5a80ab5 commit 0866e42

File tree

3 files changed

+71
-1
lines changed

3 files changed

+71
-1
lines changed

rs/src/day2.rs

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
use std::vec::Vec;
2+
3+
fn parse<'a, I, S>(lines: I) -> Vec<(u8, u8)>
4+
where
5+
I: IntoIterator<Item = &'a S>,
6+
S: AsRef<str> + 'a,
7+
{
8+
lines
9+
.into_iter()
10+
.filter_map(|line| {
11+
let mut iter = line.as_ref().split_ascii_whitespace();
12+
Some((
13+
iter.next()?.as_bytes().first()? - 64,
14+
iter.next()?.as_bytes().first()? - 87,
15+
))
16+
})
17+
.collect()
18+
}
19+
20+
fn score(left: u8, right: u8) -> u8 {
21+
(4 + right - left) % 3 * 3 + right
22+
}
23+
24+
pub fn part1<'a, I, S>(lines: I) -> u32
25+
where
26+
I: IntoIterator<Item = &'a S>,
27+
S: AsRef<str> + 'a,
28+
{
29+
parse(lines)
30+
.into_iter()
31+
.map(|(left, right)| score(left, right) as u32)
32+
.sum()
33+
}
34+
35+
pub fn part2<'a, I, S>(lines: I) -> u32
36+
where
37+
I: IntoIterator<Item = &'a S>,
38+
S: AsRef<str> + 'a,
39+
{
40+
parse(lines)
41+
.into_iter()
42+
.map(|(left, right)| score(left, 1 + (left + right) % 3) as u32)
43+
.sum()
44+
}
45+
46+
#[cfg(test)]
47+
mod tests {
48+
use super::*;
49+
use pretty_assertions::assert_eq;
50+
51+
static EXAMPLE: &[&str] = &["A Y", "B X", "C Z"];
52+
53+
#[test]
54+
fn part1_examples() {
55+
assert_eq!(15, part1(EXAMPLE));
56+
}
57+
58+
#[test]
59+
fn part2_examples() {
60+
assert_eq!(12, part2(EXAMPLE));
61+
}
62+
}

rs/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
pub mod day1;
2+
pub mod day2;

rs/src/main.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#[macro_use]
22
extern crate build_const;
33

4-
use aoc2022::day1;
4+
use aoc2022::{day1, day2};
55
use std::collections::HashSet;
66
use std::env;
77
use std::io;
@@ -21,5 +21,12 @@ fn main() -> io::Result<()> {
2121
println!();
2222
}
2323

24+
if args.is_empty() || args.contains(&2) {
25+
println!("Day 2");
26+
println!("{:?}", day2::part1(DAY2));
27+
println!("{:?}", day2::part2(DAY2));
28+
println!();
29+
}
30+
2431
Ok(())
2532
}

0 commit comments

Comments
 (0)