Computer.js 19 KB

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