Day 5 part 2

This commit is contained in:
Tyler Hallada 2018-12-20 00:46:36 -05:00
parent 20ab475034
commit 57d8189964
2 changed files with 23 additions and 0 deletions

View File

@ -3,16 +3,23 @@ extern crate regex;
use std::error::Error; use std::error::Error;
use std::fs::File; use std::fs::File;
use std::io::{BufRead, BufReader}; use std::io::{BufRead, BufReader};
use std::collections::HashMap;
use regex::Regex; use regex::Regex;
const INPUT: &str = "inputs/5.txt"; const INPUT: &str = "inputs/5.txt";
const UNITS: &str = "abcdefghijklmnopqrstuvwxyz";
pub fn solve_part1() -> Result<usize, Box<Error>> { pub fn solve_part1() -> Result<usize, Box<Error>> {
let polymer = read_polymer(INPUT)?; let polymer = read_polymer(INPUT)?;
Ok(reduce_polymer_completely(polymer).len()) Ok(reduce_polymer_completely(polymer).len())
} }
pub fn solve_part2() -> Result<usize, Box<Error>> {
let polymer = read_polymer(INPUT)?;
Ok(find_shortest_unit_eliminated_polymer(polymer))
}
fn read_polymer(filename: &str) -> Result<String, Box<Error>> { fn read_polymer(filename: &str) -> Result<String, Box<Error>> {
let file = File::open(filename)?; let file = File::open(filename)?;
let polymer = BufReader::new(file).lines().next().unwrap_or(Ok("".to_string())); let polymer = BufReader::new(file).lines().next().unwrap_or(Ok("".to_string()));
@ -39,6 +46,16 @@ fn reduce_polymer_completely(polymer: String) -> String {
} }
} }
fn find_shortest_unit_eliminated_polymer(polymer: String) -> usize {
let mut eliminated_unit_polymers = HashMap::new();
for unit in UNITS.chars() {
let test_polymer = polymer
.replace(unit, "")
.replace(unit.to_ascii_uppercase(), "");
eliminated_unit_polymers.insert(unit, reduce_polymer_completely(test_polymer).len());
}
*eliminated_unit_polymers.iter().min_by_key(|&(_, len)| len).unwrap().1
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
@ -67,4 +84,9 @@ mod tests {
fn reads_polymer() { fn reads_polymer() {
assert_eq!(read_polymer(TEST_INPUT).unwrap(), "dabAcCaCBAcCcaDA"); assert_eq!(read_polymer(TEST_INPUT).unwrap(), "dabAcCaCBAcCcaDA");
} }
#[test]
fn finds_shortest_unit_eliminated_polymer() {
assert_eq!(find_shortest_unit_eliminated_polymer("dabAcCaCBAcCcaDA".to_string()), 4);
}
} }

View File

@ -22,4 +22,5 @@ fn main() {
println!("{}", day4::solve_part2().unwrap()); println!("{}", day4::solve_part2().unwrap());
println!("Day 5:"); println!("Day 5:");
println!("{}", day5::solve_part1().unwrap()); println!("{}", day5::solve_part1().unwrap());
println!("{}", day5::solve_part2().unwrap());
} }