Added day 12

This commit is contained in:
Sebastian 2021-12-12 15:25:19 +01:00
parent 983e9d3c6f
commit 19dd107e45
3 changed files with 120 additions and 10 deletions

24
inputs/day12.txt Normal file
View File

@ -0,0 +1,24 @@
pg-CH
pg-yd
yd-start
fe-hv
bi-CH
CH-yd
end-bi
fe-RY
ng-CH
fe-CH
ng-pg
hv-FL
FL-fe
hv-pg
bi-hv
CH-end
hv-ng
yd-ng
pg-fe
start-ng
end-FL
fe-bi
FL-ks
pg-start

View File

@ -1,10 +1,7 @@
5483143223
2745854711
5264556173
6141336146
6357385478
4167524645
2176841721
6882881134
4846848554
5283751526
start-A
start-b
A-c
A-b
b-d
A-end
b-end

89
src/bin/day12.rs Normal file
View File

@ -0,0 +1,89 @@
use std::collections::HashMap;
use std::collections::HashSet;
use std::error::Error;
use std::fs::File;
use std::io::{self, BufRead};
use std::vec::Vec;
fn enumerate_ways(
start: &str,
end: &str,
vertices: &HashMap<String, HashSet<String>>,
mut path: Vec<String>,
mut allow_twice: bool,
) -> u64 {
if start == end {
return 1;
}
if start.chars().all(|c| c.is_lowercase()) {
if path.iter().filter(|n| n == &&start).count() > 0 {
if !allow_twice {
return 0;
} else {
allow_twice = false;
}
}
}
path.push(start.to_string());
let mut ways = 0;
for neighbor in vertices[start].iter() {
if neighbor != "start" {
ways += enumerate_ways(neighbor, end, vertices, path.clone(), allow_twice);
}
}
ways
}
fn main() -> Result<(), Box<dyn Error>> {
let file = File::open("inputs/day12.txt")?;
let links: Vec<(String, String)> = io::BufReader::new(file)
.lines()
.map(|l| l.unwrap())
.map(|l| {
let mut ends = l.split('-');
(
ends.next().unwrap().to_string(),
ends.next().unwrap().to_string(),
)
})
.collect();
let mut vertices: HashMap<String, HashSet<String>> = HashMap::new();
for link in links.iter() {
if vertices.contains_key(&link.0) {
let mut set = vertices[&link.0].clone();
set.insert(link.1.clone());
vertices.insert(link.0.clone(), set);
} else {
let mut set: HashSet<String> = HashSet::new();
set.insert(link.1.clone());
vertices.insert(link.0.clone(), set);
}
if vertices.contains_key(&link.1) {
let mut set = vertices[&link.1].clone();
set.insert(link.0.clone());
vertices.insert(link.1.clone(), set);
} else {
let mut set: HashSet<String> = HashSet::new();
set.insert(link.0.clone());
vertices.insert(link.1.clone(), set);
}
}
let ways1 = enumerate_ways("start", "end", &vertices, Vec::new(), false);
println!("Answer1: {}", ways1);
println!("");
let ways2 = enumerate_ways("start", "end", &vertices, Vec::new(), true);
println!("Answer2: {}", ways2);
Ok(())
}