Computer.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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 InputModes = require("./InputModes");
  6. const { DeepClone } = require("./common");
  7. module.exports = class Computer {
  8. /**
  9. * An Intcode Computer for the Advent of Code 2019 challenge
  10. *
  11. * @author Apis Necros
  12. *
  13. * @param {number[]} stack The initial memory to load into the computer
  14. * @param {Object} options Options that can be enabled within the computer
  15. * @param {object} options.debug A set of debugging options
  16. * @param {number} options.debug.tickRate The number of milliseconds between calls to Execute. Initializes to 0.
  17. * @param {boolean} options.debug.followPointer When true, the memory will be dumped during every call to Execute with the current instruction highlighted
  18. * @param {boolean} options.debug.followRuntimeInput When true, the runtime input array will be dumped during every call to Execute
  19. * @param {boolean} options.debug.followOutputValues When true, the output values array will be dumped during every call to Execute
  20. * @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.
  21. * @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.
  22. * @param {number[]} options.inputModeMap Map calls to the INPUT opcode to user input or the input array
  23. */
  24. constructor(stack, options = {}) {
  25. this._initialMemory = DeepClone(stack);
  26. this.stack = new Stack(stack);
  27. this.OPCODES = {
  28. ADD: 1,
  29. MULTIPLY: 2,
  30. INPUT: 3,
  31. OUTPUT: 4,
  32. JUMP_IF_TRUE: 5,
  33. JUMP_IF_FALSE: 6,
  34. LESS_THAN: 7,
  35. EQUALS: 8,
  36. HALT: 99,
  37. };
  38. this.EQUALITY = {
  39. EQUALS: 0,
  40. LESS_THAN: 1,
  41. };
  42. this.parameterMode = ComputerParameterMode.POSITION_MODE;
  43. /**
  44. * Whether the Execute loop should skip moving the pointer after running the opcode
  45. *
  46. * Some opcodes, such as JUMP_IF_TRUE set the stack pointer, and as such shouldn't have
  47. * the Execute function move it after the opcode finishes executing.
  48. */
  49. this.skipNext = false;
  50. this.options = {
  51. debug: {
  52. followPointer: options?.debug?.followPointer ?? false,
  53. followRuntimeInput: options?.debug?.followRuntimeInput ?? false,
  54. followOutputValues: options?.debug?.followOutputValues ?? false,
  55. tickRate: options?.debug?.tickRate ?? 0,
  56. },
  57. inputFromConsole: options.inputFromConsole ?? false,
  58. outputToConsole: options.outputToConsole ?? false,
  59. inputModeMap: options.inputModeMap ?? [],
  60. _initialInputModeMap: options.inputModeMap ?? [],
  61. };
  62. /**
  63. * A function to pass the value from OUTPUT opcodes to
  64. *
  65. * If the outputToConsole option is false, and a function is provided here,
  66. * any values from an OUTPUT opcode will be passed here.
  67. * @type {?Computer}
  68. */
  69. this.outputComputer = null;
  70. /**
  71. * An array of input values provided at runtime
  72. *
  73. * This value will be passed to the first INPUT opcode made by the computer,
  74. * and will then be cleared. If the program being ran tries to make another
  75. * call to INPUT, and `options.inputFromConsole` is false, then an error
  76. * will be thrown.
  77. * @type {number[]}
  78. */
  79. this.runtimeInput = [];
  80. /**
  81. * An array of outputs from the computer
  82. *
  83. * Outputs from the computer that weren't output to the console, or to a
  84. * callback function.
  85. *
  86. * Ideally, when not in outputToConsole mode, the computer should only ever have
  87. * one output, but I'm not certain that will be the case. In that case, this array
  88. * will have the outputs in chronological order.
  89. * @type {number[]}
  90. */
  91. this.outputValues = [];
  92. /**
  93. * Is the computer currently running
  94. * @type {boolean}
  95. */
  96. this.running = false;
  97. /**
  98. * Is the computer waiting for input
  99. *
  100. * Triggered by the INPUT opcode when the runtimeInputs array is empty
  101. * @type {boolean}
  102. */
  103. this.awaitingInput = false;
  104. }
  105. /**
  106. * Run the computer
  107. *
  108. * Runs opcodes on the stack until either the a HALT command is
  109. * encountered, or an error is thrown.
  110. * @returns {void}
  111. */
  112. async Run() {
  113. while (this.Execute(this.stack.Get(ComputerParameterMode.IMMEDIATE_MODE)) === true) {
  114. if (this.options.debug.tickRate) {
  115. // Sleep
  116. // eslint-disable-next-line no-await-in-loop, no-promise-executor-return, arrow-parens
  117. await new Promise(resolve => setTimeout(resolve, this.options.debug.tickRate));
  118. }
  119. }
  120. }
  121. /**
  122. * Run the computer with an initial input value
  123. *
  124. * Runs opcodes on the stack until either the a HALT command is
  125. * encountered, or an error is thrown. Stores the input to be used
  126. * by the first INPUT opcode encountered.
  127. * @param {number[]} input An array of input values to initialize the comptuer with
  128. * @returns {void}
  129. */
  130. async RunWithInput(input) {
  131. this.runtimeInput = input;
  132. while (this.Execute(this.stack.Get(ComputerParameterMode.IMMEDIATE_MODE)) === true) {
  133. if (this.options.debug.tickRate) {
  134. // Sleep
  135. // eslint-disable-next-line no-await-in-loop, no-promise-executor-return, arrow-parens
  136. await new Promise(resolve => setTimeout(resolve, this.options.debug.tickRate));
  137. }
  138. }
  139. }
  140. /**
  141. * Execute a call using the provided opcode
  142. *
  143. * @param {number} rawOpcode A opcode to execute
  144. * @returns {boolean} False if the opcode was HALT, otherwise true
  145. */
  146. Execute(rawOpcode) {
  147. let status = true;
  148. this.running = true;
  149. this.skipNext = false;
  150. this.FollowExecution();
  151. const opcode = rawOpcode % 100;
  152. // console.log(`DEBUG: opcode: ${opcode}`);
  153. switch (opcode) {
  154. case this.OPCODES.ADD: {
  155. this.Operation_Add(rawOpcode);
  156. break;
  157. }
  158. case this.OPCODES.MULTIPLY: {
  159. this.Operation_Multiply(rawOpcode);
  160. break;
  161. }
  162. case this.OPCODES.INPUT: {
  163. // If we're awaiting input, and still haven't received any, keep waiting
  164. if (this.awaitingInput == true && this.runtimeInput.length == 0) {
  165. this.skipNext = true;
  166. status = false;
  167. break;
  168. }
  169. this.Operation_Input();
  170. break;
  171. }
  172. case this.OPCODES.OUTPUT: {
  173. this.Operation_Output(rawOpcode);
  174. break;
  175. }
  176. case this.OPCODES.JUMP_IF_TRUE: {
  177. this.Operation_JumpIf(rawOpcode, true);
  178. break;
  179. }
  180. case this.OPCODES.JUMP_IF_FALSE: {
  181. this.Operation_JumpIf(rawOpcode, false);
  182. break;
  183. }
  184. case this.OPCODES.LESS_THAN: {
  185. this.Operation_Equality(rawOpcode, this.EQUALITY.LESS_THAN);
  186. break;
  187. }
  188. case this.OPCODES.EQUALS: {
  189. this.Operation_Equality(rawOpcode, this.EQUALITY.EQUALS);
  190. break;
  191. }
  192. case this.OPCODES.HALT:
  193. this.running = false;
  194. status = false;
  195. break;
  196. default:
  197. this.ThrowError(`Opcode ${opcode} not found`);
  198. }
  199. if (!this.skipNext) {
  200. this.stack.Next();
  201. }
  202. return status;
  203. }
  204. /**
  205. * Parse operands based on the current parameter mode
  206. *
  207. * When the int computer is in Immediate Mode, the values are returned
  208. * as-is. When in Position Mode, the operands are used as memory
  209. * addresses, and the values at those addresses are returned instead.
  210. *
  211. * @private
  212. * @returns {number[]} The parsed list of operands
  213. */
  214. _ParseOperands(...operands) {
  215. if (this.parameterMode == ComputerParameterMode.IMMEDIATE_MODE) { return operands; }
  216. return operands.map((operand) => this.stack.Get(operand));
  217. }
  218. /**
  219. * Execute the Add opcode
  220. *
  221. * Adds two numbers and stores the result at the provided position
  222. * on the stack.
  223. *
  224. * Parses the operand Parameter Mode out of the opcode used to make
  225. * this call.
  226. *
  227. * @param {number} rawOpcode The opcode in memory used to make this call
  228. * @private
  229. * @returns {void}
  230. */
  231. Operation_Add(rawOpcode) {
  232. const operandLeftMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  233. const operandRightMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  234. const operandLeft = this.stack.Next().Get(operandLeftMode);
  235. const operandRight = this.stack.Next().Get(operandRightMode);
  236. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  237. const newValue = operandLeft + operandRight;
  238. this.stack.Put(outputPosition, newValue);
  239. }
  240. /**
  241. * Execute the Multiply opcode
  242. *
  243. * Multiplies two numbers and stores the result at the provided
  244. * position on the stack.
  245. *
  246. * @param {number} rawOpcode The opcode in memory used to make this call
  247. * @private
  248. * @returns {void}
  249. */
  250. Operation_Multiply(rawOpcode) {
  251. const operandLeftMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  252. const operandRightMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  253. const operandLeft = this.stack.Next().Get(operandLeftMode);
  254. const operandRight = this.stack.Next().Get(operandRightMode);
  255. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  256. const newValue = operandLeft * operandRight;
  257. this.stack.Put(outputPosition, newValue);
  258. }
  259. /**
  260. * Execute the Input opcode
  261. *
  262. * Checks to see if the computer's `runtimeInput` is set. If so, uses that
  263. * value as the input, and stores that at a specified address, and then
  264. * empties the `runtimeInput` value. If `runtimeInput` is empty, and if
  265. * the computer is set to accept input from the console, prompts the
  266. * user for input.
  267. *
  268. * @private
  269. * @returns {void}
  270. */
  271. Operation_Input() {
  272. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  273. /** A variable to store the input in before putting it on the stack */
  274. let userInput;
  275. /** The input mode to use to get the value */
  276. let inputMode = this.options.inputModeMap.shift();
  277. // If no input mode was found, attempt to set on using the runtime options
  278. if (inputMode === undefined) {
  279. if (this.options.inputFromConsole) { inputMode = InputModes.INPUT_FROM_CONSOLE; }
  280. else { inputMode = InputModes.INPUT_FROM_RUNTIME_STACK; }
  281. }
  282. // Get the input based on the input mode
  283. switch (inputMode) {
  284. case InputModes.INPUT_FROM_RUNTIME_STACK: {
  285. userInput = this.runtimeInput.shift();
  286. // If no input was found, await input
  287. if (userInput === undefined) {
  288. // Set the stack back to the INPUT opcode
  289. this.stack.Prev();
  290. this.stack.Prev();
  291. // Set the awaitingInput flag
  292. this.awaitingInput = true;
  293. // Exit the function
  294. return;
  295. }
  296. this.awaitingInput = false;
  297. break;
  298. }
  299. case InputModes.INPUT_FROM_CONSOLE: {
  300. do {
  301. userInput = Number(prompt("Please enter a number: "));
  302. } while (Number.isNaN(userInput));
  303. break;
  304. }
  305. default:
  306. this.ThrowError("No input found");
  307. }
  308. // Put the input value onto the stack
  309. this.stack.Put(outputPosition, userInput);
  310. }
  311. /**
  312. * Execute the OUTPUT opcode
  313. *
  314. * @param {number} rawOpcode The opcode in memory used to make this call
  315. * @private
  316. * @returns {void}
  317. */
  318. Operation_Output(rawOpcode) {
  319. const currAddress = this.options.outputToConsole ? this.stack.pointer : undefined;
  320. const outputPositionMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  321. const output = this.stack.Next().Get(outputPositionMode);
  322. if (this.options.outputToConsole) {
  323. console.log(`OUTPUT FROM ADDRESS ${currAddress}: ${output}`);
  324. }
  325. else if (this.outputComputer !== null) {
  326. this.outputComputer.RunWithInput(output);
  327. }
  328. else {
  329. this.outputValues.push(output);
  330. }
  331. }
  332. /**
  333. * Execute the Jump_If_True and Jump_If_False opcodes
  334. *
  335. * Jumps to a given address in memory if the value at next address is memory matches
  336. * the given true/false condition.
  337. *
  338. * @param {number} rawOpcode The opcode in memory used to make this call
  339. * @param {boolean} testCondition The value the memory value should be compared against
  340. * @private
  341. * @returns {void}
  342. */
  343. Operation_JumpIf(rawOpcode, testCondition) {
  344. const paramMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  345. const jumpAddressMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  346. const param = this.stack.Next().Get(paramMode);
  347. const jumpAddress = this.stack.Next().Get(jumpAddressMode);
  348. const performJump = !!param == testCondition;
  349. if (performJump) {
  350. this.skipNext = true;
  351. this.stack.SetPointerAddress(jumpAddress);
  352. }
  353. }
  354. /**
  355. * Execute the various equality checking opcodes
  356. *
  357. * @param {number} rawOpcode The opcode in memory used to make this call
  358. * @param {number} testCondition The type of equality check to perform as defined in the computer's constructor
  359. * @private
  360. * @returns {void}
  361. */
  362. Operation_Equality(rawOpcode, testCondition) {
  363. const operandLeftMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  364. const operandRightMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  365. const operandLeft = this.stack.Next().Get(operandLeftMode);
  366. const operandRight = this.stack.Next().Get(operandRightMode);
  367. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  368. let testPassed = false;
  369. switch (testCondition) {
  370. case this.EQUALITY.EQUALS:
  371. testPassed = operandLeft == operandRight;
  372. break;
  373. case this.EQUALITY.LESS_THAN:
  374. testPassed = operandLeft < operandRight;
  375. break;
  376. default:
  377. break;
  378. }
  379. this.stack.Put(outputPosition, Number(testPassed));
  380. }
  381. /**
  382. * Inspects various parts of the computer before every call to Execution
  383. *
  384. * Based on the debug options set at runtime, may output any combination of the
  385. * computer's core memory, the runtime input stack, and or the output values
  386. * array.
  387. *
  388. * @returns {void}
  389. */
  390. FollowExecution() {
  391. if (this.options.debug.followPointer) { this.DumpMemory(true); }
  392. if (this.options.debug.followRuntimeInput) { this.InspectProperty("Inputs", "runtimeInput"); }
  393. if (this.options.debug.followOutputValues) { this.InspectProperty("Outputs", "outputValues"); }
  394. }
  395. /**
  396. * Outputs the computer's stack to the console
  397. *
  398. * @param {boolean} [highlightPointer=false] Should the memory address of the current pointer be highlighted
  399. * @returns {void}
  400. */
  401. DumpMemory(highlightPointer = false) {
  402. let memory = this.stack.Dump();
  403. if (highlightPointer) {
  404. memory = memory.map((instruction, idx) => (idx == this.stack.pointer ? `{${instruction}}` : instruction));
  405. }
  406. this.InspectProperty("Memory", null, memory);
  407. }
  408. /**
  409. * Inspect a property of this object in the console
  410. *
  411. * @param {string} [outputMessage] An optional message to prepend the inspection with
  412. * @param {?string} [propertyName] The name of the Computer class property to inspect
  413. * @param {?unknown} [overrideValue] If provided, this value is inspected as-is instead of the class property
  414. * @returns {void}
  415. */
  416. InspectProperty(outputMessage = "", propertyName = null, overrideValue = null) {
  417. let toInspect;
  418. if (overrideValue !== null) {
  419. toInspect = overrideValue;
  420. }
  421. else if (this[propertyName] !== undefined) {
  422. toInspect = this[propertyName];
  423. }
  424. console.log(outputMessage, util.inspect(toInspect, { breakLength: Infinity, colors: true, compact: true }));
  425. }
  426. /**
  427. * Check if the computer has any values in the output array
  428. *
  429. * @returns {boolean} True or false if there are any values in the output array
  430. */
  431. HasOutput() {
  432. return !!this.outputValues.length;
  433. }
  434. /**
  435. * Get a value from the unhandled OUTPUT values in FIFO order
  436. *
  437. * @returns {number|undefined} An unhandled value from an output call, or undefined if the array is empty
  438. */
  439. FetchOutputValue() {
  440. return this.HasOutput() ? this.outputValues.shift() : undefined;
  441. }
  442. /**
  443. * Accept input from an external source
  444. *
  445. * The input given here is pushed onto the end of the computer's runtime
  446. * input array.
  447. *
  448. * @param {number} inputValue The number to push onto the runtime input array
  449. * @returns {void}
  450. */
  451. Input(inputValue) {
  452. this.runtimeInput.push(inputValue);
  453. if (this.running && this.awaitingInput) { this.Run(); }
  454. }
  455. /**
  456. * Resets the computer's memory to the value it was created with
  457. *
  458. * @returns {void}
  459. */
  460. Reset() {
  461. this.stack = new Stack(this._initialMemory);
  462. this.outputValues = [];
  463. this.outputComputer = null;
  464. this.options.inputModeMap = DeepClone(this.options._initialInputModeMap);
  465. }
  466. /**
  467. * Sets the computer's memory to a new stack
  468. *
  469. * Note: This resets the computer's initial memory, so `Reset` will use this value
  470. *
  471. * @param {number[]} stack The new memory stack for the computer
  472. * @returns {void}
  473. */
  474. SetMemory(stack) {
  475. this._initialMemory = DeepClone(stack);
  476. this.stack = new Stack(stack);
  477. }
  478. /**
  479. * Throws an error with the given message and a memory dump
  480. *
  481. * @param {string} [msg] The error message to display to the user
  482. * @returns {void}
  483. */
  484. ThrowError(msg = "") {
  485. throw new Error(`** IntCode Computer Error **\nError Message: ${msg}\nMemdump: ${JSON.stringify(this.stack.Dump())}\nPointer: ${this.stack.pointer}`);
  486. }
  487. };