day(01): add solution
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
c692f1f510
commit
b87e0ac219
3 changed files with 78 additions and 0 deletions
4
samples/day01_1.txt
Normal file
4
samples/day01_1.txt
Normal file
|
@ -0,0 +1,4 @@
|
|||
1abc2
|
||||
pqr3stu8vwx
|
||||
a1b2c3d4e5f
|
||||
treb7uchet
|
7
samples/day01_2.txt
Normal file
7
samples/day01_2.txt
Normal file
|
@ -0,0 +1,7 @@
|
|||
two1nine
|
||||
eightwothree
|
||||
abcone2threexyz
|
||||
xtwone3four
|
||||
4nineeightseven2
|
||||
zoneight234
|
||||
7pqrstsixteen
|
67
src/bin/day01.rs
Normal file
67
src/bin/day01.rs
Normal file
|
@ -0,0 +1,67 @@
|
|||
use aoc_2023::*;
|
||||
|
||||
type Output1 = i32;
|
||||
type Output2 = Output1;
|
||||
|
||||
const NUMBERS: [&str; 9] = [
|
||||
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
|
||||
];
|
||||
|
||||
struct Day01 {
|
||||
lines: Vec<String>,
|
||||
}
|
||||
impl Solution<Output1, Output2> for Day01 {
|
||||
fn new<P: AsRef<Path>>(pathname: P) -> Self {
|
||||
Self {
|
||||
lines: file_to_lines(pathname),
|
||||
}
|
||||
}
|
||||
|
||||
fn part_1(&mut self) -> Output1 {
|
||||
self.lines
|
||||
.iter()
|
||||
.map(|line| {
|
||||
let digits = line.chars().filter_map(|c| c.to_digit(10)).collect_vec();
|
||||
|
||||
(10 * digits.first().unwrap() + digits.last().unwrap()) as i32
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
fn part_2(&mut self) -> Output2 {
|
||||
self.lines
|
||||
.iter()
|
||||
.map(|line| {
|
||||
let mut digits: Vec<i32> = vec![];
|
||||
|
||||
for (i, c) in line.chars().enumerate() {
|
||||
if let Some(d) = c.to_digit(10) {
|
||||
digits.push(d as i32);
|
||||
}
|
||||
|
||||
if let Some(d) = NUMBERS
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find_map(|(n, nstr)| {
|
||||
if line[i..].starts_with(nstr) {
|
||||
Some(n as i32 + 1)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
{
|
||||
digits.push(d)
|
||||
}
|
||||
}
|
||||
|
||||
10 * digits.first().unwrap() + digits.last().unwrap()
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
Day01::main()
|
||||
}
|
||||
|
||||
test_sample!(day_01, Day01, 142, 281);
|
Loading…
Reference in a new issue