This commit is contained in:
2018-12-17 11:51:00 +01:00
parent e6cd5a020d
commit 993bc6fd42
4 changed files with 93 additions and 2 deletions

4
2018/05/Cargo.lock generated Normal file
View File

@@ -0,0 +1,4 @@
[[package]]
name = "day-05"
version = "0.1.0"

1
2018/05/example-01.txt Normal file
View File

@@ -0,0 +1 @@
dabAcCaCBAcCcaDA

1
2018/05/input.txt Normal file

File diff suppressed because one or more lines are too long

View File

@@ -1,3 +1,88 @@
fn main() {
println!("Hello, world!");
use std::collections::HashSet;
use std::io::{self, BufRead};
fn react<I>(polymer: I) -> String
where
I: Iterator<Item = char>,
{
let mut input = polymer.collect::<Vec<char>>();
loop {
let remove = input
.windows(2)
.enumerate()
.filter(|(_, chars)| {
assert!(chars.len() == 2);
let left = chars[0];
let right = if chars[1].is_uppercase() {
chars[1].to_ascii_lowercase()
} else {
chars[1].to_ascii_uppercase()
};
left == right
})
.map(|(i, _)| i)
.scan(None, |state, i| {
if let Some(n) = state {
let prev = *n + 1;
*n = i;
if prev != i {
Some(i)
} else {
None
}
} else {
*state = Some(i);
Some(i)
}
})
.collect::<Vec<_>>();
if remove.is_empty() {
break;
}
input = input
.into_iter()
.enumerate()
.filter(|(i, _)| !remove.contains(i) && !remove.contains(&(i - 1)))
.map(|(_, c)| c)
.collect::<Vec<_>>();
}
input.into_iter().collect::<String>()
}
fn main() {
let input = io::stdin()
.lock()
.lines()
.filter_map(Result::ok)
.collect::<String>();
println!("part.one={}", react(input.chars()).len());
let units = input
.chars()
.map(|c| c.to_ascii_lowercase())
.collect::<HashSet<_>>();
let min = units
.into_iter()
.map(|u| {
let stream = input
.chars()
.filter(|c| *c != u && *c != u.to_ascii_uppercase());
react(stream).len()
})
.min()
.expect("failed to find shortest polymer");
println!("part.two={}", min);
}