Showing results for 
Search instead for 
Did you mean: 

Advent of Code Day 5

New Contributor III

Spoiler warning.

Day 5 offered a chance to have some fun at the kdb+ console.

Parsing the input:


i:flip -1 1 1*0 -1 -1+(6#" I";" ")0:(1+r?"")_r:read0`05.txt    // instructions
s:trim flip reverse((-1+r?"")#r)[;1+4*til 9]                   // stacks


The solution is to iterate over the stacks and list of instructions, appending and removing from the correct indices as necessary:


last each{@/[x;y 2 1;(,;:);](reverse y[0]#;y[0]_)@\:x y 1}/[s;i]
last each{@/[x;y 2 1;(,;:);](y[0]#;y[0]_)@\:x y 1}/[s;i]



The examples provided in the problem description are always quite visual, and since this is an iterative solution, this provided a nice opportunity to visualize the solution too. The animate function takes the stacks and formats it to match the that of the original input, before writing it to the console:


    1"\033[H\033[J";                                             // clear the console
    x:reverse flip(7h$first system"c")$x;                        // pad the stacks to match the console size
    -1 {@/[raze"[",'x,'"]";0 2+/:3*where null x;:;" "]}each x;   // surround crates with [] and write to stdout
    system"sleep 0.5";                                           // pause for dramatic effect
q)animate s    // initial stack state
   [P]            [Q]   [T]
[F][N]         [P][L]   [M]
[H][T][H]      [M][H]   [Z]
[M][C][P]   [Q][R][C]   [J]
[T][J][M][F][L][G][R]   [Q]


If we then call this animate function at each step of the iteration, we get a visual of the crates moving between the stacks at each step. Once this is finished, we can then read off the solution - the top crate on each stack. Part 2, for example:


q){animate o:@/[x;y 2 1;(,;:);](y[0]#;y[0]_)@\:x y 1;o}/[s;i];
[R]      [F][D][L][T]
[B]      [J][G][P][N][C]
[S][N]   [D][H][Q][Q][H][T]


 You can take part by following the details here:


Moderator Moderator

Very nice @cillianreilly! Thanks for sharing with the community 👏

Moderator Moderator

My solution for AOC5:

inp:read0 `:aoc5.txt
sep:first where inp like ""
d:`stacktab`moves!(sep#;1_sep _)@\:inp
stacks:rtrim each reverse each flip -1_d[`stacktab][;(count[ssr[first -1#d[`stacktab];" ";""]]-1) {4+x}\1];
moves:"I"$(" " vs' d[`moves])[;1 3 5];

/ part 1
raze -1#'{[w;x;y;z] w[z-1],:reverse neg[x]#w[y-1]; w[y-1]: neg[x] _ w[y-1];w}/[stacks] . flip moves

/ part 2
raze -1#'{[w;x;y;z] w[z-1],:neg[x]#w[y-1]; w[y-1]: neg[x] _ w[y-1];w}/[stacks] . flip moves

Less elegant than Cillian's but worth sharing to see how others attack the problems!