Computer.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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(rawOpcode);
  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. * @param {number} rawOpcode The opcode in memory used to make this call
  277. * @returns {void}
  278. */
  279. Operation_Input(rawOpcode) {
  280. const outputParamMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  281. const outputPosition = this.stack.Next().Get(outputParamMode);
  282. /** A variable to store the input in before putting it on the stack */
  283. let userInput;
  284. /** The input mode to use to get the value */
  285. let inputMode = this.options.inputModeMap.shift();
  286. // If no input mode was found, attempt to set on using the runtime options
  287. if (inputMode === undefined) {
  288. if (this.options.inputFromConsole) { inputMode = InputModes.INPUT_FROM_CONSOLE; }
  289. else { inputMode = InputModes.INPUT_FROM_RUNTIME_STACK; }
  290. }
  291. // Get the input based on the input mode
  292. switch (inputMode) {
  293. case InputModes.INPUT_FROM_RUNTIME_STACK: {
  294. userInput = this.runtimeInput.shift();
  295. // If no input was found, await input
  296. if (userInput === undefined) {
  297. // Set the stack back to the INPUT opcode
  298. this.stack.Prev();
  299. this.stack.Prev();
  300. // Set the awaitingInput flag
  301. this.awaitingInput = true;
  302. // Exit the function
  303. return;
  304. }
  305. this.awaitingInput = false;
  306. break;
  307. }
  308. case InputModes.INPUT_FROM_CONSOLE: {
  309. do {
  310. userInput = Number(prompt("Please enter a number: "));
  311. } while (Number.isNaN(userInput));
  312. break;
  313. }
  314. default:
  315. this.ThrowError("No input found");
  316. }
  317. // Put the input value onto the stack
  318. this.stack.Put(outputPosition, userInput);
  319. }
  320. /**
  321. * Execute the OUTPUT opcode
  322. *
  323. * @param {number} rawOpcode The opcode in memory used to make this call
  324. * @private
  325. * @returns {void}
  326. */
  327. Operation_Output(rawOpcode) {
  328. const currAddress = this.options.outputToConsole ? this.stack.pointer : undefined;
  329. const outputPositionMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  330. const output = this.stack.Next().Get(outputPositionMode);
  331. if (this.options.outputToConsole) {
  332. console.log(`OUTPUT FROM ADDRESS ${currAddress}: ${output}`);
  333. }
  334. else if (this.outputComputer !== null) {
  335. this.outputComputer.Input(output);
  336. }
  337. else {
  338. this.outputValues.push(output);
  339. }
  340. }
  341. /**
  342. * Execute the Jump_If_True and Jump_If_False opcodes
  343. *
  344. * Jumps to a given address in memory if the value at next address is memory matches
  345. * the given true/false condition.
  346. *
  347. * @param {number} rawOpcode The opcode in memory used to make this call
  348. * @param {boolean} testCondition The value the memory value should be compared against
  349. * @private
  350. * @returns {void}
  351. */
  352. Operation_JumpIf(rawOpcode, testCondition) {
  353. const paramMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  354. const jumpAddressMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  355. const param = this.stack.Next().Get(paramMode);
  356. const jumpAddress = this.stack.Next().Get(jumpAddressMode);
  357. const performJump = !!param == testCondition;
  358. if (performJump) {
  359. this.skipNext = true;
  360. this.stack.SetPointerAddress(jumpAddress);
  361. }
  362. }
  363. /**
  364. * Execute the various equality checking opcodes
  365. *
  366. * @param {number} rawOpcode The opcode in memory used to make this call
  367. * @param {number} testCondition The type of equality check to perform as defined in the computer's constructor
  368. * @private
  369. * @returns {void}
  370. */
  371. Operation_Equality(rawOpcode, testCondition) {
  372. const operandLeftMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  373. const operandRightMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  374. const operandLeft = this.stack.Next().Get(operandLeftMode);
  375. const operandRight = this.stack.Next().Get(operandRightMode);
  376. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  377. let testPassed = false;
  378. switch (testCondition) {
  379. case this.EQUALITY.EQUALS:
  380. testPassed = operandLeft == operandRight;
  381. break;
  382. case this.EQUALITY.LESS_THAN:
  383. testPassed = operandLeft < operandRight;
  384. break;
  385. default:
  386. break;
  387. }
  388. this.stack.Put(outputPosition, Number(testPassed));
  389. }
  390. /**
  391. * Adjusts the current relative base offset of the computer
  392. *
  393. * @param {number} rawOpcode The opcode in memory used to make this call
  394. * @returns {void}
  395. */
  396. Operation_ModifyRelativeBase(rawOpcode) {
  397. const operandMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  398. const adjustmentValue = this.stack.Next().Get(operandMode);
  399. this.stack.AdjustRelativeBaseOffset(adjustmentValue);
  400. }
  401. /**
  402. * Inspects various parts of the computer before every call to Execution
  403. *
  404. * Based on the debug options set at runtime, may output any combination of the
  405. * computer's core memory, the runtime input stack, and or the output values
  406. * array.
  407. *
  408. * @returns {void}
  409. */
  410. FollowExecution() {
  411. if (this.options.debug.followPointer) { this.DumpMemory(true); }
  412. if (this.options.debug.followRuntimeInput) { this.InspectProperty("Inputs", "runtimeInput"); }
  413. if (this.options.debug.followOutputValues) { this.InspectProperty("Outputs", "outputValues"); }
  414. }
  415. /**
  416. * Outputs the computer's stack to the console
  417. *
  418. * @param {boolean} [highlightPointer=false] Should the memory address of the current pointer be highlighted
  419. * @returns {void}
  420. */
  421. DumpMemory(highlightPointer = false) {
  422. let memory = this.stack.Dump();
  423. if (highlightPointer) {
  424. memory = memory.map((instruction, idx) => (idx == this.stack.pointer ? `{${instruction}}` : instruction));
  425. }
  426. this.InspectProperty("Memory", null, memory);
  427. }
  428. /**
  429. * Inspect a property of this object in the console
  430. *
  431. * @param {string} [outputMessage] An optional message to prepend the inspection with
  432. * @param {?string} [propertyName] The name of the Computer class property to inspect
  433. * @param {?unknown} [overrideValue] If provided, this value is inspected as-is instead of the class property
  434. * @returns {void}
  435. */
  436. InspectProperty(outputMessage = "", propertyName = null, overrideValue = null) {
  437. let toInspect;
  438. if (overrideValue !== null) {
  439. toInspect = overrideValue;
  440. }
  441. else if (this[propertyName] !== undefined) {
  442. toInspect = this[propertyName];
  443. }
  444. console.log(this.name, outputMessage, util.inspect(toInspect, { breakLength: Infinity, colors: true, compact: true }));
  445. }
  446. /**
  447. * Check if the computer has any values in the output array
  448. *
  449. * @returns {boolean} True or false if there are any values in the output array
  450. */
  451. HasOutput() {
  452. return !!this.outputValues.length;
  453. }
  454. /**
  455. * Get a value from the unhandled OUTPUT values in FIFO order
  456. *
  457. * @returns {number|undefined} An unhandled value from an output call, or undefined if the array is empty
  458. */
  459. FetchOutputValue() {
  460. return this.HasOutput() ? this.outputValues.shift() : undefined;
  461. }
  462. /**
  463. * Accept input from an external source
  464. *
  465. * The input given here is pushed onto the end of the computer's runtime
  466. * input array.
  467. *
  468. * @param {number} inputValue The number to push onto the runtime input array
  469. * @returns {void}
  470. */
  471. Input(inputValue) {
  472. this.runtimeInput.push(inputValue);
  473. if (this.running && this.awaitingInput) { this.Run(); }
  474. }
  475. /**
  476. * Resets the computer's memory to the value it was created with
  477. *
  478. * @returns {void}
  479. */
  480. Reset() {
  481. this.stack = new Stack(DeepClone(this._initialMemory));
  482. this.outputValues = [];
  483. this.options.inputModeMap = DeepClone(this.options._initialInputModeMap);
  484. this.running = false;
  485. this.awaitingInput = false;
  486. }
  487. /**
  488. * Sets the computer's memory to a new stack
  489. *
  490. * Note: This resets the computer's initial memory, so `Reset` will use this value
  491. *
  492. * @param {number[]} stack The new memory stack for the computer
  493. * @returns {void}
  494. */
  495. SetMemory(stack) {
  496. this._initialMemory = DeepClone(stack);
  497. this.stack = new Stack(stack);
  498. }
  499. /**
  500. * Throws an error with the given message and a memory dump
  501. *
  502. * @param {string} [msg] The error message to display to the user
  503. * @returns {void}
  504. */
  505. ThrowError(msg = "") {
  506. throw new Error(`** IntCode Computer Error **\nError Message: ${msg}\nMemdump: ${JSON.stringify(this.stack.Dump())}\nPointer: ${this.stack.pointer}`);
  507. }
  508. };