From 6ee0408c2e31862845768099c803f6487ec28b94 Mon Sep 17 00:00:00 2001 From: arshita04 Date: Sun, 19 Dec 2021 23:29:07 +0530 Subject: [PATCH] feat : Added the solution to Finding Missing Digit for Github Externship --- Solution.js | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 61 insertions(+), 1 deletion(-) diff --git a/Solution.js b/Solution.js index b55091c..4219dc8 100644 --- a/Solution.js +++ b/Solution.js @@ -1 +1,61 @@ -// Write your code here +class FixEquation { + //this function extracts the operands for us , i.e A , B , C , D + getAllOperands = (equation) => { + let operands = equation.split(' '); + operands = operands.filter( + (operand) => + operand !== '+' && + operand !== '*' && + operand !== '=' + ); + return operands; + }; + + //This function finds the Operands containing the Question Mark + getIncompleteOperand = (operands) => { + let res; + operands.forEach((operand, i) => { + if (operand.includes('?')) res = i; + }); + return res; + }; + + //Function tot find the value of ? + findMissingDigitUtil = (operands, incompleteOperand) => { + switch (incompleteOperand) { + case 0: + return eval(`(${operands[3]} - ${operands[2]}) / ${operands[1]}`); + case 1: + return eval(`(${operands[3]} - ${operands[2]}) / ${operands[0]}`); + case 2: + return eval(`${operands[3]} - ${operands[0]} * ${operands[1]}`); + default: + return eval(`${operands[0]} * ${operands[1]} + ${operands[2]}`); + } + }; + + findMissingDigit = (equation) => { + const operands = this.getAllOperands(equation); + const incompleteOperand = this.getIncompleteOperand(operands); + let result = this.findMissingDigitUtil(operands, incompleteOperand); + result = result.toString(); + return result.length != operands[incompleteOperand].length + ? -1 + : result.charAt(operands[incompleteOperand].indexOf('?')); + }; +} + +// tests are in the form of A * B + C = D +const tests = [ + '42 * 47 + 2 = 1?76', + '4? * 47 + 2 = 1976', + '42 * ?7 + 2 = 1976', + '42 * ?47 + 2 = 1976', + '2 * 12? + 2 = 247', +]; + +const callFixEquation = new FixEquation(); +tests.forEach((test) => { + console.log('Equation: ', test, '\n'); + console.log('Returns: ', callFixEquation.findMissingDigit(test), '\n'); +}); \ No newline at end of file