Computer.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. const prompt = require("prompt-sync")({ sigint: true });
  2. const util = require("util");
  3. const Stack = require("./Stack");
  4. const ComputerParameterMode = require("./ComputerParameterMode");
  5. const { DeepClone } = require("./common");
  6. module.exports = class Computer {
  7. /**
  8. * An Intcode Computer for the Advent of Code 2019 challenge
  9. *
  10. * @author Apis Necros
  11. *
  12. * @param {number[]} stack The initial memory to load into the computer
  13. * @param {Object} options Options that can be enabled within the computer
  14. * @param {boolean} options.followPointer When true, the memory will be dumped every call to Execute with the current instruction highlighted
  15. * @param {number} options.tickRate The number of milliseconds between calls to Execute. Initializes to 0.
  16. * @param {boolean} options.inputFromConsole When true, the computer will prompt for input on the console. If false, it will check for an linked computer and, if one exists, will wait for input from that computer.
  17. * @param {boolean} options.outputToConsole When true, the computer will print the output of opcode 4 to the console. If false, it will check for an linked computer and, if one exists, pass the output to that computer.
  18. */
  19. constructor(stack, options = {}) {
  20. this._initialMemory = DeepClone(stack);
  21. this.stack = new Stack(stack);
  22. this.OPCODES = {
  23. ADD: 1,
  24. MULTIPLY: 2,
  25. INPUT: 3,
  26. OUTPUT: 4,
  27. JUMP_IF_TRUE: 5,
  28. JUMP_IF_FALSE: 6,
  29. LESS_THAN: 7,
  30. EQUALS: 8,
  31. HALT: 99,
  32. };
  33. this.EQUALITY = {
  34. EQUALS: 0,
  35. LESS_THAN: 1,
  36. };
  37. this.parameterMode = ComputerParameterMode.POSITION_MODE;
  38. /**
  39. * Whether the Execute loop should skip moving the pointer after running the opcode
  40. *
  41. * Some opcodes, such as JUMP_IF_TRUE set the stack pointer, and as such shouldn't have
  42. * the Execute function move it after the opcode finishes executing.
  43. */
  44. this.skipNext = false;
  45. this.options = {
  46. followPointer: options.followPointer ?? false,
  47. tickRate: options.tickRate ?? 0,
  48. inputFromConsole: options.inputFromConsole ?? false,
  49. outputToConsole: options.outputToConsole ?? false,
  50. };
  51. }
  52. /**
  53. * Run the computer
  54. *
  55. * Runs opcodes on the stack until either the a HALT command is
  56. * encountered, or an error is thrown.
  57. * @returns {void}
  58. */
  59. async Run() {
  60. while (this.Execute(this.stack.Get(ComputerParameterMode.IMMEDIATE_MODE)) === true) {
  61. if (this.options.tickRate) {
  62. // Sleep
  63. // eslint-disable-next-line no-await-in-loop, no-promise-executor-return, arrow-parens
  64. await new Promise(resolve => setTimeout(resolve, this.options.tickRate));
  65. }
  66. }
  67. }
  68. /**
  69. * Execute a call using the provided opcode
  70. *
  71. * @param {number} rawOpcode A opcode to execute
  72. * @returns {boolean} False if the opcode was HALT, otherwise true
  73. */
  74. Execute(rawOpcode) {
  75. let status = true;
  76. this.skipNext = false;
  77. if (this.options.followPointer) {
  78. this.DumpMemory(true);
  79. }
  80. const opcode = rawOpcode % 100;
  81. // console.log(`DEBUG: opcode: ${opcode}`);
  82. switch (opcode) {
  83. case this.OPCODES.ADD: {
  84. this.Operation_Add(rawOpcode);
  85. break;
  86. }
  87. case this.OPCODES.MULTIPLY: {
  88. this.Operation_Multiply(rawOpcode);
  89. break;
  90. }
  91. case this.OPCODES.INPUT: {
  92. this.Operation_Input();
  93. break;
  94. }
  95. case this.OPCODES.OUTPUT: {
  96. this.Operation_Output(rawOpcode);
  97. break;
  98. }
  99. case this.OPCODES.JUMP_IF_TRUE: {
  100. this.Operation_JumpIf(rawOpcode, true);
  101. break;
  102. }
  103. case this.OPCODES.JUMP_IF_FALSE: {
  104. this.Operation_JumpIf(rawOpcode, false);
  105. break;
  106. }
  107. case this.OPCODES.LESS_THAN: {
  108. this.Operation_Equality(rawOpcode, this.EQUALITY.LESS_THAN);
  109. break;
  110. }
  111. case this.OPCODES.EQUALS: {
  112. this.Operation_Equality(rawOpcode, this.EQUALITY.EQUALS);
  113. break;
  114. }
  115. case this.OPCODES.HALT:
  116. status = false;
  117. break;
  118. default:
  119. throw Error(`Opcode ${opcode} not found\nMemdump: ${JSON.stringify(this.stack.Dump())}\nPointer: ${this.stack.pointer}`);
  120. }
  121. if (!this.skipNext) {
  122. this.stack.Next();
  123. }
  124. return status;
  125. }
  126. /**
  127. * Parse operands based on the current parameter mode
  128. *
  129. * When the int computer is in Immediate Mode, the values are returned
  130. * as-is. When in Position Mode, the operands are used as memory
  131. * addresses, and the values at those addresses are returned instead.
  132. *
  133. * @returns {number[]} The parsed list of operands
  134. */
  135. _ParseOperands(...operands) {
  136. if (this.parameterMode == ComputerParameterMode.IMMEDIATE_MODE) { return operands; }
  137. return operands.map((operand) => this.stack.Get(operand));
  138. }
  139. /**
  140. * Execute the Add opcode
  141. *
  142. * Adds two numbers and stores the result at the provided position
  143. * on the stack.
  144. *
  145. * Parses the operand Parameter Mode out of the opcode used to make
  146. * this call.
  147. *
  148. * @param {number} rawOpcode The opcode in memory used to make this call
  149. * @returns {void}
  150. */
  151. Operation_Add(rawOpcode) {
  152. const operandLeftMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  153. const operandRightMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  154. const operandLeft = this.stack.Next().Get(operandLeftMode);
  155. const operandRight = this.stack.Next().Get(operandRightMode);
  156. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  157. const newValue = operandLeft + operandRight;
  158. this.stack.Put(outputPosition, newValue);
  159. }
  160. /**
  161. * Execute the Multiply opcode
  162. *
  163. * Multiplies two numbers and stores the result at the provided
  164. * position on the stack.
  165. *
  166. * @param {number} rawOpcode The opcode in memory used to make this call
  167. * @returns {void}
  168. */
  169. Operation_Multiply(rawOpcode) {
  170. const operandLeftMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  171. const operandRightMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  172. const operandLeft = this.stack.Next().Get(operandLeftMode);
  173. const operandRight = this.stack.Next().Get(operandRightMode);
  174. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  175. const newValue = operandLeft * operandRight;
  176. this.stack.Put(outputPosition, newValue);
  177. }
  178. /**
  179. * Execute the Input opcode
  180. *
  181. * Prompts the user to input a value from the command line
  182. *
  183. * @returns {void}
  184. */
  185. Operation_Input() {
  186. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  187. let userInput;
  188. do {
  189. userInput = Number(prompt("Please enter a number: "));
  190. } while (Number.isNaN(userInput));
  191. this.stack.Put(outputPosition, userInput);
  192. }
  193. /**
  194. * Execute the OUTPUT opcode
  195. *
  196. * @param {number} rawOpcode The opcode in memory used to make this call
  197. * @returns {void}
  198. */
  199. Operation_Output(rawOpcode) {
  200. const currAddress = this.stack.pointer;
  201. const outputPositionMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  202. const output = this.stack.Next().Get(outputPositionMode);
  203. console.log(`OUTPUT FROM ADDRESS ${currAddress}: ${output}`);
  204. }
  205. /**
  206. * Execute the Jump_If_True and Jump_If_False opcodes
  207. *
  208. * Jumps to a given address in memory if the value at next address is memory matches
  209. * the given true/false condition.
  210. *
  211. * @param {number} rawOpcode The opcode in memory used to make this call
  212. * @param {boolean} testCondition The value the memory value should be compared against
  213. * @returns {void}
  214. */
  215. Operation_JumpIf(rawOpcode, testCondition) {
  216. const paramMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  217. const jumpAddressMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  218. const param = this.stack.Next().Get(paramMode);
  219. const jumpAddress = this.stack.Next().Get(jumpAddressMode);
  220. const performJump = !!param == testCondition;
  221. if (performJump) {
  222. this.skipNext = true;
  223. this.stack.SetPointerAddress(jumpAddress);
  224. }
  225. }
  226. /**
  227. * Execute the various equality checking opcodes
  228. *
  229. * @param {number} rawOpcode The opcode in memory used to make this call
  230. * @param {number} testCondition The type of equality check to perform as defined in the computer's constructor
  231. * @returns {void}
  232. */
  233. Operation_Equality(rawOpcode, testCondition) {
  234. const operandLeftMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  235. const operandRightMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  236. const operandLeft = this.stack.Next().Get(operandLeftMode);
  237. const operandRight = this.stack.Next().Get(operandRightMode);
  238. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  239. let testPassed = false;
  240. switch (testCondition) {
  241. case this.EQUALITY.EQUALS:
  242. testPassed = operandLeft == operandRight;
  243. break;
  244. case this.EQUALITY.LESS_THAN:
  245. testPassed = operandLeft < operandRight;
  246. break;
  247. default:
  248. break;
  249. }
  250. this.stack.Put(outputPosition, Number(testPassed));
  251. }
  252. /**
  253. * Outputs the computer's stack to the console
  254. *
  255. * @param {boolean} [highlightPointer=false] Should the memory address of the current pointer be highlighted
  256. * @returns {void}
  257. */
  258. DumpMemory(highlightPointer = false) {
  259. let memory = this.stack.Dump();
  260. if (highlightPointer) {
  261. memory = memory.map((instruction, idx) => (idx == this.stack.pointer ? `{${instruction}}` : instruction));
  262. }
  263. console.log(util.inspect(memory, { breakLength: Infinity, colors: true, compact: true }));
  264. }
  265. /**
  266. * Resets the computer's memory to the value it was created with
  267. *
  268. * @returns {void}
  269. */
  270. Reset() {
  271. this.stack = new Stack(this._initialMemory);
  272. }
  273. /**
  274. * Sets the computer's memory to a new stack
  275. *
  276. * Note: This resets the computer's initial memory, so `Reset` will use this value
  277. *
  278. * @param {number[]} stack The new memory stack for the computer
  279. * @returns {void}
  280. */
  281. SetMemory(stack) {
  282. this._initialMemory = DeepClone(stack);
  283. this.stack = new Stack(stack);
  284. }
  285. };