xenua
1 year ago
4 changed files with 1085 additions and 0 deletions
@ -0,0 +1,7 @@
@@ -0,0 +1,7 @@
|
||||
# This file is automatically @generated by Cargo. |
||||
# It is not intended for manual editing. |
||||
version = 3 |
||||
|
||||
[[package]] |
||||
name = "a-trebuchet" |
||||
version = "0.1.0" |
@ -0,0 +1,8 @@
@@ -0,0 +1,8 @@
|
||||
[package] |
||||
name = "a-trebuchet" |
||||
version = "0.1.0" |
||||
edition = "2021" |
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html |
||||
|
||||
[dependencies] |
@ -0,0 +1,70 @@
@@ -0,0 +1,70 @@
|
||||
use std::char; |
||||
|
||||
static INPUT: &str = include_str!("input"); |
||||
|
||||
fn main() { |
||||
println!("part 1's result is: {:?}", part1()); |
||||
println!("part 2's result is: {:?}", part2()); |
||||
} |
||||
|
||||
fn part1() -> usize { |
||||
sum_them_up(INPUT.lines()) |
||||
} |
||||
|
||||
fn sum_them_up(input: impl Iterator<Item = impl AsRef<str>>) -> usize { |
||||
input |
||||
.map(|line| { |
||||
let d1 = line |
||||
.as_ref() |
||||
.chars() |
||||
.find(|c| c.is_ascii_digit()) |
||||
.expect("every line has at least one digit"); |
||||
let d2 = line |
||||
.as_ref() |
||||
.chars() |
||||
.rev() |
||||
.find(|c| c.is_ascii_digit()) |
||||
.expect("every line still has at least one digit"); |
||||
format!("{}{}", d1, d2) |
||||
.parse::<usize>() |
||||
.expect("two digits should be parsable as int") |
||||
}) |
||||
.sum() |
||||
} |
||||
|
||||
static CHECK_MAP: [(&str, char); 9] = [ |
||||
("one", '1'), |
||||
("two", '2'), |
||||
("three", '3'), |
||||
("four", '4'), |
||||
("five", '5'), |
||||
("six", '6'), |
||||
("seven", '7'), |
||||
("eight", '8'), |
||||
("nine", '9'), |
||||
]; |
||||
|
||||
fn extract_digits(line: &str) -> String { |
||||
let mut buf = String::new(); |
||||
let mut out = String::new(); |
||||
|
||||
for c in line.chars() { |
||||
if c.is_ascii_digit() { |
||||
out.push(c); |
||||
} else { |
||||
buf.push(c); |
||||
if let Some(digit) = CHECK_MAP |
||||
.into_iter() |
||||
.find_map(|(pat, dig)| Some(dig).filter(|_| buf.ends_with(pat))) |
||||
{ |
||||
out.push(digit); |
||||
} |
||||
} |
||||
} |
||||
|
||||
out |
||||
} |
||||
|
||||
fn part2() -> usize { |
||||
sum_them_up(INPUT.lines().map(extract_digits)) |
||||
} |
Loading…
Reference in new issue