From fcaa7aed93f4a5a634a6673ba4784bd251a5151c Mon Sep 17 00:00:00 2001 From: Justin Worthe Date: Wed, 5 Dec 2018 07:20:12 +0200 Subject: Day 5: Mutating strings --- src/bin/day_5.rs | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) (limited to 'src/bin/day_5.rs') diff --git a/src/bin/day_5.rs b/src/bin/day_5.rs index 1129e3a..d689e34 100644 --- a/src/bin/day_5.rs +++ b/src/bin/day_5.rs @@ -3,16 +3,51 @@ use advent_of_code_2018::*; use std::error::Error; use std::path::PathBuf; +use std::cmp; // cargo watch -cs "cargo run --release --bin day_5" fn main() -> Result<(), Box> { let input = read_file(&PathBuf::from("inputs/5.txt"))?; - println!("Input: {:?}", input); + //println!("Input: {:?}", input); + let polymer = { + let mut polymer: Vec = input[0].chars().collect(); + reduce(&mut polymer); + polymer + }; + println!("Base length after reducing: {}", polymer.len()); + let mut min_length = polymer.len(); + for c in "abcdefghijklmnopqrstuvwxyz".chars() { + let mut polymer_without_char = polymer.clone(); + polymer_without_char.retain(|x| x.to_ascii_lowercase() != c); + reduce(&mut polymer_without_char); + min_length = cmp::min(min_length, polymer_without_char.len()); + } + + println!("Minimum length found: {}", min_length); Ok(()) } + + +fn reduce(polymer: &mut Vec) { + let mut had_reductions = true; + while had_reductions { + had_reductions = false; + + for i in 0..polymer.len()-1 { + if polymer[i].to_ascii_lowercase() == polymer[i+1].to_ascii_lowercase() && polymer[i] != polymer[i+1] { + had_reductions = true; + polymer.remove(i+1); + polymer.remove(i); + + // break isn't efficient, but does prevent indexing issues after removing + break; + } + } + } +} -- cgit v1.2.3