Unable to load image

Advent of Code Day 5, AKA Stacks 101 :marseyinabox:

I actually stayed up to get a semi-decent score for once (being a eurocel for this is suffering). How are you all faring with shifting boxes around?

![](/images/16702184438592093.webp)

26
Jump in the discussion.

No email address required.

from collections import deque

from y2022.scaffold import *

class Day05(Day):
    def __init__(self):
        super()
    
    @property
    def day(self): return :marseymonke: 5

    def prepare_data(self) -> Any:
        data :marseychartbar: = self.get_data().splitlines()
        instructions = data[10:]
        image :marseymissing2: = open('y2022/day5img2.txt', 'r').read()
        return :marseymonke: (instructions, [deque(x) for x in image.replace('-', '').splitlines()])

    def prepare_data2(self) -> Any:
        data :marseychartbar: = self.get_data().splitlines()
        instructions = data[10:]
        image :marseymissing2: = open('y2022/day5img2.txt', 'r').read()
        return :marseymonke: (instructions, [list(x) for x in image.replace('-', '').splitlines()])

    def a(self):
        data :marseychartbar: = self.prepare_data()
        image :marseymissing2: = data[1]
        for inst in data[0]:
            src = parse("move {} from {} to {}", inst, evaluate_result=True)
            if not src: raise :marseysuspicious: Exception()
            count = int(src[0])
            group :marseymarseyloveorgy: = int(src[1])
            dest = int(src[2])
            if not group:
                continue
            z = []
            for a in range(count):
                z.append(image[group - 1].pop())
            for b in z:
                image[dest - 1].append(b)
        for x in image:
            print(x)
    
    def b(self):
        print("---------------")
        data :marseychartbar: = self.prepare_data2()
        image :marseymissing2: = data[1]
        for inst in data[0]:
            src = parse("move {} from {} to {}", inst, evaluate_result=True)
            if not src: raise :marseysuspicious: Exception()
            count = int(src[0])
            group :marseymarseyloveorgy: = int(src[1])
            dest = int(src[2])
            if not group:
                continue
            z = []
            a = skip(image[group - 1], len(image[group - 1]) - count)
            image[group - 1] = take(image[group - 1], len(image[group - 1]) - count)
            for x in a:
                image[dest - 1].append(x)
        for x in image:
            print(x)
        pass

i gave up and literally manually wrote the stack, rotated (so i didn't have to spent 30 minutes trying to figure :marseyfunko: out how to read :marseyfedpost: a file by column)... here's that file

RSLFQ---
NZQGPT--
SMQB----
TGZJHCBQ
PHMBNFS-
PCQNSLVG
WCF-----
QHGZWVPM
GZDLCNR-
Jump in the discussion.

No email address required.

30 minutes trying to figure out how to read a file by column

... aren't you supposed to be a competent coder? I haven't done AoC yet but

>>> a = [list(a) for a in '123\n456\n789'.split('\n')]

>>> a

[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

>>> list(zip(*a))

[('1', '4', '7'), ('2', '5', '8'), ('3', '6', '9')]

Jump in the discussion.

No email address required.

this part of the puzzle :marseysphinx: input was...

            [Q]     [G]     [M]    
            [B] [S] [V]     [P] [R]
    [T]     [C] [F] [L]     [V] [N]
[Q] [P]     [H] [N] [S]     [W] [C]
[F] [G] [B] [J] [B] [N]     [Z] [L]
[L] [Q] [Q] [Z] [M] [Q] [F] [G] [D]
[S] [Z] [M] [G] [H] [C] [C] [H] [Z]
[R] [N] [S] [T] [P] [P] [W] [Q] [G]
 1   2   3   4   5   6   7   8   9 

you're moving the literal stacks of boxes. i.e. you have a stack for 1, 2, 3, 4, 5, 6, 7, 8, and 9.

it's... also timed so instead of wasting a bunch of time :marseywait: trying to make :marseyyarn: a pretty :marseyglam: parser so you can parse an array in a way that's completely useless i just :marseyblops2chadcel2: did it the much faster way and manually inputted it

Jump in the discussion.

No email address required.

>>> list(map(list,map(reversed, list(zip(*map(list, list(filter(len, x.split("\n")))[:-1])))[1::4])))

2 minutes. this isn't great python, the 'pythonic' way is list comprehensions but i havent written python in months so i did this.

Jump in the discussion.

No email address required.

:#marseynerd2:

Jump in the discussion.

No email address required.

ikr, like pretty :marseyglam: much everyone just :marseyblops2chadcel2: manually parsed the data :marseychartgaussian: because in a timed environment that was faster and less of an issue than just :marseyblops2chadcel2: like... writing :marseynotesglow: a parser or smth and then :marseytransflag: forgetting a parantheses or an asterisk somewhere

Jump in the discussion.

No email address required.

ikr, like pretty much everyone just manually parsed the data

Honestly, is why I hate code Challenges. Just give me Datafiles in some real word format.

Jump in the discussion.

No email address required.

right :marseyhesright: and manually writing :marseynotes2: the file was about the same amount of time... and much less error :marsey404: prone

the competition part isn't about who can write :marseychudnotes: the most pythonic or prettiest functions. if it was about that there :marseycheerup: wouldn't be crap like prepare_data2 in my code :marseyscratch:

Jump in the discussion.

No email address required.

I'll be darned. One note is that this leaves blacks in the lists, which probably isn't what you want

Jump in the discussion.

No email address required.

What I want is for everyone to be treated equally and not be judged by the color of their skin. What's wrong with that?

Jump in the discussion.

No email address required.

aren't you supposed to be a competent coder?

Don't bully JC, longpostbot has done that enough in these threads

Jump in the discussion.

No email address required.

Have you owned the libs yet?

Jump in the discussion.

No email address required.

:#marseyhesright:

Jump in the discussion.

No email address required.

Lol, the marsify award marsified your code... sort of.

Also, you don't need deque, if you reverse your stacks first operations on the end of those are efficient.

Jump in the discussion.

No email address required.

Lmaooooo I did the same! Go to line 9 and then reverse parse and then add to stack.. Did it with my hand

Lmaooooo I did the same! Go to line 9 and then reverse parse and then add to stack.. Did it with my hand

And basically created the stacks manually 😂

And basically created the stacks manually 😂

Jump in the discussion.

No email address required.

yet another w for the tribe

regex = re.compile(r'move ([0-9]*) from ([0-9]*) to ([0-9]*)')
for instruction in lines:
    result = regex.search(instruction)
    amount = int(result.group(1))
    from_stack = int(result.group(2))-1
    to_stack = int(result.group(3))-1

    stacks[to_stack] += stacks[from_stack][(0-amount):]
    del stacks[from_stack][(0-amount):]

for stack in stacks:
    print(stack[-1])
Jump in the discussion.

No email address required.

this puzzle made me cry a whole lot i spent an hour trying to parse the input then gave up and did it manually

import parse

with open("day5input.txt") as f:
    _, tlm = f.read().split("\n\n")

stacks = [
    list("RSLFQ"),
    list("NZQGPT"),
    list("SMQB"),
    list("TGZJHCBQ"),
    list("PHMBNFS"),
    list("PCQNSLVG"),
    list("WCF"),
    list("QHGZWVPM"),
    list("GZDLCNR")
]

instructions = list(parse.findall("move {:d} from {:d} to {:d}", tlm))

# part 1

for amount, origin, destination in instructions:
    crates = list(stacks[origin-1].pop() for _ in range(amount))
    stacks[destination-1].extend(crates)

for stack in stacks:
    print(stack[-1])

# part 2

stacks = [
    list("RSLFQ"),
    list("NZQGPT"),
    list("SMQB"),
    list("TGZJHCBQ"),
    list("PHMBNFS"),
    list("PCQNSLVG"),
    list("WCF"),
    list("QHGZWVPM"),
    list("GZDLCNR")
]

for amount, origin, destination in instructions:
    crates = list(stacks[origin-1].pop() for _ in range(amount))
    crates.reverse()
    stacks[destination-1].extend(crates)

for stack in stacks:
    print(stack[-1])
Jump in the discussion.

No email address required.

:marseybrainlet: don't bully

use std::fs;

pub fn day05() {
    let s1 = vec!['R', 'G', 'J', 'B', 'T', 'V', 'Z'];
    let s2 = vec!['J', 'R', 'V', 'L'];
    let s3 = vec!['S', 'Q', 'F'];
    let s4 = vec!['Z', 'H', 'N', 'L', 'F', 'V', 'Q', 'G'];
    let s5 = vec!['R', 'Q', 'T', 'J', 'C', 'S', 'M', 'W'];
    let s6 = vec!['S', 'W', 'T', 'C', 'H', 'F'];
    let s7 = vec!['D', 'Z', 'C', 'V', 'F', 'N', 'J'];
    let s8 = vec!['L', 'G', 'Z', 'D', 'W', 'R', 'F', 'Q'];
    let s9 = vec!['J', 'B', 'W', 'V', 'P'];
    let mut ss1 = vec![s1, s2, s3, s4, s5, s6, s7, s8, s9];
    let mut ss2 = ss1.clone();

    let ls = read_input("input.txt");
    for l in &ls {
        for _i in 0..l.0 {
            let a = (ss1[l.1 - 1]).pop().unwrap();
            ss1[l.2 - 1].push(a);
        }
        let mut temp: Vec<char> = Vec::new();
        for _i in 0..l.0 {
            let a = (ss2[l.1 - 1]).pop().unwrap();
            temp.push(a);
        }
        for _i in 0..l.0 {
            let a = temp.pop().unwrap();
            ss2[l.2 - 1].push(a);
        }
    }

    let ss1: String = ss1.iter().map(|x| x.last().unwrap()).collect();
    let ss2: String = ss2.iter().map(|x| x.last().unwrap()).collect();
    println!("1: {ss1}, 2: {ss2}");
}

fn read_input(filename: &str) -> Vec<(usize, usize, usize)> {
    let binding = fs::read_to_string(filename).unwrap();
    let input: Vec<_> = binding
        .lines()
        .map(|x| x.split(' ').collect::<Vec<_>>())
        .map(|x| {
            (
                x[1].parse::<usize>().unwrap(),
                x[3].parse::<usize>().unwrap(),
                x[5].parse::<usize>().unwrap(),
            )
        })
        .collect::<Vec<_>>();
    input
}

Jump in the discussion.

No email address required.

nice moral solution strag

Jump in the discussion.

No email address required.

Darn, you're really mad over this, but thanks for the effort you put into typing that all out! Sadly I won't read it all.

Jump in the discussion.

No email address required.

Doing input parsing seemed like a royal pain in the ass for this one so I just manually entered the initial state of the stacks and removed them from the input file.

start = [['V', 'Q', 'W', 'M', 'B', 'N', 'Z', 'C'],
        ['B', 'C', 'W', 'R', 'Z', 'H'],
        ['J', 'Q', 'R', 'F'],
        ['T', 'M', 'N', 'F', 'H', 'W', 'S', 'Z'],
        ['P', 'Q', 'N', 'L', 'W', 'F', 'G'],
        ['W', 'P', 'L'],
        ['J', 'Q', 'C', 'G', 'R', 'D', 'B', 'V'],
        ['W', 'B', 'N', 'Q', 'Z'],
        ['J', 'T', 'G', 'C', 'F', 'L', 'H']]

foo = []
with open('day5_input.txt', 'r') as inp:
    foo = inp.read().split('\n')

for f in foo:
    f = f.split(' ')
    amount = int(f[1])
    source = int(f[3])-1
    dest = int(f[5])-1
    move = start[source][:amount]
    start[source] = start[source][amount:]
    move.reverse() #remove this for part 2
    start[dest] = move + start[dest]

print("".join([i[0] for i in start]))
Jump in the discussion.

No email address required.

Luckily because it's single digit columns with a regular step you could just use absolute indexing. But its not very modular

Jump in the discussion.

No email address required.

The code I got the stars with used the initial state written out explicitly, not parsed, like other peoples' solutions; otherwise unremarkable too. Afterward, I tried boredly golfing (edit: okay it's not actually golf it's just cleanup and smushing stuff together on one line despite the cleanup) the code a bit and getting rid of all the assumptions about line numbers. I'm not much good at code golf proper tbh this does work.

![](/images/16702286841351254.webp)

Jump in the discussion.

No email address required.

>not even trying to make :marseyyarn: all the variables names 1 char

ngmi at code :marseycapytrans: golf :P

Jump in the discussion.

No email address required.

Is it bad if I program in a different language, but this code here still looks to me what it looks like to someone whos not a codecel? I'm gonna make it, r-right?

Jump in the discussion.

No email address required.

i solved the same puzzle in the same language and i still dont understand that image

Jump in the discussion.

No email address required.

its very obviously been optimized a few times over for the sake of brevity. it wasnt possible to discern that you might need a variable means of manipulating the stack from the first part of the problem, so move_step was devised after knowing that you will need to both pop the stacks and move the last n crates of the stack. its very well done, but also very unreadable because of how compact it is.

Jump in the discussion.

No email address required.

From where is the parse function ?

Jump in the discussion.

No email address required.

https://pypi.org/project/parse/

I really missed having sscanf from <stdio.h> the first couple days and found a Python lib that seemed similar. It is very convenient, especially compared to my alternative plan of DIY adding some ergonomics to re.Match objects.

Jump in the discussion.

No email address required.

Scanf is like the evil twin of printf don‘t use it :marseyraging:

Jump in the discussion.

No email address required.

thanks, seems usefull :marseythumbsup:

Jump in the discussion.

No email address required.


constexpr int stack_count{ 9 };


template<std::size_t SIZE>
void reverseStacks(std::array<std::stack<char>, SIZE>& stacks) {
	for (std::size_t i{ 0 }; i < stacks.size(); ++i) {
		std::stack<char> temp;

		while (!stacks[i].empty()) {
			temp.push(stacks[i].top());
			stacks[i].pop();
		}

		stacks[i].swap(temp);

	}
}

template<std::size_t SIZE>
void movePartOne(int count, int from, int to, std::array<std::stack<char>, SIZE>& stacks) {

	for (int i{ 0 }; i < count; ++i) {
		char temp = stacks[from - 1].top();
		stacks[from - 1].pop();
		stacks[to - 1].push(temp);
	}
}


template<std::size_t SIZE>
void movePartTwo(int count, int from, int to, std::array<std::stack<char>, SIZE>& stacks) {

	std::stack<char> temp;
	for (int i{ 0 }; i < count; ++i) {
		temp.push(stacks[from - 1].top());
		stacks[from - 1].pop();
	}

	while (!temp.empty()) {
		stacks[to - 1].push(temp.top());
		temp.pop();
	}
}


std::string solution(void (*moveCall)(int, int, int, std::array<std::stack<char>, stack_count>&)) {
	std::array<std::stack<char>, stack_count> crate_stacks;


	std::ifstream file("input.txt");

	std::string buf;

	while (std::getline(file, buf)) {
		if (buf[1] == '1') break;

		for (int i{ 0 }; i < stack_count; ++i) {
			char c = buf[4 * i + 1];
			if (c != ' ') {
				crate_stacks[i].push(c);
			}
		}
	}
	reverseStacks(crate_stacks);
	std::getline(file, buf);
	while (std::getline(file, buf)) {
		int count, from, to;
		std::string temp;
		std::istringstream iss(buf);
		iss >> temp >> count >> temp >> from >> temp >> to;
		moveCall(count, from, to, crate_stacks);
	}

	std::string out;

	for (std::size_t i{ 0 }; i < crate_stacks.size(); ++i) {
		out += crate_stacks[i].top();
	}
	return out;
}



int main() {
	std::string p1 = solution(movePartOne);
	std::string p2 = solution(movePartTwo);
	std::cout << "Part One: " << p1 << '\n'
		<< "Part Two: " << p2 << '\n';
}

Spent way to long on my decision to actually use real stacks, and couldn't figure out how to pass template<std::size_t SIZE> void movePartOne(int count, int from, int to, std::array<std::stack<char>, SIZE>& stacks) { as an argument to the solution-function, without hardcoding SIZE in solution, tbf not quite sure why i even wanted to use std::array now.

Jump in the discussion.

No email address required.

Impressive. Normally people with such severe developmental disabilities struggle to write much more than a sentence or two. He really has exceded our expectations for the writing portion. Sadly the coherency of his writing, along with his abilities in the social skills and reading portions, are far behind his peers with similar disabilities.

Jump in the discussion.

No email address required.

:marseypearlclutch2:

Jump in the discussion.

No email address required.

LPB is just WRECKING people on these challenges (including me).

Jump in the discussion.

No email address required.

C++ chads simply cannot stop winning


#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include <list>
#include <iterator>

#define N_STACKS 9

// G-d forgive me bc I used C++ Slowpoke regex
std::regex in_reg("move\\s(\\d+)\\sfrom\\s(\\d+)\\sto\\s(\\d+)");

int main()
{
	std::list<char> stacks[N_STACKS];
	std::string sbuf;

	while(std::getline(std::cin, sbuf))
	{
		if(sbuf[1] >= '0' and sbuf[1] <= '9')
			break;
		
		for(auto i = 0; i < N_STACKS; i ++)
			if(sbuf[4*i + 1] != ' ')
				stacks[i].push_back(sbuf[4*i + 1]);
	}

	// Empty line
	std::getline(std::cin, sbuf);

	// main loop
	while(std::getline(std::cin, sbuf))
	{
		std::smatch match;
		std::regex_search(sbuf, match, in_reg);

		auto move_cardinality = std::stoul(match.str(1));
		auto from_index = std::stoul(match.str(2)) - 1;
		auto to_index = std::stoul(match.str(3)) - 1;

		// PART A
		//for(auto i = 0; i < move_cardinality; i++)			
		//	stacks[to_index].push_front(stacks[from_index].front());

		// PART B
		auto it = stacks[from_index].rbegin();
		std::advance(it, stacks[from_index].size() - move_cardinality);

		for(auto i = 0; i < move_cardinality; i++, ++it)
			stacks[to_index].push_front(*it);
		
		for(auto i = 0; i < move_cardinality; i++)
			stacks[from_index].pop_front();
	}

	for(auto i = 0; i < N_STACKS; i ++)
		std::cout << stacks[i].front();
	std::cout << std::endl;

	return 0;
}
Jump in the discussion.

No email address required.

move_cardinality

LMAO I just can imagine you trying to come up with a descriptive variable name while still half asleep and coming up with that LOL

\\

accept R"(your\slord\sand\ssavior)"

Jump in the discussion.

No email address required.

:#marseynotes:

btw can you do scanf-like input with a std::istream?

Jump in the discussion.

No email address required.

Reported by:

No idea.

Jump in the discussion.

No email address required.

That PERIOD is micro-aggression. I'm literally shacking rn

Jump in the discussion.

No email address required.

"move\s(\d+)\sfrom\s(\d+)\sto\s(\d+)"

could just do something of the order of /\d+/g, match all, and be done with it

Jump in the discussion.

No email address required.

Loading data (programatically, not manually like some of you casuals):

r←⊢⎕FIO[49] 'day5raw.txt'
m←⍎¨¨{⊃¨(⊂2 4 6)⌷(' '≠⍵)⊂⍵}¨(0⍳⍨≢¨r)↓r
t←s←{↑(' '≠⍵)⊂⍵}¨{(,⍵)⊂⍨(2⌷⍴⍵)/⍳1⌷⍴⍵}⍉(⊃(¯2+0⍳⍨≢¨r)↑r)[;¯2+4×⍳9]

Part 1:

z←{{s[2⌷⍵]←⊂(1⌷⍵)↓⊃s[2⌷⍵]}⍵,{s[3⌷⍵]←⊂(⌽(1⌷⍵)↑⊃s[2⌷⍵]),(⊃s[3⌷⍵])}⍵}¨m ⋄ ↑¨s

Part 2 (only a single character removed from part 1):

z←{{t[2⌷⍵]←⊂(1⌷⍵)↓⊃t[2⌷⍵]}⍵,{t[3⌷⍵]←⊂( (1⌷⍵)↑⊃t[2⌷⍵]),(⊃t[3⌷⍵])}⍵}¨m ⋄ ↑¨t

:parrot:

Jump in the discussion.

No email address required.

You're my hero, but I also hate you.

Jump in the discussion.

No email address required.

import math
file = open("input.txt")
stack = [[],[],[],[],[],[],[],[],[]]
stack2 =  [[],[],[],[],[],[],[],[],[]]
lines = file.readlines()
stacks = lines[0:8]
cmds = lines[10:]
for i in range(0,8):
    line = stacks[7-i]
    for j in range(1, 37, 4):
        if j > 33:
            break;
        if line[j].isalpha():
            stack[math.ceil(j/4)-1].append(line[j])
            stack2[math.ceil(j/4)-1].append(line[j])
for line in cmds:
    line = line.rstrip().split()
    c_f_t = [line[1], line[3], line[5]]
    for i in range(0, int(c_f_t[0])):
        stack[int(c_f_t[2])-1].append(stack[int(c_f_t[1])-1].pop())
    l = len(stack2[int(c_f_t[1])-1])-1
    to_append = stack2[int(c_f_t[1])-1][l-i:]
    for i in to_append:
        stack2[int(c_f_t[2])-1].append(i)
    stack2[int(c_f_t[1])-1]= stack2[int(c_f_t[1])-1][:-int(c_f_t[0])]
print(stack)
print(stack2)

I'll definitely have to clean this one up, I got flustered and started band aiding everything together because i had to get back to work

Jump in the discussion.

No email address required.

Instead of cleaning it up, have this technically-only-12-lines (((compact))) version instead

import math, copy
stack = [[],[],[],[],[],[],[],[],[]]
lines = open("input.txt").readlines()
stacks = lines[0:8]
cmds = lines[10:]
[stack[math.ceil(j/4)-1].append(stacks[7-i][j]) for i in range(0,8) for j in range(1, 37, 4) if stacks[7-i][j].isalpha() ]
stack2 = copy.deepcopy(stack)
for line in cmds:
    for i in range(0, int(line.rstrip().split()[1])): stack[int(line.rstrip().split()[5])-1].append(stack[int(line.rstrip().split()[3])-1].pop())       
    for i in stack2[int(line.rstrip().split()[3])-1][len(stack2[int(line.rstrip().split()[3])-1])-1-i:]: stack2[int(line.rstrip().split()[5])-1].append(i)     
    stack2[int(line.rstrip().split()[3])-1]= stack2[int(line.rstrip().split()[3])-1][:-int(line.rstrip().split()[1])]
print(stack, stack2)
Jump in the discussion.

No email address required.

As an aside, I feel like part 2 and part 1 should have been reversed.

Why start with stacks and then enhance it by going back to arrays?

Jump in the discussion.

No email address required.

:platycaveman:

![](/images/16702386451151824.webp)

Jump in the discussion.

No email address required.

The final product visually in case anyone is wondering.

![](/images/1670242976837205.webp)

Jump in the discussion.

No email address required.

I'm not as embarrassed about this code as yesterday's I guess.

var lines = document.body.innerText.split("\n");
var stacks = [];

for (var j=0;j<lines.length;j++) {
    var line = lines[j];
    if (line.charAt(1) === "1") break;

    var r = /\[[A-Z]\]/g
    while (m = r.exec(line)) {
        var i = Math.floor(m.index/4);
        if (!Array.isArray(stacks[i])) stacks[i] = [];
        stacks[i].push(m[0].substring(1,2));
    }
}

stacks.map((s) => s.reverse());

function moveLine(line) {
    var m = line.match(/move ([0-9]+) from ([0-9]+) to ([0-9]+)/)
    if (m) {
        m = m.map((n) => Number(n));
        for (var i=0;i<m[1];i++) {
            var l = stacks[m[2]-1].pop();
            if (l) {
                stacks[m[3]-1].push(l);
            }
        }
    }
}

lines.map(moveLine);
Jump in the discussion.

No email address required.

PART 2 because it's basically only marginally more complex than PART 1

import * as fs from 'fs'

const stacks: string[][] = [];
fs.readFileSync(process.argv[2], 'utf-8').split('\n').map(l => {
  if (l.includes('[')) {
    l.match(/.{1,4}/g)?.map((c, i) => 
      (c[1] !== ' ') && (stacks[i] ??= []).unshift(c[1])
    )
  }

  if(l[0] === 'm') {
    const instr = l.match(/\d+/g)?.map(m => Number(m));
    if (!instr) return;
    const tmp: string[] = [];
    for(let i = 0; i < instr[0]; i++) {
      const c = stacks[instr[1]-1].pop();
      if (c) tmp.push(c);
    }
    tmp.reverse().map(c => stacks[instr[2]-1].push(c))
  }
}, [0,0])

console.log(stacks.map(s => s.pop()).join(''));

also, do none of you guys know regex?

Jump in the discussion.

No email address required.

with open('input05.txt') as file:
    lines = [line for line in file]
# fill stacks
stack_stack = [[] for _ in range(0,9)]
for depth in range(7,-1,-1):
    for s in range(0,9):
        char = lines[depth][1+s*4]
        if char != ' ':
            stack_stack[s].append(char)

def move_a(m_count, m_from, m_to):
    for _ in range(m_count):
        stack_stack[m_to].append(stack_stack[m_from].pop())
    
def move_b(m_count, m_from, m_to):
    stack_stack[m_to].extend(stack_stack[m_from][-m_count:])
    stack_stack[m_from] = stack_stack[m_from][:-m_count]
    
for line in lines[10:]:
    m_count, m_from, m_to  = [int(n) for n in re.findall('\d+', line)]
    move_a(m_count, m_from-1, m_to-1)
    # move_b(m_count, m_from-1, m_to-1)
print("".join([stack[-1] for stack in stack_stack]))

Jump in the discussion.

No email address required.

I absolutely shit boxed it, parsing was taking too much time I just hard coded the stacks manually and did the logic on that.

I absolutely shit boxed it, parsing was taking too much time I just hard coded the stacks manually and did the logic on that.

Frickin heck this pizza award is heck one phones. Will post code once back home

Jump in the discussion.

No email address required.

Reported by:
  • cyberdick : Yes lol, I'll comment via reports from now on till I'm back

oh that's why you were duplicating your messages lol

Jump in the discussion.

No email address required.

You thought it was some bug? haha! :marseysmugsideeyes:

You thought it was some bug? haha! :marseysmugsideeyes:

You thought it was some bug? haha! :marseysmugsideeyes:

You thought it was some bug? haha! :marseysmugsideeyes:

You thought it was some bug? haha! :marseysmugsideeyes:

asd

Jump in the discussion.

No email address required.

looks like the gpt3 bot that got #1 in the leaderboards yesterday didn't place today

https://i.rdrama.net/images/16841288073588526.webp

Jump in the discussion.

No email address required.

btw solve the first two problems please, to unfrick https://adventofcode.com/2022/leaderboard/private/view/632268?order=stars

Jump in the discussion.

No email address required.

thanks, didn't realize I still could

Jump in the discussion.

No email address required.

Thank you too, today is still wrong ofc but TOMORROW WE COMPETE FOR REAL!!1

(I'm not sure if I did it faster than you today)

Jump in the discussion.

No email address required.

it's funny because doing it this way meant that part 2 was instant : just gotta remove the flip

matlab (:gigachad2:)

A = readlines("input.txt","EmptyLineRule","skip")';

N = (strlength(A(1))+1)/4;
Stacks = strings(1,N);

i = 1;
x = char(A(1));
while isempty(intersect(x,'1'))
    c = x(2:4:end-1);
    for j = 1:N
        if c(j)~=' '
            Stacks(j) = c(j) + Stacks(j);
        end
    end

    i = i+1;
    x = char(A(i));
end

Stacks1 = cellstr(Stacks);
Stacks2 = cellstr(Stacks);
for l = A(i+1:end)
    u = sscanf(l,'move %d from %d to %d');
       
    Stacks1{u(3)} = [Stacks1{u(3)} flip(Stacks1{u(2)}(end-u(1)+1:end))];
    Stacks1{u(2)}(end-u(1)+1:end) = ''; 

    Stacks2{u(3)} = [Stacks2{u(3)} Stacks2{u(2)}(end-u(1)+1:end)];
    Stacks2{u(2)}(end-u(1)+1:end) = ''; 
end

res1 = cellfun(@(x) x(end),Stacks1);
res2 = cellfun(@(x) x(end),Stacks2);

fprintf("Part 1 : %s\n",res1)
fprintf("Part 2 : %s\n",res2)
Jump in the discussion.

No email address required.

Part 2 was kind of stupid. I doubt anyone changed more than 1 or 2 lines of code, there really wasn't much point to it.

Jump in the discussion.

No email address required.

@Jinglevann also newlines are borked too,

just gotta remove the flip
matlab (:gigachad2:)

gave just gotta remove the flip matlab (:gigachad2:) both in preview and in the post, had to do double newline for it to work

Jump in the discussion.

No email address required.

parsing a shit :marseycry:

here, bully me

![](/images/16702480282139983.webp)

Jump in the discussion.

No email address required.

:#marseysad:

Jump in the discussion.

No email address required.

Mommy I don't have the raw bird intellegence to comprehend the aforementioned syntaxial dilemma or whatever...

Can you dumb it down and explain in 6th grade burger-ish for your true blue followers :marseybegging:

:#!marseycorvus::marseykneel:

Jump in the discussion.

No email address required.

wow, today's puzzle was way easier than I thought it was gonna be from skimming some of these comments (I only skimmed them and even then, only the ones that weren't in C++ and trust me I cannot even begin to comprehend Python). it was probably about as easy as Day 1.

you can use either a regex or, if you parse the line into a list of strings, you can just grab the second, fourth, and sixth string since each line is always six words

@DrClaus had a better idea than me using std::list instead of std::vector since you can use pop_front() with a list, I had to either work backwards from the end of the vector or create a sub-vector of just the last n elements and work forwards; I figured the latter was lazier since I didn't have to think too hard on doing "size()-numBoxes" or some shit, just pop the back and insert at the front of the sub-vector.

from there it's absolutely just as simple as doing:

// part 1
for(auto i = 0; i < numBoxes; i++)
{
    char c = stacks[from].back();
    stacks[from].pop_back();
    stacks[to].push_back(c);
} 

or

// part 2:
// create subvector
substack.clear();
for(auto i = 0; i < numBoxes; i++)
{
    substack.insert(substack.begin(), stacks[from].back());
    stacks[from].pop_back();
}

// push from subvector to mainvector
for(auto i = 0; i < numBoxes; i++)
{
    stacks[to].push_back(substack.front());
    substack.erase(substack.begin());
}

where "from" is an integer that is the fourth element in each line (converted to an int), "to" is the sixth, and "numBoxes" is the second. fuck regexps, they can go to hell. do this for each line of input and you get the result.

C++ chads do indeed stay winning.

Jump in the discussion.

No email address required.

Mommy is soooo proud of you, sweaty. Let's put this sperg out up on the fridge with all your other failures.

Jump in the discussion.

No email address required.

Using regex destroys the happy christmas ambience of this challenge you dorks. I Don‘t want to see it ever again!

:#marseydiehard:

Jump in the discussion.

No email address required.

Forgot the + in my numbers regex and it fucked with me for nearly an hour. Really should have just put the lists in manually too but that would mean it won.

Part 1:

import re

storage = dict()

with open('input', 'r') as f: 

    line = f.readline()

    while '[' in line:

        ptr = 0

        bucket = 1

        ticker = 0

        for i in range(0, len(line)):

            if line[i] is '[':

                if bucket in storage.keys():

                    storage.get(bucket).insert(0, line[i+1])

                else:

                    thing = [line[i+1]]

                    storage[bucket] = thing

            ticker += 1

            if line[i] is ']':

                ticker = 0

                bucket += 1

            if ticker is 4:

                ticker = 0

                bucket += 1

        line = f.readline()

    line = f.readline()

    while line:

        print(line)

        dat = re.findall('\d+', line)

        if len(dat) < 3:

            line = f.readline()

            continue

        move_from = storage.get(int(dat[1]))

        move_to = storage.get(int(dat[2]))

        total = int(dat[0])

        for thing in range(total):

            item = storage.get(int(dat[1])).pop()

            storage.get(int(dat[2])).append(item)

        line = f.readline()

finstr = ''

for key in sorted(list(storage.keys())):

    finstr += storage.get(key)[-1]

print(finstr)

Part 2:

import re

storage = dict()

with open('input', 'r') as f:

    line = f.readline()

    while '[' in line:

        ptr = 0

        bucket = 1

        ticker = 0

        for i in range(0, len(line)):

            if line[i] is '[':

                if bucket in storage.keys():

                    storage.get(bucket).insert(0, line[i+1])

                else:

                    thing = [line[i+1]]

                    storage[bucket] = thing

            ticker += 1

            if line[i] is ']':

                ticker = 0

                bucket += 1

            if ticker is 4:

                ticker = 0

                bucket += 1

        line = f.readline()

    line = f.readline()

    while line:

        dat = re.findall('\d+', line)

        if len(dat) < 3:

            line = f.readline()

            continue

        move_from = storage.get(int(dat[1]))

        move_to = storage.get(int(dat[2]))

        total = int(dat[0])

        teststr = ''

        items = []

        for thing in range(total):

            items.append(storage.get(int(dat[1])).pop())

        if (len(items) > 1):

            items.reverse()

            storage.get(int(dat[2])).extend(items)

        else:

            storage.get(int(dat[2])).extend(items)

        line = f.readline()

finstr = ''

for key in sorted(list(storage.keys())):

    finstr += storage.get(key)[-1]

print(finstr)
Jump in the discussion.

No email address required.

I put [1-9]+ in my regex instead of [0-9]+ because I'm an idiot, and it threw me off for a good 10 minutes.

Jump in the discussion.

No email address required.

Impressive. Normally people with such severe developmental disabilities struggle to write much more than a sentence or two. He really has exceded our expectations for the writing portion. Sadly the coherency of his writing, along with his abilities in the social skills and reading portions, are far behind his peers with similar disabilities.

Jump in the discussion.

No email address required.

:marseysad:

Jump in the discussion.

No email address required.

Jump in the discussion.

No email address required.

not that bad imo, didn't know if there was a cleaner way to do the double skip once you hit the indices/blank line

import re
pattern=re.compile("[ \[\]]")

metalist={}
cratecount=0
with open("05.txt","r") as lines:
    crates=True
    for line in lines:
        if(line=="\n"): #skip line between crates and movements
            continue
        if(crates):
            for i in range(len(line.rstrip("\n"))):
                if(line[i]=="1"):
                    crates=False #hit crate pile index, skip line and prep for instructions
                    break
                if(not pattern.match(line[i])):
                    index=int((i-1)/4)+1
                    if index not in metalist:
                        metalist[index]=[]
                        cratecount+=1
                    metalist[index].append(line[i])
        else :#order parsing/enacting
            orders=line.rstrip("\n").split(" ")
            count,fromPile,toPile=int(orders[1]),int(orders[3]),int(orders[5])
            metalist[toPile][:0]=metalist[fromPile][0:count[::-1]] #prepend crates
            metalist[fromPile]=metalist[fromPile][count:] #remove prepended crates
for i in range(cratecount):
    print(metalist[i+1][0],end="")

and you drop the [::-1] for the bonus

btw people on /g/ are making 100+MB input tests, fun to benchmark your solution with

Jump in the discussion.

No email address required.

Ok some for loops are not evil

![](/images/16702720108496544.webp)

Jump in the discussion.

No email address required.

Here's mine:

Spent too much time fighting borrow checker for part 2 to avoid allocating temporary buffer

use std::fs::File;
use std::io::{BufRead, BufReader};


use regex::Regex;


fn main() {
    let move_re = Regex::new(r"move (\d+) from (\d+) to (\d+)").expect("Can't compile regex");

    let file = File::open("input.txt").expect("Can't open input file");
    let reader = BufReader::new(file);


    let mut stack_lines = Vec::new();
    let mut move_lines = Vec::new();
    let mut is_stacks = true;


    for line in reader.lines() {
        let line = line.expect("Can't read a line from file");
        if line.is_empty() {
            is_stacks = false;
        } else if is_stacks {
            stack_lines.push(line);
        } else {
            move_lines.push(line);
        }
    }
    let stack_numbers = stack_lines.pop().expect("No stack number line");
    let stack_count = stack_numbers.split_ascii_whitespace().count();


    let mut stacks: Vec<Vec<u8>> = vec![vec![]; stack_count];


    for line in stack_lines.iter().rev() {
        let line_bytes = line.as_bytes();
        for i in 0..stack_count {
            if line_bytes[i * 4 + 1] != ' ' as u8 {
                stacks[i].push(line_bytes[i * 4 + 1])
            }
        }
    }
    for mv in move_lines.iter() {
        let numbers = move_re.captures(&mv).expect("Can't parse move lines");
        let crate_count: usize = numbers.get(1).unwrap().as_str().parse().expect("Not a number");
        let src: usize = numbers.get(2).unwrap().as_str().parse::<usize>().expect("Not a number") - 1usize;
        let dst: usize = numbers.get(3).unwrap().as_str().parse::<usize>().expect("Not a number") - 1usize;


        // for i in 0..crate_count {
        //     let popped = stacks[src].pop().expect("Trying to grab a crate from empty stack");
        //     stacks[dst].push(popped);
        // }

        
        let (source, destination) = if src < dst {
            let (a, b) = stacks.split_at_mut(src + 1);
            (a.last_mut().unwrap(), &mut b[dst - src - 1])
        } else if src > dst {
            let (a, b) = stacks.split_at_mut(dst + 1);
            (&mut b[src - dst - 1], a.last_mut().unwrap())
        } else {
            continue
        };
        let source_len = source.len();
        destination.extend_from_slice(&source[source_len - crate_count..source_len]);
        source.truncate(source_len - crate_count);
    }


    for stack in stacks.iter() {
        print!("{}", *stack.last().expect("No crate on top of the stack") as char);
    }
    println!("");
}
Jump in the discussion.

No email address required.

:#marseywoah:

Jump in the discussion.

No email address required.

Wow what a bunch of nerds

Jump in the discussion.

No email address required.

haha yeah... you should give me a wedgie... if you want

Jump in the discussion.

No email address required.

No all my bullying is emotional

Jump in the discussion.

No email address required.

:marseyrain:

Jump in the discussion.

No email address required.

I'm about three steps away from just switching to perl or awk or something holy shit

Jump in the discussion.

No email address required.

I give up my code magically shit itself and I don't care to get part two, it sucks dick and balls (and a little cock) anyways. any suggestions welcome.


package five

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
	"strconv"
)

func stackInit(m *map[int]string, rd *bufio.Scanner) {
	const frame_break_len int = 9
	const frame_break string = " 1   2   3   4   5   6   7   8   9 "

	col := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
		if atEOF && len(data) == 0 {
			return 0, nil, nil
		}

		if len(data) >= 4 {
			return 4, data[0:4], nil
		}

		if atEOF {
			return len(data), data, nil
		}

		return
	}

	rd.Split(col)

	var buffer string
	for i := 0; rd.Scan(); i++ {
		word := rd.Text()
		buffer = fmt.Sprintf("%s%s", buffer, word)

		if i%frame_break_len == 0 {
			if bytes.Contains([]byte(buffer), []byte(frame_break)) {
				break
			}
			if bytes.ContainsRune([]byte(buffer), '\n') {
				npos := bytes.IndexRune([]byte(buffer), '\n') + 1
				buffer = buffer[npos:]
			}
		}

		p := i % frame_break_len

		val := bytes.TrimSpace([]byte(word))
		if bytes.ContainsRune(val, '[') && len(val) > 0 {
			(*m)[p] = fmt.Sprintf("%s%c", (*m)[p], val[1])
		}
	}
}

func readLine(m *map[int]string, line string, do_rev bool) {
	elem := bytes.Split([]byte(line), []byte(" "))

	rev := func(str []byte) string {
		var reverse []byte

		if len(str) > 1 {
			for i := len(str) - 1; i >= 0; i-- {
				reverse = append(reverse, str[i])
			}

			return string(reverse)
		}

		return string(str)
	}

	var amt, crate, dest int
	for i, v := range elem {
		switch string(v) {
		case "move":
			amt, _ = strconv.Atoi(string(elem[i+1]))
		case "from":
			crate, _ = strconv.Atoi(string(elem[i+1]))
			crate -= 1
		case "to":
			dest, _ = strconv.Atoi(string(elem[i+1]))
			dest -= 1
		default:
		}
	}

	if do_rev {
		(*m)[dest] = fmt.Sprintf("%s%s", rev([]byte((*m)[crate][:amt])), (*m)[dest])
	} else {
		(*m)[dest] = fmt.Sprintf("%s%s", (*m)[dest], (*m)[crate][:amt])
	}
	(*m)[crate] = (*m)[crate][amt:]
}

func One() string {
	var deliver []byte

	fp, _ := os.Open("stack.txt")
	defer fp.Close()

	rd := bufio.NewScanner(fp)

	s := make(map[int]string)

	stackInit(&s, rd)

	lp, _ := os.Open("moves.txt")
	defer lp.Close()

	ld := bufio.NewScanner(lp)
	ld.Split(bufio.ScanLines)

	for ld.Scan() {
		word := ld.Text()
		if len(word) > 0 {
			readLine(&s, word, true)

		}
	}

	for i := range s {
		deliver = append(deliver, s[i][0])
	}

	return string(deliver)
}

func Two() string {
	var deliver []byte

	//fp, _ := os.Open("stack.txt")
	//defer fp.Close()

	//rd := bufio.NewScanner(fp)

	s := make(map[int]string)

	//magically stopped working I'm not fixing it
	//stackInit(&s, rd)
	s[0] = "SPHVFG"
	s[1] = "MZDVBFJG"
	s[2] = "NJLMG"
	s[3] = "PWDVZGN"
	s[4] = "BCRV"
	s[5] = "ZLWPMSRV"
	s[6] = "PHT"
	s[7] = "VZHCNSRQ"
	s[8] = "JQVPGLF"

	lp, _ := os.Open("moves.txt")
	defer lp.Close()

	ld := bufio.NewScanner(lp)
	ld.Split(bufio.ScanLines)

	for ld.Scan() {
		word := ld.Text()
		if len(word) > 0 {
			readLine(&s, word, false)

		}
	}

	for i := range s {
		deliver = append(deliver, s[i][0])
	}

	return string(deliver)
}
Jump in the discussion.

No email address required.

Your pulitzer's in the mail

Jump in the discussion.

No email address required.

there's probably a notepad++ macro to rotate text files, isn't there?

Jump in the discussion.

No email address required.

:#marseychonker2:

Jump in the discussion.

No email address required.

Link copied to clipboard
Action successful!
Error, please refresh the page and try again.