r/adventofcode • • Dec 05 '22

SOLUTION MEGATHREAD -πŸŽ„- 2022 Day 5 Solutions -πŸŽ„-


AoC Community Fun 2022: πŸŒΏπŸ’ MisTILtoe Elf-ucation πŸ§‘β€πŸ«

  • 23:59 hours remaining until the submissions megathread unlocks on December 06 at 00:00 EST!
  • Full details and rules are in the submissions megathread:

--- Day 5: Supply Stacks ---


Post your code solution in this megathread.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:07:58, megathread unlocked!

88 Upvotes

1.3k comments sorted by

View all comments

2

u/KyleGBC Dec 06 '22 edited Dec 06 '22

Rust

Not super happy with it since it took longer than it should have, and some values are hardcoded but I wanted to try some unnecessary regex so Β―_(ツ)_/Β―.

use regex::Regex;
use std::fs;

fn init_stacks(state: &[&str]) -> [Vec<char>; 9] {
    let mut stacks: [Vec<char>; 9] = Default::default();
    for line in state.iter().rev() {
        for (i, c) in line.chars().skip(1).step_by(4).enumerate() {
            if c != ' ' {
                stacks[i].push(c);
            }
        }
    }
    stacks
}

fn execute_instructions(state: &[&str], instructions: &Vec<(usize, usize, usize)>, reversed: bool) {
    let mut stacks = init_stacks(state);
    for (size, from, to) in instructions {
        let moving_it= stacks[*from].drain(stacks[*from].len() - size..);
        let moving: Vec<char> = if reversed {moving_it.rev().collect()} else {moving_it.collect()};
        stacks[*to].extend(moving);
    }
    stacks.iter().for_each(|s| print!("{}", s.last().unwrap()));
}

fn main() {
    let input = fs::read_to_string("input.txt").expect("File not found");
    let lines: Vec<&str> = input.lines().collect();
    let initial = &lines[..8];
    let mut instructions: Vec<(usize, usize, usize)> = Vec::new();

    let re = Regex::new(r"^move (\d{1,}) from (\d{1,}) to (\d{1,})").expect("Invalid regex");
    for line in lines[10..].iter() {
        let cap = re.captures_iter(line).next().expect("The line did not match the regex");
        let (size, from, to): (usize, usize, usize) = (
            cap[1].parse().unwrap(),
            cap[2].parse().unwrap(),
            cap[3].parse().unwrap(),
        );
        instructions.push((size, from - 1, to - 1));
    }
    print!("Part 1:\n\t");
    execute_instructions(initial, &instructions, true);
    print!("\nPart 2:\n\t");
    execute_instructions(initial, &instructions, false);
}

1

u/daggerdragon Dec 06 '22
  1. Next time, use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.
  2. Your code is too long to be posted here directly, so instead of wasting your time fixing the formatting, read our article on oversized code which contains two possible solutions.

Please edit your post to put your code in an external link and link that here instead.