Created
December 6, 2019 09:05
-
-
Save hellow554/a8b5e355704ca4416baa4372ff29a929 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::collections::HashMap; | |
use petgraph::{algo, Directed, Direction, Graph, Undirected}; | |
const INPUT: &str = include_str!("../input"); | |
type MyGraph = Graph<String, (), Directed>; | |
type MyUnGraph = Graph<String, (), Undirected>; | |
fn parse_directed(s: &str) -> MyGraph { | |
let mut hm = HashMap::new(); | |
let mut graph = MyGraph::new(); | |
for line in s.lines() { | |
let mut p = line.split(')').collect::<Vec<_>>(); | |
assert_eq!(2, p.len()); | |
let pa = p.pop().unwrap(); | |
let pb = p.pop().unwrap(); | |
let node_a = *hm.entry(pa).or_insert_with(|| graph.add_node(pa.to_string())); | |
let node_b = *hm.entry(pb).or_insert_with(|| graph.add_node(pb.to_string())); | |
graph.update_edge(node_a, node_b, ()); | |
} | |
graph | |
} | |
fn parse_undirected(s: &str) -> MyUnGraph { | |
let mut hm = HashMap::new(); | |
let mut graph = MyUnGraph::new_undirected(); | |
for line in s.lines() { | |
let mut p = line.split(')').collect::<Vec<_>>(); | |
assert_eq!(2, p.len()); | |
let pa = p.pop().unwrap(); | |
let pb = p.pop().unwrap(); | |
let node_a = *hm.entry(pa).or_insert_with(|| graph.add_node(pa.to_string())); | |
let node_b = *hm.entry(pb).or_insert_with(|| graph.add_node(pb.to_string())); | |
graph.update_edge(node_a, node_b, ()); | |
} | |
graph | |
} | |
fn solve_a(g: &MyGraph) -> usize { | |
let com_node = g | |
.node_indices() | |
.find(|n| g.neighbors_directed(*n, Direction::Outgoing).count() == 0) | |
.unwrap(); | |
g.node_indices() | |
.map(|start_node| algo::astar(g, start_node, |f| f == com_node, |_| 1, |_| 0).unwrap().0) | |
.sum() | |
} | |
fn solve_b(g: &MyUnGraph) -> usize { | |
let you_node = g.node_indices().find(|n| g[*n] == "YOU").unwrap(); | |
let san_node = g.node_indices().find(|n| g[*n] == "SAN").unwrap(); | |
algo::astar(g, you_node, |f| f == san_node, |_| 1, |_| 0).unwrap().0 - 2 | |
} | |
fn main() { | |
let directed = parse_directed(INPUT); | |
let undirected = parse_undirected(INPUT); | |
println!("A: {}", solve_a(&directed)); | |
println!("B: {}", solve_b(&undirected)); | |
} | |
#[test] | |
fn ta() { | |
let input = "COM)B | |
B)C | |
C)D | |
D)E | |
E)F | |
B)G | |
G)H | |
D)I | |
E)J | |
J)K | |
K)L"; | |
let input = parse_directed(input); | |
assert_eq!(42, solve_a(&input)); | |
} | |
#[test] | |
fn tb() { | |
let input = "COM)B | |
B)C | |
C)D | |
D)E | |
E)F | |
B)G | |
G)H | |
D)I | |
E)J | |
J)K | |
K)L | |
K)YOU | |
I)SAN"; | |
let input = parse_undirected(input); | |
assert_eq!(4, solve_b(&input)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment