summaryrefslogtreecommitdiff
path: root/src/bin/day_5.rs
blob: 2b24d4c32ef6af09ed344017057b76a052fa5068 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
extern crate advent_of_code_2018;
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);
    let polymer = {
        let mut polymer: Vec<char> = input[0].chars().collect();
        reduce(&mut polymer);
        polymer
    };

    debug!(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());
    }

    debug!(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;
            }
        }
    }
}