This commit is contained in:
2024-10-29 11:27:33 +01:00
parent 04ae9d47ef
commit 1979821775
4 changed files with 385 additions and 0 deletions

20
y2015/src/bin/d8.rs Normal file
View File

@@ -0,0 +1,20 @@
use std::fs;
use y2015::days::d8;
fn main() {
part1();
part2();
}
fn part1() {
let root = env!("CARGO_MANIFEST_DIR");
let content = fs::read_to_string(format!("{root}/resources/8_input.txt")).unwrap();
println!("{}", d8::process_part1(&content));
}
fn part2() {
let root = env!("CARGO_MANIFEST_DIR");
let content = fs::read_to_string(format!("{root}/resources/8_input.txt")).unwrap();
println!("{}", d8::process_part2(&content));
}

64
y2015/src/days/d8.rs Normal file
View File

@@ -0,0 +1,64 @@
pub fn process_part1(input: &str) -> u32 {
let slashed_quote = r#"\""#;
let double_slash = r#"\\"#;
let escape = r#"\x"#;
let num_char_string_code: u32 = input.lines().map(|line| line.len() as u32).sum();
let num_char_mem: u32 = input
.lines()
.map(|line| {
// first remove \\ and \" and replace with single random character so they count for
// one instead of 2
let line = line.to_string();
let line = line.replace(double_slash, "x");
let line = line.replace(slashed_quote, "x");
// only count what's in the quotes
let inner_quote_length = line.len() - 2;
let num_ascii_codes = line.matches(escape).count() * 3;
(inner_quote_length - num_ascii_codes) as u32
})
.sum();
num_char_string_code - num_char_mem
}
pub fn process_part2(input: &str) -> u32 {
let slashed_quote = r#"\""#;
let double_slash = r#"\\"#;
let escape = r#"\x"#;
let num_char_string_code: u32 = input.lines().map(|line| line.len() as u32).sum();
let num_char_encode: u32 = input
.lines()
.map(|line| {
let line = line.to_string();
let line = line.replace(double_slash, "xxxx");
let line = line.replace(slashed_quote, "xxxx");
let line = line.replace(escape, "xxx");
line.len() as u32 + 4
})
.sum();
num_char_encode - num_char_string_code
}
#[cfg(test)]
mod tests_8 {
use super::*;
const INPUT: &str = r#"""
"abc"
"aaa\"aaa"
"\x27"
"#;
#[test]
fn it_works() {
let result = process_part1(INPUT);
assert_eq!(result, 12);
}
#[test]
fn part2() {
let result = process_part2(INPUT);
assert_eq!(result, 19);
}
}

View File

@@ -5,3 +5,4 @@ pub mod d4;
pub mod d5;
pub mod d6;
pub mod d7;
pub mod d8;