Generate all combinations of mathematical expressions that add to target (Java homework/interview)

前端 未结 3 914
你的背包
你的背包 2021-01-31 05:39

I\'ve tried to solve the problem below for a coding challenge but could not finish it in 1 hour. I have an idea on how the algorithm works but I\'m not quite sure how to best im

3条回答
  •  南旧
    南旧 (楼主)
    2021-01-31 06:30

    My Javascript implementation:
    Will improve the code using web worker later on

    // was not allowed to use eval , so this is my replacement for the eval function.
    function evaluate(expr) {
      return new Function('return '+expr)();
     }
     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+"
    "; } 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); } } }; function f(input,total) { calc("",input,total); }

提交回复
热议问题