Computer.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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. /**
  94. * Run the computer
  95. *
  96. * Runs opcodes on the stack until either the a HALT command is
  97. * encountered, or an error is thrown.
  98. * @returns {void}
  99. */
  100. async Run() {
  101. while (this.Execute(this.stack.Get(ComputerParameterMode.IMMEDIATE_MODE)) === true) {
  102. if (this.options.debug.tickRate) {
  103. // Sleep
  104. // eslint-disable-next-line no-await-in-loop, no-promise-executor-return, arrow-parens
  105. await new Promise(resolve => setTimeout(resolve, this.options.debug.tickRate));
  106. }
  107. }
  108. }
  109. /**
  110. * Run the computer with an initial input value
  111. *
  112. * Runs opcodes on the stack until either the a HALT command is
  113. * encountered, or an error is thrown. Stores the input to be used
  114. * by the first INPUT opcode encountered.
  115. * @param {number[]} input An array of input values to initialize the comptuer with
  116. * @returns {void}
  117. */
  118. async RunWithInput(input) {
  119. this.runtimeInput = input;
  120. while (this.Execute(this.stack.Get(ComputerParameterMode.IMMEDIATE_MODE)) === true) {
  121. if (this.options.debug.tickRate) {
  122. // Sleep
  123. // eslint-disable-next-line no-await-in-loop, no-promise-executor-return, arrow-parens
  124. await new Promise(resolve => setTimeout(resolve, this.options.debug.tickRate));
  125. }
  126. }
  127. }
  128. /**
  129. * Execute a call using the provided opcode
  130. *
  131. * @param {number} rawOpcode A opcode to execute
  132. * @returns {boolean} False if the opcode was HALT, otherwise true
  133. */
  134. Execute(rawOpcode) {
  135. let status = true;
  136. this.skipNext = false;
  137. this.FollowExecution();
  138. const opcode = rawOpcode % 100;
  139. // console.log(`DEBUG: opcode: ${opcode}`);
  140. switch (opcode) {
  141. case this.OPCODES.ADD: {
  142. this.Operation_Add(rawOpcode);
  143. break;
  144. }
  145. case this.OPCODES.MULTIPLY: {
  146. this.Operation_Multiply(rawOpcode);
  147. break;
  148. }
  149. case this.OPCODES.INPUT: {
  150. this.Operation_Input();
  151. break;
  152. }
  153. case this.OPCODES.OUTPUT: {
  154. this.Operation_Output(rawOpcode);
  155. break;
  156. }
  157. case this.OPCODES.JUMP_IF_TRUE: {
  158. this.Operation_JumpIf(rawOpcode, true);
  159. break;
  160. }
  161. case this.OPCODES.JUMP_IF_FALSE: {
  162. this.Operation_JumpIf(rawOpcode, false);
  163. break;
  164. }
  165. case this.OPCODES.LESS_THAN: {
  166. this.Operation_Equality(rawOpcode, this.EQUALITY.LESS_THAN);
  167. break;
  168. }
  169. case this.OPCODES.EQUALS: {
  170. this.Operation_Equality(rawOpcode, this.EQUALITY.EQUALS);
  171. break;
  172. }
  173. case this.OPCODES.HALT:
  174. status = false;
  175. break;
  176. default:
  177. this.ThrowError(`Opcode ${opcode} not found`);
  178. }
  179. if (!this.skipNext) {
  180. this.stack.Next();
  181. }
  182. return status;
  183. }
  184. /**
  185. * Parse operands based on the current parameter mode
  186. *
  187. * When the int computer is in Immediate Mode, the values are returned
  188. * as-is. When in Position Mode, the operands are used as memory
  189. * addresses, and the values at those addresses are returned instead.
  190. *
  191. * @returns {number[]} The parsed list of operands
  192. */
  193. _ParseOperands(...operands) {
  194. if (this.parameterMode == ComputerParameterMode.IMMEDIATE_MODE) { return operands; }
  195. return operands.map((operand) => this.stack.Get(operand));
  196. }
  197. /**
  198. * Execute the Add opcode
  199. *
  200. * Adds two numbers and stores the result at the provided position
  201. * on the stack.
  202. *
  203. * Parses the operand Parameter Mode out of the opcode used to make
  204. * this call.
  205. *
  206. * @param {number} rawOpcode The opcode in memory used to make this call
  207. * @returns {void}
  208. */
  209. Operation_Add(rawOpcode) {
  210. const operandLeftMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  211. const operandRightMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  212. const operandLeft = this.stack.Next().Get(operandLeftMode);
  213. const operandRight = this.stack.Next().Get(operandRightMode);
  214. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  215. const newValue = operandLeft + operandRight;
  216. this.stack.Put(outputPosition, newValue);
  217. }
  218. /**
  219. * Execute the Multiply opcode
  220. *
  221. * Multiplies two numbers and stores the result at the provided
  222. * position on the stack.
  223. *
  224. * @param {number} rawOpcode The opcode in memory used to make this call
  225. * @returns {void}
  226. */
  227. Operation_Multiply(rawOpcode) {
  228. const operandLeftMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  229. const operandRightMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  230. const operandLeft = this.stack.Next().Get(operandLeftMode);
  231. const operandRight = this.stack.Next().Get(operandRightMode);
  232. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  233. const newValue = operandLeft * operandRight;
  234. this.stack.Put(outputPosition, newValue);
  235. }
  236. /**
  237. * Execute the Input opcode
  238. *
  239. * Checks to see if the computer's `runtimeInput` is set. If so, uses that
  240. * value as the input, and stores that at a specified address, and then
  241. * empties the `runtimeInput` value. If `runtimeInput` is empty, and if
  242. * the computer is set to accept input from the console, prompts the
  243. * user for input.
  244. *
  245. * @returns {void}
  246. */
  247. Operation_Input() {
  248. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  249. /** A variable to store the input in before putting it on the stack */
  250. let userInput;
  251. /** The input mode to use to get the value */
  252. let inputMode = this.options.inputModeMap.shift();
  253. // If no input mode was found, attempt to set on using the runtime options
  254. if (inputMode === undefined) {
  255. if (this.options.inputFromConsole) { inputMode = InputModes.INPUT_FROM_CONSOLE; }
  256. else { inputMode = InputModes.INPUT_FROM_RUNTIME_STACK; }
  257. }
  258. // Get the input based on the input mode
  259. switch (inputMode) {
  260. case InputModes.INPUT_FROM_RUNTIME_STACK: {
  261. userInput = this.runtimeInput.shift();
  262. if (userInput === undefined) {
  263. this.ThrowError("runtime Input array empty");
  264. }
  265. break;
  266. }
  267. case InputModes.INPUT_FROM_CONSOLE: {
  268. do {
  269. userInput = Number(prompt("Please enter a number: "));
  270. } while (Number.isNaN(userInput));
  271. break;
  272. }
  273. default:
  274. this.ThrowError("No input found");
  275. }
  276. // Put the input value onto the stack
  277. this.stack.Put(outputPosition, userInput);
  278. }
  279. /**
  280. * Execute the OUTPUT opcode
  281. *
  282. * @param {number} rawOpcode The opcode in memory used to make this call
  283. * @returns {void}
  284. */
  285. Operation_Output(rawOpcode) {
  286. const currAddress = this.options.outputToConsole ? this.stack.pointer : undefined;
  287. const outputPositionMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  288. const output = this.stack.Next().Get(outputPositionMode);
  289. if (this.options.outputToConsole) {
  290. console.log(`OUTPUT FROM ADDRESS ${currAddress}: ${output}`);
  291. }
  292. else if (this.outputComputer !== null) {
  293. this.outputComputer.RunWithInput(output);
  294. }
  295. else {
  296. this.outputValues.push(output);
  297. }
  298. }
  299. /**
  300. * Execute the Jump_If_True and Jump_If_False opcodes
  301. *
  302. * Jumps to a given address in memory if the value at next address is memory matches
  303. * the given true/false condition.
  304. *
  305. * @param {number} rawOpcode The opcode in memory used to make this call
  306. * @param {boolean} testCondition The value the memory value should be compared against
  307. * @returns {void}
  308. */
  309. Operation_JumpIf(rawOpcode, testCondition) {
  310. const paramMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  311. const jumpAddressMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  312. const param = this.stack.Next().Get(paramMode);
  313. const jumpAddress = this.stack.Next().Get(jumpAddressMode);
  314. const performJump = !!param == testCondition;
  315. if (performJump) {
  316. this.skipNext = true;
  317. this.stack.SetPointerAddress(jumpAddress);
  318. }
  319. }
  320. /**
  321. * Execute the various equality checking opcodes
  322. *
  323. * @param {number} rawOpcode The opcode in memory used to make this call
  324. * @param {number} testCondition The type of equality check to perform as defined in the computer's constructor
  325. * @returns {void}
  326. */
  327. Operation_Equality(rawOpcode, testCondition) {
  328. const operandLeftMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  329. const operandRightMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  330. const operandLeft = this.stack.Next().Get(operandLeftMode);
  331. const operandRight = this.stack.Next().Get(operandRightMode);
  332. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  333. let testPassed = false;
  334. switch (testCondition) {
  335. case this.EQUALITY.EQUALS:
  336. testPassed = operandLeft == operandRight;
  337. break;
  338. case this.EQUALITY.LESS_THAN:
  339. testPassed = operandLeft < operandRight;
  340. break;
  341. default:
  342. break;
  343. }
  344. this.stack.Put(outputPosition, Number(testPassed));
  345. }
  346. /**
  347. * Inspects various parts of the computer before every call to Execution
  348. *
  349. * Based on the debug options set at runtime, may output any combination of the
  350. * computer's core memory, the runtime input stack, and or the output values
  351. * array.
  352. *
  353. * @returns {void}
  354. */
  355. FollowExecution() {
  356. if (this.options.debug.followPointer) { this.DumpMemory(true); }
  357. if (this.options.debug.followRuntimeInput) { this.InspectProperty("Inputs", "runtimeInput"); }
  358. if (this.options.debug.followOutputValues) { this.InspectProperty("Outputs", "outputValues"); }
  359. }
  360. /**
  361. * Outputs the computer's stack to the console
  362. *
  363. * @param {boolean} [highlightPointer=false] Should the memory address of the current pointer be highlighted
  364. * @returns {void}
  365. */
  366. DumpMemory(highlightPointer = false) {
  367. let memory = this.stack.Dump();
  368. if (highlightPointer) {
  369. memory = memory.map((instruction, idx) => (idx == this.stack.pointer ? `{${instruction}}` : instruction));
  370. }
  371. this.InspectProperty("Memory", null, memory);
  372. }
  373. /**
  374. * Inspect a property of this object in the console
  375. *
  376. * @param {string} [outputMessage] An optional message to prepend the inspection with
  377. * @param {?string} [propertyName] The name of the Computer class property to inspect
  378. * @param {?unknown} [overrideValue] If provided, this value is inspected as-is instead of the class property
  379. * @returns {void}
  380. */
  381. InspectProperty(outputMessage = "", propertyName = null, overrideValue = null) {
  382. let toInspect;
  383. if (overrideValue !== null) {
  384. toInspect = overrideValue;
  385. }
  386. else if (this[propertyName] !== undefined) {
  387. toInspect = this[propertyName];
  388. }
  389. console.log(outputMessage, util.inspect(toInspect, { breakLength: Infinity, colors: true, compact: true }));
  390. }
  391. /**
  392. * Get a value from the unhandled OUTPUT values in FIFO order
  393. *
  394. * @returns {number} An unhandled value from an output call
  395. */
  396. FetchOutputValue() {
  397. return this.outputValues.shift();
  398. }
  399. /**
  400. * Resets the computer's memory to the value it was created with
  401. *
  402. * @returns {void}
  403. */
  404. Reset() {
  405. this.stack = new Stack(this._initialMemory);
  406. this.outputValues = [];
  407. this.outputComputer = null;
  408. this.options.inputModeMap = DeepClone(this.options._initialInputModeMap);
  409. }
  410. /**
  411. * Sets the computer's memory to a new stack
  412. *
  413. * Note: This resets the computer's initial memory, so `Reset` will use this value
  414. *
  415. * @param {number[]} stack The new memory stack for the computer
  416. * @returns {void}
  417. */
  418. SetMemory(stack) {
  419. this._initialMemory = DeepClone(stack);
  420. this.stack = new Stack(stack);
  421. }
  422. /**
  423. * Throws an error with the given message and a memory dump
  424. *
  425. * @param {string} [msg] The error message to display to the user
  426. * @returns {void}
  427. */
  428. ThrowError(msg = "") {
  429. throw new Error(`** IntCode Computer Error **\nError Message: ${msg}\nMemdump: ${JSON.stringify(this.stack.Dump())}\nPointer: ${this.stack.pointer}`);
  430. }
  431. };