Computer.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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 { DeepClone } = require("./common");
  6. module.exports = class Computer {
  7. /**
  8. * An Intcode Computer for the Advent of Code 2019 challenge
  9. *
  10. * @author Apis Necros
  11. *
  12. * @param {number[]} stack The initial memory to load into the computer
  13. * @param {Object} options Options that can be enabled within the computer
  14. * @param {boolean} options.followPointer When true, the memory will be dumped every call to Execute with the current instruction highlighted
  15. * @param {number} options.tickRate The number of milliseconds between calls to Execute. Initializes to 0.
  16. * @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.
  17. * @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.
  18. */
  19. constructor(stack, options = {}) {
  20. this._initialMemory = DeepClone(stack);
  21. this.stack = new Stack(stack);
  22. this.OPCODES = {
  23. ADD: 1,
  24. MULTIPLY: 2,
  25. INPUT: 3,
  26. OUTPUT: 4,
  27. JUMP_IF_TRUE: 5,
  28. JUMP_IF_FALSE: 6,
  29. LESS_THAN: 7,
  30. EQUALS: 8,
  31. HALT: 99,
  32. };
  33. this.EQUALITY = {
  34. EQUALS: 0,
  35. LESS_THAN: 1,
  36. };
  37. this.parameterMode = ComputerParameterMode.POSITION_MODE;
  38. /**
  39. * Whether the Execute loop should skip moving the pointer after running the opcode
  40. *
  41. * Some opcodes, such as JUMP_IF_TRUE set the stack pointer, and as such shouldn't have
  42. * the Execute function move it after the opcode finishes executing.
  43. */
  44. this.skipNext = false;
  45. this.options = {
  46. followPointer: options.followPointer ?? false,
  47. tickRate: options.tickRate ?? 0,
  48. inputFromConsole: options.inputFromConsole ?? false,
  49. outputToConsole: options.outputToConsole ?? false,
  50. };
  51. /**
  52. * A function to pass the value from OUTPUT opcodes to
  53. *
  54. * If the outputToConsole option is false, and a function is provided here,
  55. * any values from an OUTPUT opcode will be passed here.
  56. * @type {?Computer}
  57. */
  58. this.outputComputer = null;
  59. /**
  60. * An input value provided at runtime
  61. *
  62. * This value will be passed to the first INPUT opcode made by the computer,
  63. * and will then be cleared. If the program being ran tries to make another
  64. * call to INPUT, and `options.inputFromConsole` is false, then an error
  65. * will be thrown.
  66. * @type {number}
  67. */
  68. this.runtimeInput = null;
  69. /**
  70. * An array of outputs from the computer
  71. *
  72. * Outputs from the computer that weren't output to the console, or to a
  73. * callback function.
  74. *
  75. * Ideally, when not in outputToConsole mode, the computer should only ever have
  76. * one output, but I'm not certain that will be the case. In that case, this array
  77. * will have the outputs in chronological order.
  78. * @type {number[]}
  79. */
  80. this.outputValues = [];
  81. }
  82. /**
  83. * Run the computer
  84. *
  85. * Runs opcodes on the stack until either the a HALT command is
  86. * encountered, or an error is thrown.
  87. * @returns {void}
  88. */
  89. async Run() {
  90. while (this.Execute(this.stack.Get(ComputerParameterMode.IMMEDIATE_MODE)) === true) {
  91. if (this.options.tickRate) {
  92. // Sleep
  93. // eslint-disable-next-line no-await-in-loop, no-promise-executor-return, arrow-parens
  94. await new Promise(resolve => setTimeout(resolve, this.options.tickRate));
  95. }
  96. }
  97. }
  98. /**
  99. * Run the computer with an initial input value
  100. *
  101. * Runs opcodes on the stack until either the a HALT command is
  102. * encountered, or an error is thrown. Stores the input to be used
  103. * by the first INPUT opcode encountered.
  104. * @param {number} input The input value to initialize the comptuer with.
  105. * @returns {void}
  106. */
  107. async RunWithInput(input) {
  108. this.runtimeInput = input;
  109. while (this.Execute(this.stack.Get(ComputerParameterMode.IMMEDIATE_MODE)) === true) {
  110. if (this.options.tickRate) {
  111. // Sleep
  112. // eslint-disable-next-line no-await-in-loop, no-promise-executor-return, arrow-parens
  113. await new Promise(resolve => setTimeout(resolve, this.options.tickRate));
  114. }
  115. }
  116. }
  117. /**
  118. * Execute a call using the provided opcode
  119. *
  120. * @param {number} rawOpcode A opcode to execute
  121. * @returns {boolean} False if the opcode was HALT, otherwise true
  122. */
  123. Execute(rawOpcode) {
  124. let status = true;
  125. this.skipNext = false;
  126. if (this.options.followPointer) {
  127. this.DumpMemory(true);
  128. }
  129. const opcode = rawOpcode % 100;
  130. // console.log(`DEBUG: opcode: ${opcode}`);
  131. switch (opcode) {
  132. case this.OPCODES.ADD: {
  133. this.Operation_Add(rawOpcode);
  134. break;
  135. }
  136. case this.OPCODES.MULTIPLY: {
  137. this.Operation_Multiply(rawOpcode);
  138. break;
  139. }
  140. case this.OPCODES.INPUT: {
  141. this.Operation_Input();
  142. break;
  143. }
  144. case this.OPCODES.OUTPUT: {
  145. this.Operation_Output(rawOpcode);
  146. break;
  147. }
  148. case this.OPCODES.JUMP_IF_TRUE: {
  149. this.Operation_JumpIf(rawOpcode, true);
  150. break;
  151. }
  152. case this.OPCODES.JUMP_IF_FALSE: {
  153. this.Operation_JumpIf(rawOpcode, false);
  154. break;
  155. }
  156. case this.OPCODES.LESS_THAN: {
  157. this.Operation_Equality(rawOpcode, this.EQUALITY.LESS_THAN);
  158. break;
  159. }
  160. case this.OPCODES.EQUALS: {
  161. this.Operation_Equality(rawOpcode, this.EQUALITY.EQUALS);
  162. break;
  163. }
  164. case this.OPCODES.HALT:
  165. status = false;
  166. break;
  167. default:
  168. throw Error(`Opcode ${opcode} not found\nMemdump: ${JSON.stringify(this.stack.Dump())}\nPointer: ${this.stack.pointer}`);
  169. }
  170. if (!this.skipNext) {
  171. this.stack.Next();
  172. }
  173. return status;
  174. }
  175. /**
  176. * Parse operands based on the current parameter mode
  177. *
  178. * When the int computer is in Immediate Mode, the values are returned
  179. * as-is. When in Position Mode, the operands are used as memory
  180. * addresses, and the values at those addresses are returned instead.
  181. *
  182. * @returns {number[]} The parsed list of operands
  183. */
  184. _ParseOperands(...operands) {
  185. if (this.parameterMode == ComputerParameterMode.IMMEDIATE_MODE) { return operands; }
  186. return operands.map((operand) => this.stack.Get(operand));
  187. }
  188. /**
  189. * Execute the Add opcode
  190. *
  191. * Adds two numbers and stores the result at the provided position
  192. * on the stack.
  193. *
  194. * Parses the operand Parameter Mode out of the opcode used to make
  195. * this call.
  196. *
  197. * @param {number} rawOpcode The opcode in memory used to make this call
  198. * @returns {void}
  199. */
  200. Operation_Add(rawOpcode) {
  201. const operandLeftMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  202. const operandRightMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  203. const operandLeft = this.stack.Next().Get(operandLeftMode);
  204. const operandRight = this.stack.Next().Get(operandRightMode);
  205. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  206. const newValue = operandLeft + operandRight;
  207. this.stack.Put(outputPosition, newValue);
  208. }
  209. /**
  210. * Execute the Multiply opcode
  211. *
  212. * Multiplies two numbers and stores the result at the provided
  213. * position on the stack.
  214. *
  215. * @param {number} rawOpcode The opcode in memory used to make this call
  216. * @returns {void}
  217. */
  218. Operation_Multiply(rawOpcode) {
  219. const operandLeftMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  220. const operandRightMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  221. const operandLeft = this.stack.Next().Get(operandLeftMode);
  222. const operandRight = this.stack.Next().Get(operandRightMode);
  223. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  224. const newValue = operandLeft * operandRight;
  225. this.stack.Put(outputPosition, newValue);
  226. }
  227. /**
  228. * Execute the Input opcode
  229. *
  230. * Checks to see if the computer's `runtimeInput` is set. If so, uses that
  231. * value as the input, and stores that at a specified address, and then
  232. * empties the `runtimeInput` value. If `runtimeInput` is empty, and if
  233. * the computer is set to accept input from the console, prompts the
  234. * user for input.
  235. *
  236. * @returns {void}
  237. */
  238. Operation_Input() {
  239. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  240. let userInput;
  241. if (this.runtimeInput !== null) {
  242. userInput = this.runtimeInput;
  243. this.runtimeInput = null;
  244. }
  245. else if (this.options.inputFromConsole) {
  246. do {
  247. userInput = Number(prompt("Please enter a number: "));
  248. } while (Number.isNaN(userInput));
  249. }
  250. else {
  251. throw new Error("No input found");
  252. }
  253. this.stack.Put(outputPosition, userInput);
  254. }
  255. /**
  256. * Execute the OUTPUT opcode
  257. *
  258. * @param {number} rawOpcode The opcode in memory used to make this call
  259. * @returns {void}
  260. */
  261. Operation_Output(rawOpcode) {
  262. const currAddress = this.options.outputToConsole ? this.stack.pointer : undefined;
  263. const outputPositionMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  264. const output = this.stack.Next().Get(outputPositionMode);
  265. if (this.options.outputToConsole) {
  266. console.log(`OUTPUT FROM ADDRESS ${currAddress}: ${output}`);
  267. }
  268. else if (this.outputComputer !== null) {
  269. this.outputComputer.RunWithInput(output);
  270. }
  271. else {
  272. this.outputValues.push(output);
  273. }
  274. }
  275. /**
  276. * Execute the Jump_If_True and Jump_If_False opcodes
  277. *
  278. * Jumps to a given address in memory if the value at next address is memory matches
  279. * the given true/false condition.
  280. *
  281. * @param {number} rawOpcode The opcode in memory used to make this call
  282. * @param {boolean} testCondition The value the memory value should be compared against
  283. * @returns {void}
  284. */
  285. Operation_JumpIf(rawOpcode, testCondition) {
  286. const paramMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  287. const jumpAddressMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  288. const param = this.stack.Next().Get(paramMode);
  289. const jumpAddress = this.stack.Next().Get(jumpAddressMode);
  290. const performJump = !!param == testCondition;
  291. if (performJump) {
  292. this.skipNext = true;
  293. this.stack.SetPointerAddress(jumpAddress);
  294. }
  295. }
  296. /**
  297. * Execute the various equality checking opcodes
  298. *
  299. * @param {number} rawOpcode The opcode in memory used to make this call
  300. * @param {number} testCondition The type of equality check to perform as defined in the computer's constructor
  301. * @returns {void}
  302. */
  303. Operation_Equality(rawOpcode, testCondition) {
  304. const operandLeftMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 1);
  305. const operandRightMode = ComputerParameterMode.ParseParameterMode(rawOpcode, 2);
  306. const operandLeft = this.stack.Next().Get(operandLeftMode);
  307. const operandRight = this.stack.Next().Get(operandRightMode);
  308. const outputPosition = this.stack.Next().Get(ComputerParameterMode.IMMEDIATE_MODE);
  309. let testPassed = false;
  310. switch (testCondition) {
  311. case this.EQUALITY.EQUALS:
  312. testPassed = operandLeft == operandRight;
  313. break;
  314. case this.EQUALITY.LESS_THAN:
  315. testPassed = operandLeft < operandRight;
  316. break;
  317. default:
  318. break;
  319. }
  320. this.stack.Put(outputPosition, Number(testPassed));
  321. }
  322. /**
  323. * Outputs the computer's stack to the console
  324. *
  325. * @param {boolean} [highlightPointer=false] Should the memory address of the current pointer be highlighted
  326. * @returns {void}
  327. */
  328. DumpMemory(highlightPointer = false) {
  329. let memory = this.stack.Dump();
  330. if (highlightPointer) {
  331. memory = memory.map((instruction, idx) => (idx == this.stack.pointer ? `{${instruction}}` : instruction));
  332. }
  333. console.log(util.inspect(memory, { breakLength: Infinity, colors: true, compact: true }));
  334. }
  335. /**
  336. * Get a value from the unhandled OUTPUT values in FIFO order
  337. *
  338. * @returns {number} An unhandled value from an output call
  339. */
  340. FetchOutputValue() {
  341. return this.outputValues.shift();
  342. }
  343. /**
  344. * Resets the computer's memory to the value it was created with
  345. *
  346. * @returns {void}
  347. */
  348. Reset() {
  349. this.stack = new Stack(this._initialMemory);
  350. }
  351. /**
  352. * Sets the computer's memory to a new stack
  353. *
  354. * Note: This resets the computer's initial memory, so `Reset` will use this value
  355. *
  356. * @param {number[]} stack The new memory stack for the computer
  357. * @returns {void}
  358. */
  359. SetMemory(stack) {
  360. this._initialMemory = DeepClone(stack);
  361. this.stack = new Stack(stack);
  362. }
  363. };