feat: day 1!

This commit is contained in:
Ashhhleyyy 2023-12-02 02:11:13 +00:00
parent 217944d106
commit 277a25bc8f
Signed by: ash
GPG key ID: 83B789081A0878FB
3 changed files with 1090 additions and 0 deletions

1000
.aoc-cache/1.txt Normal file

File diff suppressed because it is too large Load diff

83
src/bin/day_1.rs Normal file
View file

@ -0,0 +1,83 @@
use aoc_2022::prelude::*;
type Input = Vec<String>;
fn parse(s: &str) -> Result<Input> {
Ok(s.lines()
.map(ToOwned::to_owned)
.filter(|line| line.len() != 0)
.collect::<Vec<_>>())
}
const DIGITS: [(&str, &str); 18] = [
("one", "1"),
("two", "2"),
("three", "3"),
("four", "4"),
("five", "5"),
("six", "6"),
("seven", "7"),
("eight", "8"),
("nine", "9"),
("1", "1"),
("2", "2"),
("3", "3"),
("4", "4"),
("5", "5"),
("6", "6"),
("7", "7"),
("8", "8"),
("9", "9"),
];
#[aoc(day = 1, parse = parse, test_cases = ["day_1.txt"])]
fn day_1(mut input: Input) -> Result<()> {
// Part 1
println!("Part one: ");
let mut total = 0;
for line in &input {
let digits = line.chars()
.filter(|c| c.is_digit(10))
.collect::<Vec<_>>();
if digits.len() == 0 {
continue;
}
let first_digit = digits[0];
let last_digit = digits[digits.len() - 1];
let value = format!("{first_digit}{last_digit}")
.parse::<u32>()
.expect("digits to be digits");
total += value;
}
println!("{total}");
// Part 2
println!("Part two: ");
let mut total = 0;
for line in &input {
let mut first_digit = None;
let mut last_digit = None;
for i in 0..(line.len()) {
for (word, digit) in DIGITS {
if i + word.len() <= line.len() {
if &line[i..(i+word.len())] == word {
if first_digit.is_none() {
first_digit = Some(digit.to_owned());
}
last_digit = Some(digit.to_owned());
break;
}
}
}
}
let (first_digit, last_digit) = (first_digit.expect("there to be a first digit"), last_digit.expect("there to be a last digit"));
let value = format!("{first_digit}{last_digit}")
.parse::<u32>()
.expect("digits to be digits");
println!("{value}");
total += value;
}
println!("{total}");
Ok(())
}

7
test_cases/day_1.txt Normal file
View file

@ -0,0 +1,7 @@
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen