Computer.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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. break;
  167. }
  168. this.Operation_Input();
  169. break;
  170. }
  171. case this.OPCODES.OUTPUT: {
  172. this.Operation_Output(rawOpcode);
  173. break;
  174. }
  175. case this.OPCODES.JUMP_IF_TRUE: {
  176. this.Operation_JumpIf(rawOpcode, true);
  177. break;
  178. }
  179. case this.OPCODES.JUMP_IF_FALSE: {
  180. this.Operation_JumpIf(rawOpcode, false);
  181. break;
  182. }
  183. case this.OPCODES.LESS_THAN: {
  184. this.Operation_Equality(rawOpcode, this.EQUALITY.LESS_THAN);
  185. break;
  186. }
  187. case this.OPCODES.EQUALS: {
  188. this.Operation_Equality(rawOpcode, this.EQUALITY.EQUALS);
  189. break;
  190. }
  191. case this.OPCODES.HALT:
  192. this.running = false;
  193. status = false;
  194. break;
  195. default:
  196. this.ThrowError(`Opcode ${opcode} not found`);
  197. }
  198. if (!this.skipNext) {
  199. this.stack.Next();
  200. }
  201. return status;
  202. }
  203. /**
  204. * Parse operands based on the current parameter mode
  205. *
  206. * When the int computer is in Immediate Mode, the values are returned
  207. * as-is. When in Position Mode, the operands are used as memory
  208. * addresses, and the values at those addresses are returned instead.
  209. *
  210. * @returns {number[]} The parsed list of operands
  211. */
  212. _ParseOperands(...operands) {
  213. if (this.parameterMode == ComputerParameterMode.IMMEDIATE_MODE) { return operands; }
  214. return operands.map((operand) => this.stack.Get(operand));
  215. }
  216. /**
  217. * Execute the Add opcode
  218. *
  219. * Adds two numbers and stores the result at the provided position
  220. * on the stack.
  221. *
  222. * Parses the operand Parameter Mode out of the opcode used to make
  223. * this call.
  224. *
  225. * @param {number} rawOpcode The opcode in memory used to make this call
  226. * @returns {void}
  227. */
  228. Operation_Add(rawOpcode) {
  229. const operandLeftMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  230. const operandRightMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  231. const operandLeft = this.stack.Next().Get(operandLeftMode);
  232. const operandRight = this.stack.Next().Get(operandRightMode);
  233. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  234. const newValue = operandLeft + operandRight;
  235. this.stack.Put(outputPosition, newValue);
  236. }
  237. /**
  238. * Execute the Multiply opcode
  239. *
  240. * Multiplies two numbers and stores the result at the provided
  241. * position on the stack.
  242. *
  243. * @param {number} rawOpcode The opcode in memory used to make this call
  244. * @returns {void}
  245. */
  246. Operation_Multiply(rawOpcode) {
  247. const operandLeftMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  248. const operandRightMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  249. const operandLeft = this.stack.Next().Get(operandLeftMode);
  250. const operandRight = this.stack.Next().Get(operandRightMode);
  251. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  252. const newValue = operandLeft * operandRight;
  253. this.stack.Put(outputPosition, newValue);
  254. }
  255. /**
  256. * Execute the Input opcode
  257. *
  258. * Checks to see if the computer's `runtimeInput` is set. If so, uses that
  259. * value as the input, and stores that at a specified address, and then
  260. * empties the `runtimeInput` value. If `runtimeInput` is empty, and if
  261. * the computer is set to accept input from the console, prompts the
  262. * user for input.
  263. *
  264. * @returns {void}
  265. */
  266. Operation_Input() {
  267. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  268. /** A variable to store the input in before putting it on the stack */
  269. let userInput;
  270. /** The input mode to use to get the value */
  271. let inputMode = this.options.inputModeMap.shift();
  272. // If no input mode was found, attempt to set on using the runtime options
  273. if (inputMode === undefined) {
  274. if (this.options.inputFromConsole) { inputMode = InputModes.INPUT_FROM_CONSOLE; }
  275. else { inputMode = InputModes.INPUT_FROM_RUNTIME_STACK; }
  276. }
  277. // Get the input based on the input mode
  278. switch (inputMode) {
  279. case InputModes.INPUT_FROM_RUNTIME_STACK: {
  280. userInput = this.runtimeInput.shift();
  281. // If no input was found, await input
  282. if (userInput === undefined) {
  283. // Set the stack back to the INPUT opcode
  284. this.stack.Prev();
  285. this.stack.Prev();
  286. // Set the awaitingInput flag
  287. this.awaitingInput = true;
  288. // Exit the function
  289. return;
  290. }
  291. this.awaitingInput = false;
  292. break;
  293. }
  294. case InputModes.INPUT_FROM_CONSOLE: {
  295. do {
  296. userInput = Number(prompt("Please enter a number: "));
  297. } while (Number.isNaN(userInput));
  298. break;
  299. }
  300. default:
  301. this.ThrowError("No input found");
  302. }
  303. // Put the input value onto the stack
  304. this.stack.Put(outputPosition, userInput);
  305. }
  306. /**
  307. * Execute the OUTPUT opcode
  308. *
  309. * @param {number} rawOpcode The opcode in memory used to make this call
  310. * @returns {void}
  311. */
  312. Operation_Output(rawOpcode) {
  313. const currAddress = this.options.outputToConsole ? this.stack.pointer : undefined;
  314. const outputPositionMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  315. const output = this.stack.Next().Get(outputPositionMode);
  316. if (this.options.outputToConsole) {
  317. console.log(`OUTPUT FROM ADDRESS ${currAddress}: ${output}`);
  318. }
  319. else if (this.outputComputer !== null) {
  320. this.outputComputer.RunWithInput(output);
  321. }
  322. else {
  323. this.outputValues.push(output);
  324. }
  325. }
  326. /**
  327. * Execute the Jump_If_True and Jump_If_False opcodes
  328. *
  329. * Jumps to a given address in memory if the value at next address is memory matches
  330. * the given true/false condition.
  331. *
  332. * @param {number} rawOpcode The opcode in memory used to make this call
  333. * @param {boolean} testCondition The value the memory value should be compared against
  334. * @returns {void}
  335. */
  336. Operation_JumpIf(rawOpcode, testCondition) {
  337. const paramMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  338. const jumpAddressMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  339. const param = this.stack.Next().Get(paramMode);
  340. const jumpAddress = this.stack.Next().Get(jumpAddressMode);
  341. const performJump = !!param == testCondition;
  342. if (performJump) {
  343. this.skipNext = true;
  344. this.stack.SetPointerAddress(jumpAddress);
  345. }
  346. }
  347. /**
  348. * Execute the various equality checking opcodes
  349. *
  350. * @param {number} rawOpcode The opcode in memory used to make this call
  351. * @param {number} testCondition The type of equality check to perform as defined in the computer's constructor
  352. * @returns {void}
  353. */
  354. Operation_Equality(rawOpcode, testCondition) {
  355. const operandLeftMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  356. const operandRightMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  357. const operandLeft = this.stack.Next().Get(operandLeftMode);
  358. const operandRight = this.stack.Next().Get(operandRightMode);
  359. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  360. let testPassed = false;
  361. switch (testCondition) {
  362. case this.EQUALITY.EQUALS:
  363. testPassed = operandLeft == operandRight;
  364. break;
  365. case this.EQUALITY.LESS_THAN:
  366. testPassed = operandLeft < operandRight;
  367. break;
  368. default:
  369. break;
  370. }
  371. this.stack.Put(outputPosition, Number(testPassed));
  372. }
  373. /**
  374. * Inspects various parts of the computer before every call to Execution
  375. *
  376. * Based on the debug options set at runtime, may output any combination of the
  377. * computer's core memory, the runtime input stack, and or the output values
  378. * array.
  379. *
  380. * @returns {void}
  381. */
  382. FollowExecution() {
  383. if (this.options.debug.followPointer) { this.DumpMemory(true); }
  384. if (this.options.debug.followRuntimeInput) { this.InspectProperty("Inputs", "runtimeInput"); }
  385. if (this.options.debug.followOutputValues) { this.InspectProperty("Outputs", "outputValues"); }
  386. }
  387. /**
  388. * Outputs the computer's stack to the console
  389. *
  390. * @param {boolean} [highlightPointer=false] Should the memory address of the current pointer be highlighted
  391. * @returns {void}
  392. */
  393. DumpMemory(highlightPointer = false) {
  394. let memory = this.stack.Dump();
  395. if (highlightPointer) {
  396. memory = memory.map((instruction, idx) => (idx == this.stack.pointer ? `{${instruction}}` : instruction));
  397. }
  398. this.InspectProperty("Memory", null, memory);
  399. }
  400. /**
  401. * Inspect a property of this object in the console
  402. *
  403. * @param {string} [outputMessage] An optional message to prepend the inspection with
  404. * @param {?string} [propertyName] The name of the Computer class property to inspect
  405. * @param {?unknown} [overrideValue] If provided, this value is inspected as-is instead of the class property
  406. * @returns {void}
  407. */
  408. InspectProperty(outputMessage = "", propertyName = null, overrideValue = null) {
  409. let toInspect;
  410. if (overrideValue !== null) {
  411. toInspect = overrideValue;
  412. }
  413. else if (this[propertyName] !== undefined) {
  414. toInspect = this[propertyName];
  415. }
  416. console.log(outputMessage, util.inspect(toInspect, { breakLength: Infinity, colors: true, compact: true }));
  417. }
  418. /**
  419. * Check if the computer has any values in the output array
  420. *
  421. * @returns {boolean} True or false if there are any values in the output array
  422. */
  423. HasOutput() {
  424. return !!this.outputValues.length;
  425. }
  426. /**
  427. * Get a value from the unhandled OUTPUT values in FIFO order
  428. *
  429. * @returns {number|undefined} An unhandled value from an output call, or undefined if the array is empty
  430. */
  431. FetchOutputValue() {
  432. return this.HasOutput() ? this.outputValues.shift() : undefined;
  433. }
  434. /**
  435. * Accept input from an external source
  436. *
  437. * The input given here is pushed onto the end of the computer's runtime
  438. * input array.
  439. *
  440. * @param {number} inputValue The number to push onto the runtime input array
  441. * @returns {void}
  442. */
  443. Input(inputValue) {
  444. this.runtimeInput.push(inputValue);
  445. if (this.running && this.awaitingInput) { this.Run(); }
  446. }
  447. /**
  448. * Resets the computer's memory to the value it was created with
  449. *
  450. * @returns {void}
  451. */
  452. Reset() {
  453. this.stack = new Stack(this._initialMemory);
  454. this.outputValues = [];
  455. this.outputComputer = null;
  456. this.options.inputModeMap = DeepClone(this.options._initialInputModeMap);
  457. }
  458. /**
  459. * Sets the computer's memory to a new stack
  460. *
  461. * Note: This resets the computer's initial memory, so `Reset` will use this value
  462. *
  463. * @param {number[]} stack The new memory stack for the computer
  464. * @returns {void}
  465. */
  466. SetMemory(stack) {
  467. this._initialMemory = DeepClone(stack);
  468. this.stack = new Stack(stack);
  469. }
  470. /**
  471. * Throws an error with the given message and a memory dump
  472. *
  473. * @param {string} [msg] The error message to display to the user
  474. * @returns {void}
  475. */
  476. ThrowError(msg = "") {
  477. throw new Error(`** IntCode Computer Error **\nError Message: ${msg}\nMemdump: ${JSON.stringify(this.stack.Dump())}\nPointer: ${this.stack.pointer}`);
  478. }
  479. };