2018: day05: part 2
This commit is contained in:
parent
af39de85b0
commit
cef2fba255
|
@ -1,17 +1,24 @@
|
||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
use super::Result;
|
use super::Result;
|
||||||
|
|
||||||
const INPUT: &str = include_str!("../input/day05.txt");
|
const INPUT: &str = include_str!("../input/day05.txt");
|
||||||
|
|
||||||
pub fn run() -> Result<()> {
|
pub fn run() -> Result<()> {
|
||||||
println!("part 1: {}", part1(INPUT));
|
println!("part 1: {}", part1(INPUT));
|
||||||
|
println!("part 2: {}", part2(INPUT));
|
||||||
|
|
||||||
Ok(())
|
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()
|
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 {
|
fn collapse(input: &str) -> String {
|
||||||
let mut res = String::with_capacity(input.len());
|
let mut res = String::with_capacity(input.len());
|
||||||
|
|
||||||
|
@ -22,7 +29,7 @@ fn collapse(input: &str) -> String {
|
||||||
match last {
|
match last {
|
||||||
Some(elem) => {
|
Some(elem) => {
|
||||||
// if same type but different polarity
|
// 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
|
// drop both elem and next
|
||||||
last = res.pop();
|
last = res.pop();
|
||||||
} else {
|
} else {
|
||||||
|
@ -50,6 +57,19 @@ fn part1(input: &str) -> usize {
|
||||||
res.len()
|
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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
@ -65,4 +85,14 @@ mod tests {
|
||||||
fn part1_real() {
|
fn part1_real() {
|
||||||
assert_eq!(part1(INPUT), 10638);
|
assert_eq!(part1(INPUT), 10638);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn part2_provided() {
|
||||||
|
assert_eq!(part2(PROVIDED), 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn part2_real() {
|
||||||
|
assert_eq!(part2(INPUT), 4944);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue