Skip to content

Instantly share code, notes, and snippets.

@vinayverghese
Last active August 23, 2018 19:41
Show Gist options
  • Select an option

  • Save vinayverghese/64a0ecf40fefbfb70834722ccd02bdf6 to your computer and use it in GitHub Desktop.

Select an option

Save vinayverghese/64a0ecf40fefbfb70834722ccd02bdf6 to your computer and use it in GitHub Desktop.
Missing DigitII
// Missing DigitII
// Using the JavaScript language, have the function MissingDigitII(str) take the str parameter, which will be a simple mathematical formula with three numbers, a single operator (+, -, *, or /) and an equal sign (=) and return the two digits that complete the equation. In two of the numbers in the equation, there will be a single ? character, and your program should determine what digits are missing and return them separated by a space. For example, if str is "38?5 * 3 = 1?595" then your program should output 6 1.
// The ? character will always appear in both the first number and the last number in the mathematical expression. There will always be a unique solution.
function MissingDigitII(str) {
str=str.replace(/=/,'===')
for(i=0;i<10;i++){
for(j=0;j<10;j++){
temp=str.replace(/\?/,i)
temp=temp.replace(/\?/,j)
if(eval(temp)){
return i+' '+j
}
}
}
}
//console.log(MissingDigitII("38?5 * 3 = 1?595")); // 6 1
console.log(MissingDigitII("56? * 106 = 5?678")); // 3 9
//console.log(MissingDigitII("18?1 + 9 = 189?")); // 8 0
// solution 2
// function MissingDigitII(str) {
// for (let i = 0; i <= 9; i++) {
// for (let j = 0; j <= 9; j++) {
// let newStr = str.replace(/\?/, String(i)).replace(/\?/, String(j)).replace(/=/, '===');
// if (eval(newStr)) {
// return `${i} ${j}`;
// }
// }
// }
// }
// solution 3
// function MissingDigitII(str) {
// var slot1 = str.indexOf('?');
// var slot2 = str.lastIndexOf('?');
// for (var i = 0; i <= 9; i++) {
// for (var j = 0; j <= 9; j++) {
// var strArr = str.split('');
// strArr[slot1] = i;
// strArr[slot2] = j;
// strArr = strArr.join('').split(' ');
// var num1 = Number(strArr[0]);
// var num2 = Number(strArr[2]);
// var answer = Number(strArr[4]);
// var equastion = determineSign(strArr[1], num1, num2);
// if (equastion === answer)
// return [i, j].join(' ');
// }
// }
// function determineSign(str, num1, num2) {
// if (strArr[1] === '+')
// return (num1 + num2);
// if (strArr[1] === '-')
// return (num1 - num2);
// if (strArr[1] === '*')
// return (num1 * num2);
// if (strArr[1] === '/')
// return (num1 / num2);
// }
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment