Skip to content

Instantly share code, notes, and snippets.

@bChiquet
Created December 14, 2020 17:32
Show Gist options
  • Save bChiquet/4ef2cb04e82249d60d7c5712e7af7ec1 to your computer and use it in GitHub Desktop.
Save bChiquet/4ef2cb04e82249d60d7c5712e7af7ec1 to your computer and use it in GitHub Desktop.
use std::io::{self, BufRead};
macro_rules! parse_input {
($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap())
}
fn main() {
let stdin = io::stdin();
let problem = stdin.lock().lines().map(|x| x.unwrap()).collect::<Vec<String>>();
let mut result = Vec::new();
solve_problem(problem, &mut result);
result.iter().for_each(|line|println!("{}", line));
}
fn solve_problem(problem: Vec<String>, result: &mut Vec<String>) -> () {
let mut problem_lines= problem.iter();
let size_line = problem_lines.next().unwrap();
let problem_size = size_line.split(" ").collect::<Vec<_>>();
let h = parse_input!(problem_size[1], i32);
let tops_line = problem_lines.next().unwrap();
let tops= tops_line.split(" ").map(|t| t.trim()).collect::<Vec<_>>();
let number_of_paths = tops.len();
let wire_height = h - 2;
let mut permutations = (0..number_of_paths).collect::<Vec<usize>> ();
for _i in 0..wire_height as usize {
let wire_line = problem_lines.next().unwrap();
update_permutations(&mut permutations, wire_line);
}
let bottom_line = problem_lines.next().unwrap();
let bottoms= bottom_line.split(" ").map(|b| b.trim()).collect::<Vec<_>>();
for path in 0..number_of_paths as usize {
result.push(format!("{}{}", tops[path], bottoms[permutations[path]]));
}
}
fn update_permutations(permutations : &mut Vec<usize>, wire_line : &String) -> () {
let bridges = wire_line.split("|").collect::<Vec<_>>();
for (index, bridge) in bridges.iter().enumerate() {
if bridge == &"--" {
let buf = permutations[index];
permutations[index]= permutations[index-1];
permutations[index-1] = buf
}
}
}
#[cfg(test)]
mod tests {
use crate::solve_problem;
macro_rules! string_vec {
($($x:expr),*) => (vec![$($x.to_string()),*]);
}
#[test]
fn example_1() {
let problem= string_vec![
"7 7",
"A B C",
"| | |",
"|--| |",
"| |--|",
"| |--|",
"| | |",
"1 2 3"
];
let mut solution= Vec::new();
solve_problem(problem, &mut solution);
assert_eq!("A2", solution[0]);
assert_eq!("B1", solution[1]);
assert_eq!("C3", solution[2]);
}
#[test]
fn example_1_with_arbitrary_tops_and_bottoms() {
let problem= string_vec![
"7 7",
"K W Z",
"| | |",
"|--| |",
"| |--|",
"| |--|",
"| | |",
"R M H"
];
let mut solution= Vec::new();
solve_problem(problem, &mut solution);
assert_eq!("KM", solution[0]);
assert_eq!("WR", solution[1]);
assert_eq!("ZH", solution[2]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment