--- id: 5a23c84252665b21eecc8038 title: Subleq challengeType: 5 forumTopicId: 302328 dashedName: subleq --- # --description-- [Subleq](https://rosettacode.org/wiki/eso:Subleq) is an example of a [One-Instruction Set Computer (OISC)](https://en.wikipedia.org/wiki/One_instruction_set_computer). It is named after its only instruction, which is **SU**btract and **B**ranch if **L**ess than or **EQ**ual to zero. Your task is to create an interpreter which emulates such a machine. The machine's memory consists of an array of signed integers. Any reasonable word size is fine, but the memory must be able to hold negative as well as positive numbers. Execution begins with the instruction pointer aimed at the first word, which is address 0. It proceeds as follows:
15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0Which corresponds to something like this in a hypothetical assembler language:
start: zero, message, -1 message, -1, -1 neg1, start+1, -1 neg1, start+3, -1 zero, zero, start zero: 0 neg1: -1 message: "Hello, world!\n\0"# --instructions-- Write a function that takes an array of integers as a parameter. This represents the memory elements. The function should interpret the sequence and return the output string. For this task, assume that there is no standard input. # --hints-- `Subleq` should be a function. ```js assert(typeof Subleq == 'function'); ``` `Subleq([15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 0])` should return a string. ```js assert( typeof Subleq([ 15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 0 ]) == 'string' ); ``` `Subleq([15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 0])` should return `"Hello, world!"`. ```js assert.equal( Subleq([ 15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 0 ]), 'Hello, world!' ); ``` # --seed-- ## --seed-contents-- ```js function Subleq(mem) { } ``` # --solutions-- ```js function Subleq(mem) { var out = ''; var instructionPointer = 0; do { var a = mem[instructionPointer]; var b = mem[instructionPointer + 1]; if (a === -1) { } else if (b === -1) { out += String.fromCharCode(mem[a]); } else { mem[b] -= mem[a]; if (mem[b] < 1) { instructionPointer = mem[instructionPointer + 2]; continue; } } instructionPointer += 3; } while (instructionPointer >= 0); return out; } ```