summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorJustin Worthe <justin@worthe-it.co.za>2018-12-05 07:20:12 +0200
committerJustin Worthe <justin@worthe-it.co.za>2018-12-05 07:20:12 +0200
commitfcaa7aed93f4a5a634a6673ba4784bd251a5151c (patch)
tree97168c588a621bb52d70aa7a4d9b45ca62724dd1 /src
parentf2efadfb17c7c47d1a501117b5f31c07b01567a3 (diff)
Day 5: Mutating strings
Diffstat (limited to 'src')
-rw-r--r--src/bin/day_5.rs37
1 files changed, 36 insertions, 1 deletions
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<Error>> {
let input = read_file(&PathBuf::from("inputs/5.txt"))?;
- println!("Input: {:?}", input);
+ //println!("Input: {:?}", input);
+ let polymer = {
+ let mut polymer: Vec<char> = 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<char>) {
+ 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;
+ }
+ }
+ }
+}