Last active
September 9, 2022 21:46
-
-
Save SergioAFern/6bb4dce46244931459ae to your computer and use it in GitHub Desktop.
Triplebyte Pi Programming Question in Javascript
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
// Sergio Fernandez made on March 2016 | |
// [email protected] | |
// www.dominicanvoice.com | |
// this is my Javascript solution to the TripelByte programming quesion. | |
// TASK: given a string of number and a target value. | |
// show all the arithmatic combinaitons of the input numbers that add up to the target value. | |
// note: the input numbers remain in the order they were inputed. | |
// For example: | |
// f("314159265358", 27182) should print: | |
// 3 + 1 - 415 * 92 + 65358 = 27182 | |
// 3 * 1 + 4 * 159 + 26535 + 8 = 27182 | |
// 3 / 1 + 4 * 159 + 26535 + 8 = 27182 | |
// 3 * 14 * 15 + 9 + 26535 + 8 = 27182 | |
// 3141 * 5 / 9 * 26 / 5 * 3 - 5 * 8 = 27182 | |
// this functions replaces eval.. since Triplebyte said I could not use eval. | |
function evaluate(expr) { | |
return new Function('return '+expr)(); | |
} | |
// this is teh core of the program, it calculates all the combinations of the string | |
function calc(expr,input,target) { | |
if (input.length==1) { | |
// I'm not allowed to use eval, so I will use my function evaluate | |
//if (eval(expr+input)==target) console.log(expr+input+"="+target); | |
if (evaluate(expr+input)==target) document.body.innerHTML+=expr+input+"="+target+"<br>"; | |
} | |
else { | |
for(var i=1;i<=input.length;i++) { | |
var left=input.substring(0,i); | |
var right=input.substring(i); | |
['+','-','*','/'].forEach(function(oper) { | |
calc(expr+left+oper,right,target); | |
},this); | |
} | |
} | |
}; | |
// this is a shell function to confirm to triplebytes sugested function name and input | |
function f(input,total) { | |
calc("",input,total); | |
} | |
f("314159265",27); | |
// very slow performance for a large number.. will incorporate web workers to improve performance. | |
// f("314159265358",27182); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment