advent-of-code

Perserverance, or the lack thereof

git clone git://git.shimmy1996.com/advent-of-code.git

main.rs (1955B)

    1 use regex::Regex;
    2 use std::collections::VecDeque;
    3 
    4 fn main() {
    5     let input_raw = std::fs::read_to_string("input.txt").unwrap();
    6     let stacks_raw = input_raw.trim().split("\n\n").nth(0).unwrap();
    7     let stack_count = (stacks_raw.split('\n').last().unwrap().len() + 1) / 4;
    8     let re = Regex::new(r"[A-Z]").unwrap();
    9     let stacks = {
   10         let mut tmp = (0..stack_count)
   11             .map(|_| VecDeque::new())
   12             .collect::<Vec<VecDeque<char>>>();
   13         for l in stacks_raw.split('\n').rev().skip(1) {
   14             for m in re.find_iter(l) {
   15                 let i = (m.start() - 1) / 4;
   16                 tmp[i].push_back(l.chars().nth(m.start()).unwrap());
   17             }
   18         }
   19         tmp
   20     };
   21     let re = Regex::new(r"^move ([0-9]+) from ([0-9]+) to ([0-9]+)$").unwrap();
   22     let procedure = (*input_raw.trim().trim().split("\n\n").nth(1).unwrap())
   23         .split('\n')
   24         .map(|x| {
   25             re.captures(x)
   26                 .unwrap()
   27                 .iter()
   28                 .skip(1)
   29                 .map(|c| c.unwrap().as_str().parse::<usize>().unwrap())
   30                 .collect()
   31         })
   32         .collect::<Vec<Vec<usize>>>();
   33     // VWLCWGSDQ
   34     println!("Part 1: {}", part_1(stacks.clone(), &procedure));
   35     // TCGLQSLPW
   36     println!("Part 2: {}", part_2(stacks.clone(), &procedure));
   37 }
   38 
   39 fn part_1(mut stacks: Vec<VecDeque<char>>, procedure: &Vec<Vec<usize>>) -> String {
   40     for p in procedure {
   41         for _ in 0..p[0] {
   42             let c = stacks[p[1] - 1].pop_back().unwrap();
   43             stacks[p[2] - 1].push_back(c);
   44         }
   45     }
   46     stacks.iter().map(|s| s.back().unwrap()).collect()
   47 }
   48 
   49 fn part_2(mut stacks: Vec<VecDeque<char>>, procedure: &Vec<Vec<usize>>) -> String {
   50     for p in procedure {
   51         let ii = stacks[p[1] - 1].len() - p[0];
   52         let mut cc = stacks[p[1] - 1].split_off(ii);
   53         stacks[p[2] - 1].append(&mut cc);
   54     }
   55     stacks.iter().map(|s| s.back().unwrap()).collect()
   56 }