From 9abb60642c5c7ea61f26fd9690a2f265182ddf4d Mon Sep 17 00:00:00 2001 From: Wesley Moore Date: Sat, 9 Dec 2017 14:10:47 +1000 Subject: [PATCH] Add day 4 part 2 solution --- 2017/day/4/src/main.rs | 51 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/2017/day/4/src/main.rs b/2017/day/4/src/main.rs index a5c0089..9b22ac1 100644 --- a/2017/day/4/src/main.rs +++ b/2017/day/4/src/main.rs @@ -11,7 +11,17 @@ fn main() { .filter(|valid| *valid == true) .count(); - println!("{}", valid); + println!("Part 1: {}", valid); + + let file = File::open("input").expect("unable to open input file"); + let reader = BufReader::new(file); + + let valid = reader.lines() + .map(|line| passphrase_is_valid_part2(&line.unwrap())) + .filter(|valid| *valid == true) + .count(); + + println!("Part 2: {}", valid); } fn passphrase_is_valid(passphrase: &str) -> bool { @@ -19,6 +29,15 @@ fn passphrase_is_valid(passphrase: &str) -> bool { !passphrase.split_whitespace().any(|word| seen.insert(word) == false) } +fn passphrase_is_valid_part2(passphrase: &str) -> bool { + let mut seen = HashSet::new(); + !passphrase.split_whitespace().any(|word| { + let mut sorted_chars = word.chars().collect::>(); + sorted_chars.sort(); + seen.insert(sorted_chars) == false + }) +} + // aa bb cc dd ee is valid. #[test] fn test_example1() { @@ -36,3 +55,33 @@ fn test_example2() { fn test_example3() { assert_eq!(passphrase_is_valid("aa bb cc dd aaa"), true) } + +// abcde fghij is a valid passphrase. +#[test] +fn test_example1_part2() { + assert_eq!(passphrase_is_valid_part2("abcde fghij "), true) +} + +// abcde xyz ecdab is not valid - the letters from the third word can be rearranged to form the first word. +#[test] +fn test_example2_part2() { + assert_eq!(passphrase_is_valid_part2("abcde xyz ecdab"), false) +} + +// a ab abc abd abf abj is a valid passphrase, because all letters need to be used when forming another word. +#[test] +fn test_example3_part2() { + assert_eq!(passphrase_is_valid_part2("a ab abc abd abf abj"), true) +} + +// iiii oiii ooii oooi oooo is valid. +#[test] +fn test_example4_part2() { + assert_eq!(passphrase_is_valid_part2("iiii oiii ooii oooi oooo"), true) +} + +// oiii ioii iioi iiio is not valid - any of these words can be rearranged to form any other word. +#[test] +fn test_example5_part2() { + assert_eq!(passphrase_is_valid_part2("oiii ioii iioi iiio"), false) +}