Skip to content

Commit

Permalink
day 01
Browse files Browse the repository at this point in the history
  • Loading branch information
HectorMalot committed Dec 1, 2023
1 parent 649add5 commit cf98607
Show file tree
Hide file tree
Showing 4 changed files with 127 additions and 0 deletions.
61 changes: 61 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,6 @@ doctest = false
test_lib = []

[dependencies]
itertools = "0.12.0"
pico-args = "0.5.0"
regex = "1.10.2"
54 changes: 54 additions & 0 deletions src/bin/01.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
advent_of_code::solution!(1);

use itertools::Itertools;

pub fn part_one(input: &str) -> Option<u32> {
let result = input
.lines()
.map(|line| line.chars().filter(|&c| c.is_numeric()).collect::<String>())
.filter(|line| line.len() >= 1)
.map(|line| {
line.chars().nth(0).unwrap().to_digit(10).unwrap() * 10
+ line.chars().last().unwrap().to_digit(10).unwrap()
})
.sum();
Some(result)
}

// list of written out numbers
const NUMBERS: [&str; 10] = [
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
];

#[allow(unused_variables)]
pub fn part_two(input: &str) -> Option<u32> {
let res = input
.lines()
// recursively replace all written out numbers with their digits
.map(|line| {
let mut line = line.to_string();
for (i, number) in NUMBERS.iter().enumerate() {
line = line.replace(number, format!("{}{}{}", number, i, number).as_str());
}
line
})
.join("\n");
part_one(&res)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_part_one() {
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(142));
}

#[test]
fn test_part_two() {
let result = part_two(&advent_of_code::template::read_filepath("examples", "01-b"));
assert_eq!(result, Some(281));
}
}
10 changes: 10 additions & 0 deletions src/template/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,16 @@ pub fn read_file(folder: &str, day: Day) -> String {
f.expect("could not open input file")
}

pub fn read_filepath(folder: &str, filename: &str) -> String {
let cwd = env::current_dir().unwrap();
let filepath = cwd
.join("data")
.join(folder)
.join(format!("{filename}.txt"));
let f = fs::read_to_string(filepath);
f.expect("could not open input file")
}

/// Creates the constant `DAY` and sets up the input and runner for each part.
#[macro_export]
macro_rules! solution {
Expand Down

0 comments on commit cf98607

Please sign in to comment.