Advertisement
Guest User

Untitled

a guest
Dec 13th, 2021
329
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.82 KB | None | 0 0
  1. use std::io;
  2. use std::io::BufRead;
  3. use std::collections::HashSet;
  4. use std::iter::FromIterator;
  5. use itertools::Itertools;
  6.  
  7. const CANONICAL : [u8; 10] = [
  8.     //abcdefg
  9.     0b1110111,  // 0
  10.     0b0010010,
  11.     0b1011101,
  12.     0b1011011,
  13.     0b0111010,
  14.     0b1101011,
  15.     0b1101111,
  16.     0b1010010,
  17.     0b1111111,
  18.     0b1111011,  // 9
  19. ];
  20.  
  21. fn pos<P : std::cmp::Eq>(haystack : &[P], needle : P) -> Option<usize> {
  22.     for (i,p) in haystack.iter().enumerate() {
  23.         if *p == needle { return Some(i) }
  24.     }
  25.     return None
  26. }
  27.  
  28. fn encode(w : &str, perm : &[char]) -> u8 {
  29.     let mut ret = 0u8;
  30.     for c in w.chars() {
  31.         match pos(perm, c) {
  32.             Some(x) => {ret += 1u8 << x}
  33.             None => {panic!("unexpected character")}
  34.         }
  35.     }
  36.     return ret
  37. }
  38.  
  39. fn find_code(wires : &[&str]) -> Vec::<char> {
  40.     let canonical_values = HashSet::<u8>::from_iter(CANONICAL.iter().cloned());
  41.     for perm in ['a', 'b', 'c', 'd', 'e', 'f', 'g'].iter().permutations(7) {
  42.         let perm : Vec<char> = perm.into_iter().cloned().collect();
  43.         let values : HashSet<u8> = wires.iter().map(|w| encode(w, &perm[..])).collect();
  44.         if values == canonical_values {
  45.             return perm
  46.         }
  47.     }
  48.     panic!("Failed to find_code")
  49. }
  50.  
  51. fn main() {
  52.     let mut k : i32 = 0;
  53.     for line in io::stdin().lock().lines() {
  54.         let line = String::from(line.unwrap());
  55.         let words : Vec<&str> = line.trim().split_whitespace().collect();
  56.         let code = find_code(&words[.. 10]);
  57.         let mut num : i32 = 0;
  58.         for w in &words[11 ..] {
  59.             let e = encode(w, &code[..]);
  60.             let digit = pos(&CANONICAL, e).unwrap();
  61.             num = num*10 + (digit as i32);
  62.         }
  63.         k += num;
  64.         println!("{} -> {}", line, num);
  65.     }
  66.     println!("{}", k)
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement