AdventOfCode/day2/src/main.rs

75 lines
2.0 KiB
Rust
Raw Normal View History

2018-12-02 17:05:17 +01:00
use std::fs::File;
use std::io::Read;
use std::prelude::v1::Vec;
use std::collections::HashMap;
fn main() {
let mut f = File::open("input").expect("file not found");
let mut contents = String::new();
f.read_to_string(&mut contents).expect("something went wrong reading the file");
let lines: Vec<&str> = contents.split("\n").collect();
2018-12-03 20:25:55 +01:00
println!("{}", count_doubles_and_triples(&lines));
let common_letters : String;
match find_common_letters(&lines){
Ok(s) => common_letters = s.into_iter().collect(),
Err(s) => common_letters = s.to_string(),
}
println!("{}", common_letters);
2018-12-02 17:05:17 +01:00
}
2018-12-03 20:25:55 +01:00
fn count_doubles_and_triples(lines: &Vec<&str>) -> i32 {
2018-12-02 17:05:17 +01:00
let mut doubles = 0;
let mut triples = 0;
2018-12-03 20:25:55 +01:00
for line in lines {
2018-12-02 17:05:17 +01:00
let mut counts = HashMap::new();
for character in line.chars() {
*counts.entry(character).or_insert(0) += 1;
}
if counts.values().any(|&count| count == 2) {
doubles += 1;
}
if counts.values().any(|&count| count == 3) {
triples += 1;
}
}
2018-12-03 20:25:55 +01:00
triples * doubles
2018-12-02 17:05:17 +01:00
}
2018-12-03 20:25:55 +01:00
fn find_common_letters(lines: &Vec<&str>) -> Result<Vec<char> , std::io::Error> {
for line in lines {
for line2 in lines {
let mismatches = line.chars().zip(line2.chars()).filter(|&(a, b)| a != b).count();
if mismatches == 1 {
let result: Vec<(char,char)> = line.chars().zip(line2.chars()).filter(|&(a, b)| a == b).collect();
let candidate1: Vec<char> = line.chars().collect();
let candidate2: Vec<char> = line2.chars().collect();
let mut result: Vec<char> = Vec::new();
for x in 0..candidate1.len() {
if candidate1[x] == candidate2[x]{
result.push(candidate1[x]);
}
}
return Ok(test);
}
}
}
2018-12-02 17:05:17 +01:00
2018-12-03 20:25:55 +01:00
Err(std::io::Error::new(std::io::ErrorKind::Other, "No match found"))
2018-12-02 17:05:17 +01:00
}