const fs = require('fs'); const readline = require('readline'); function Stack() { this.data = []; this.id = 0; } Stack.prototype.push = function(letter) { if (letter !== ' ') this.data.push(letter); } Stack.prototype.multiPush = function(arr) { this.data = arr.concat(this.data); } Stack.prototype.log = function() { console.log(this.id, this.data); } Stack.prototype.moveTo = function(count, targetStack) { //targetStack.multiPush(this.data.splice(0, count).reverse()); // Part 1 targetStack.multiPush(this.data.splice(0, count)); // part 2 } Stack.prototype.finalize = function() { this.id = parseInt(this.data.pop()); } async function main() { let stacks = null; let stackDefined = false; for await (let line of readline.createInterface({ input: process.stdin })) { if ((!line || !line.length) && !stackDefined) { stackDefined = true; stacks.forEach(i => i.finalize()); continue; } if (!stackDefined) { if (!stacks) { stacks = []; for (let i =0; i < line.length / 4; ++i) stacks.push(new Stack()); } for (let i =0; i < line.length /4; ++i) { stacks[i].push(line[i*4+1]); } } else { if (!line || !line.length) break; let num = []; for (let i of line.matchAll(/\d+/g)) num.push(i[0]); stacks[num[1] -1].moveTo(num[0], stacks[num[2] -1]); } } stacks.forEach(i => i.log()); console.log(stacks.map(i => i.data[0] || null).filter(i => !!i).join("")); }; (main());