Computer.js 20 KB

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