2018: day05: part 2

This commit is contained in:
Antoine Martin 2019-11-22 17:45:58 +01:00
parent af39de85b0
commit cef2fba255

View file

@ -1,17 +1,24 @@
use std::collections::HashSet;
use super::Result;
const INPUT: &str = include_str!("../input/day05.txt");
pub fn run() -> Result<()> {
println!("part 1: {}", part1(INPUT));
println!("part 2: {}", part2(INPUT));
Ok(())
}
fn same_type(a: char, b: char) -> bool {
fn same_type(a: &char, b: &char) -> bool {
a.to_ascii_lowercase() == b.to_ascii_lowercase()
}
fn remove_type(input: &str, c: &char) -> String {
input.chars().filter(|ch| !same_type(c, ch)).collect()
}
fn collapse(input: &str) -> String {
let mut res = String::with_capacity(input.len());
@ -22,7 +29,7 @@ fn collapse(input: &str) -> String {
match last {
Some(elem) => {
// if same type but different polarity
if same_type(elem, next) && elem != next {
if same_type(&elem, &next) && elem != next {
// drop both elem and next
last = res.pop();
} else {
@ -50,6 +57,19 @@ fn part1(input: &str) -> usize {
res.len()
}
fn part2(input: &str) -> usize {
let mut set = HashSet::new();
for c in input.chars() {
set.insert(c.to_ascii_lowercase());
}
set.iter()
.map(|c| collapse(&remove_type(input, c)).len())
.min()
.unwrap()
}
#[cfg(test)]
mod tests {
use super::*;
@ -65,4 +85,14 @@ mod tests {
fn part1_real() {
assert_eq!(part1(INPUT), 10638);
}
#[test]
fn part2_provided() {
assert_eq!(part2(PROVIDED), 4);
}
#[test]
fn part2_real() {
assert_eq!(part2(INPUT), 4944);
}
}