xenua 1 year ago
parent
commit
1d48375878
Signed by: xenua
GPG Key ID: 8F93B68BD37255B8
  1. 7
      a-trebuchet/Cargo.lock
  2. 8
      a-trebuchet/Cargo.toml
  3. 1000
      a-trebuchet/src/input
  4. 70
      a-trebuchet/src/main.rs

7
a-trebuchet/Cargo.lock generated

@ -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"

8
a-trebuchet/Cargo.toml

@ -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]

1000
a-trebuchet/src/input

File diff suppressed because it is too large Load Diff

70
a-trebuchet/src/main.rs

@ -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…
Cancel
Save