Add day 5 solutions

master
Danila Fedorin 10 months ago
parent 6e6d652858
commit 07d8457cd8

@ -0,0 +1,64 @@
use List;
use IO;
iter boxes() {
for line in stdin.lines() {
if line == "\n" then return;
var boxList = new list(string);
for idx in 0..<line.size by 4 align 1 {
boxList.append(line[idx]);
}
yield boxList;
}
}
iter instructions() {
var n, from, to: int;
while readf("move %i from %i to %i\n", n, from, to) do yield (n, from-1, to-1);
}
proc transpose(lists) {
var listsT: [0..<lists[0].size] list(string);
for lidx in 0..<(lists.size - 1) by -1 {
for (char, idx) in zip(lists[lidx], 0..) {
if char != ' ' then listsT[idx].append(char);
}
}
return listsT;
}
proc moveOneAtATime(ref from: list(string), ref to: list(string), n: int) {
for i in 1..n {
to.append(from.pop());
}
}
proc moveAll(ref from: list(string), ref to: list(string), n: int) {
var offset = from.size - n;
for i in 1..n {
to.append(from.pop(offset));
}
}
proc tops(stacks) {
var acc = "";
for stack in stacks do acc += stack.last();
return acc;
}
var layers = boxes();
var stacks = transpose(layers);
config const part = 1;
if part == 1 {
for (n, from, to) in instructions() {
moveOneAtATime(stacks[from], stacks[to], n);
}
} else if part == 2 {
for (n, from, to) in instructions() {
moveAll(stacks[from], stacks[to], n);
}
}
writeln(tops(stacks));

@ -0,0 +1,47 @@
require "advent"
boxes, instructions = input(2022, 5).split("\n\n")
boxes = parse_boxes_lines(boxes.lines);
instrs = parse_instrs(instructions.lines);
def parse_instr(str)
_, n, _, f, _, t = str.split(" ")
{ n.to_i64, f.to_i64, t.to_i64 }
end
def parse_instrs(lines)
lines.map { |l| parse_instr(l) }
end
def parse_boxes_line(str)
str += " "
str.chars.in_groups_of(4).map do |group|
group[1]
end
end
def parse_boxes_lines(lines)
lines.pop
lines = lines.map { |l| parse_boxes_line(l) }
lines = lines.transpose
lines.each do |line|
line.reject!(&.==(' ')).reverse!
end
lines
end
def move(from, to, n)
# n.times do
# to << from.pop
# end
from.pop(n).each do |x|
next unless x
to.push(x)
end
end
instrs.each do |instr|
n, f, t = instr
move(boxes[f-1], boxes[t-1], n)
end
puts boxes.map(&.last).join("")
Loading…
Cancel
Save