main.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. const fs = require('fs');
  2. const readline = require('readline');
  3. function Stack() {
  4. this.data = [];
  5. this.id = 0;
  6. }
  7. Stack.prototype.push = function(letter) {
  8. if (letter !== ' ')
  9. this.data.push(letter);
  10. }
  11. Stack.prototype.multiPush = function(arr) {
  12. this.data = arr.concat(this.data);
  13. }
  14. Stack.prototype.log = function() {
  15. console.log(this.id, this.data);
  16. }
  17. Stack.prototype.moveTo = function(count, targetStack) {
  18. //targetStack.multiPush(this.data.splice(0, count).reverse()); // Part 1
  19. targetStack.multiPush(this.data.splice(0, count)); // part 2
  20. }
  21. Stack.prototype.finalize = function() {
  22. this.id = parseInt(this.data.pop());
  23. }
  24. async function main() {
  25. let stacks = null;
  26. let stackDefined = false;
  27. for await (let line of readline.createInterface({ input: process.stdin })) {
  28. if ((!line || !line.length) && !stackDefined) {
  29. stackDefined = true;
  30. stacks.forEach(i => i.finalize());
  31. continue;
  32. }
  33. if (!stackDefined) {
  34. if (!stacks) {
  35. stacks = [];
  36. for (let i =0; i < line.length / 4; ++i)
  37. stacks.push(new Stack());
  38. }
  39. for (let i =0; i < line.length /4; ++i) {
  40. stacks[i].push(line[i*4+1]);
  41. }
  42. } else {
  43. if (!line || !line.length)
  44. break;
  45. let num = [];
  46. for (let i of line.matchAll(/\d+/g)) num.push(i[0]);
  47. stacks[num[1] -1].moveTo(num[0], stacks[num[2] -1]);
  48. }
  49. }
  50. stacks.forEach(i => i.log());
  51. console.log(stacks.map(i => i.data[0] || null).filter(i => !!i).join(""));
  52. };
  53. (main());