Day 2, 3, and 4.

This commit is contained in:
2017-12-04 10:46:19 +01:00
parent f8873234a0
commit d1d29bcd64
12 changed files with 892 additions and 0 deletions

90
2017/04/src/main.rs Normal file
View File

@@ -0,0 +1,90 @@
use std::io::{self, Read};
fn has_duplicate_words(input: &str) -> bool {
let words = input.split_whitespace().collect::<Vec<_>>();
let mut iter = words.iter();
while let Some(needle) = iter.next() {
if iter.clone().any(|haystack| haystack == needle) {
return true;
}
}
false
}
fn has_anagram_words(input: &str) -> bool {
let words = input.split_whitespace().collect::<Vec<_>>();
let mut iter = words.iter();
while let Some(needle) = iter.next() {
let mut needle_chars = needle.chars().collect::<Vec<_>>();
needle_chars.sort();
for haystack in iter.clone() {
let mut haystack_chars = haystack.chars().collect::<Vec<_>>();
haystack_chars.sort();
if haystack_chars == needle_chars {
return true;
}
}
}
false
}
fn main() {
let mut input = String::new();
io::stdin()
.read_to_string(&mut input)
.expect("failed to parse input");
let part_one = input
.lines()
.map(|line| line.trim())
.filter(|line| !line.is_empty())
.filter(|line| !has_duplicate_words(line))
.count();
println!("part one: valid={}", part_one);
let part_two = input
.lines()
.map(|line| line.trim())
.filter(|line| !line.is_empty())
.filter(|line| !has_duplicate_words(line))
.filter(|line| !has_anagram_words(line))
.count();
println!("part two: valid={}", part_two);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_duplicate_words() {
assert_eq!(has_duplicate_words("aa bb cc dd ee"), false);
assert_eq!(has_duplicate_words("aa bb cc dd aa"), true);
assert_eq!(has_duplicate_words("aa bb cc dd aaa"), false);
}
#[test]
fn test_anagram_words() {
assert_eq!(has_anagram_words("abcde fghij"), false);
assert_eq!(has_anagram_words("abcde xyz ecdab"), true);
assert_eq!(has_anagram_words("a ab abc abd abf abj"), false);
assert_eq!(has_anagram_words("iiii oiii ooii oooi oooo"), false);
assert_eq!(has_anagram_words("oiii ioii iioi iiio"), true);
}
}