Created
August 29, 2019 06:31
-
-
Save marvinsjsu/4126ba4b5843a85805e2fca8f7c26ec0 to your computer and use it in GitHub Desktop.
circuitsOutput
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function circuitsOutput(circuitsExpression) { | |
// Write your code here | |
let output = []; | |
let stack = []; | |
let operations = new Set(['&', '|', '!']); | |
let values = new Set([0, 1]); | |
let circuit, frame, value; | |
for (let i = 0; i < circuitsExpression.length; i++) { | |
circuit = circuitsExpression[i]; | |
for (let j = 0; j < circuit.length; j++) { | |
if (circuit[j] === '[') { | |
frame = new Frame(); | |
stack.push(frame); | |
} else if (operations.has(circuit[j])) { | |
frame.setOperation(circuit[j]); | |
} else if (values.has(parseInt(circuit[j]))) { | |
frame.addArg(parseInt(circuit[j])); | |
} else if (circuit[j] === ']') { | |
frame = stack.pop(); | |
value = frame.evaluate(); | |
if (stack.length > 0) { | |
frame = stack[stack.length - 1]; | |
frame.addArg(value); | |
} else { | |
output.push(value); | |
} | |
} | |
} | |
} | |
return output; | |
} | |
function Frame() { | |
this.operation = null; | |
this.args = []; | |
return { | |
args: this.args, | |
setOperation: (operation) => { | |
this.operation = operation; | |
}, | |
addArg: (val) => { | |
this.args.push(val); | |
}, | |
evaluate: () => { | |
if (this.operation === '|') { | |
return this.args.includes(1) ? 1 : 0; | |
} else if (this.operation === '&') { | |
return this.args.includes(0) ? 0 : 1; | |
} else if (this.operation === '!') { | |
return this.args[0] === 0 ? 1 : 0; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment