1
0
Fork 0
advent-of-code/2018/day5/src/main.rs

78 lines
2.2 KiB
Rust
Raw Normal View History

2018-12-08 09:25:42 -05:00
#[macro_use]
extern crate lazy_static;
extern crate regex;
use regex::Regex;
use std::fs::File;
use std::io::{BufRead, BufReader};
fn calc_remaining_monomers(polymers: &str) -> usize {
lazy_static! {
static ref POLYMER: Regex = Regex::new(r"aA|Aa|bB|Bb|cC|Cc|dD|Dd|eE|Ee|fF|Ff|gG|Gg|hH|Hh|iI|Ii|jJ|Jj|kK|Kk|lL|Ll|mM|Mm|nN|Nn|oO|Oo|pP|Pp|qQ|Qq|rR|Rr|sS|Ss|tT|Tt|uU|Uu|vV|Vv|wW|Ww|xX|Xx|yY|Yy|zZ|Zz").unwrap();
}
if POLYMER.is_match(polymers) {
calc_remaining_monomers(&POLYMER.replace_all(polymers, ""))
} else {
polymers.len()
}
}
2019-01-03 22:06:21 -05:00
fn calc_most_significant_monomer(polymers: &str) -> usize {
2018-12-13 15:00:47 -05:00
let chars: Vec<char> = (b'a'..=b'z').map(char::from).collect();
2018-12-08 09:25:42 -05:00
let mut min_letter = 'a';
let mut min_length = polymers.len();
for mychar in chars.iter() {
let regex_str = format!(r"{}|{}", mychar, mychar.to_uppercase());
let r = Regex::new(regex_str.as_str()).unwrap();
let new_len = react_monomer(polymers, r);
if new_len < min_length {
min_letter = *mychar;
min_length = new_len;
}
}
2018-12-13 15:00:47 -05:00
println!(
"minimum new length {} found by replacing {}",
min_length, min_letter
);
2019-01-03 22:06:21 -05:00
min_length
2018-12-08 09:25:42 -05:00
}
fn react_monomer(polymers: &str, r: Regex) -> usize {
if r.is_match(polymers) {
react_monomer(&r.replace_all(polymers, ""), r)
} else {
calc_remaining_monomers(polymers)
}
}
fn main() {
let lines: Vec<String> = BufReader::new(File::open("input").unwrap())
.lines()
.map(|line| line.unwrap())
.collect();
let polymers = lines.get(0).unwrap().as_str();
let reacted_len = calc_remaining_monomers(polymers);
println!("remaining polymers has size {}", reacted_len);
calc_most_significant_monomer(polymers);
}
2019-01-03 22:06:21 -05:00
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_one() {
let polymers = "dabAcCaCBAcCcaDA";
let reacted_len = calc_remaining_monomers(polymers);
assert_eq!(reacted_len, 10);
}
#[test]
fn test_part_two() {
let polymers = "dabAcCaCBAcCcaDA";
let min_len = calc_most_significant_monomer(polymers);
assert_eq!(min_len, 4);
}
}