day05 both parts fast

This commit is contained in:
Johannes Schaefer
2018-12-05 10:49:52 +01:00
parent 6e92d937a9
commit 40957e1252
2 changed files with 37 additions and 26 deletions

File diff suppressed because one or more lines are too long

View File

@@ -2,7 +2,7 @@ use utils;
pub fn task1() {
let mut input = utils::read_file("input/day05.txt");
input = reduce(input);
input = reduce(input.as_str());
println!("resulting polymer: {}", input); //11591 too high
println!("RESULT: {}", input.len());
@@ -16,36 +16,47 @@ pub fn task2() {
(
c,
reduce(
input
&input
.chars()
.filter(|ch| ch.to_lowercase().next().unwrap() != c)
.collect(),
),
.collect::<String>(),
).len(),
)
}).max_by_key(|it| it.1.len())
}).min_by_key(|it| it.1)
.unwrap();
println!("Best: {} (length {})", best.0, best.1.len()); // 11184 too high
println!("Best: {} (length {})", best.0, best.1); // 11184 too high, 4328 too low
}
fn reduce(mut input: String) -> String {
let mut go_on = true;
while go_on {
go_on = false;
let mut index = 0;
while index < input.len() - 1 {
let a = input.chars().nth(index).unwrap();
let b = input.chars().nth(index + 1).unwrap();
if a.is_lowercase() && b.is_uppercase() && a == b.to_lowercase().next().unwrap()
|| b.is_lowercase() && a.is_uppercase() && b == a.to_lowercase().next().unwrap()
{
// println!("{} and {} match", a, b);
input.remove(index);
input.remove(index);
go_on = true;
}
index += 1;
}
}
fn reduce(input: &str) -> String {
input
.chars()
.fold(Vec::<char>::new(), |mut stack, c| {
let last: Option<char>;
{
if let Some(c) = stack.last() {
last = Some(*c)
} else {
last = None
}
}
if let Some(last) = last {
if c.is_lowercase()
&& last.is_uppercase()
&& c == last.to_lowercase().next().unwrap()
|| last.is_lowercase()
&& c.is_uppercase()
&& last == c.to_lowercase().next().unwrap()
{
stack.pop();
} else {
stack.push(c);
}
} else {
stack.push(c);
}
stack
}).iter()
.collect()
}