素人がプログラミングを勉強していたブログ

プログラミング、セキュリティ、英語、Webなどのブログ since 2008

連絡先: twitter: @javascripter にどうぞ。

4つの数字から四則演算で10になるのを見つける

function calc(a,b,c,d){
  var all = [add, sub, mul, div];
  var r = [];
  all.forEach(function(op1){
    all.forEach(function(op2){
      all.forEach(function(op3){
        if (op3(op2(op1(a, b), c), d) == 10){
          r.push("((" + a + op2s(op1) + b + ")" + op2s(op2) + c + ")" + op2s(op3) + d);
        }
      });
    });
  });
  return r.join("\n");
  function op2s(op){
    switch(op){
    case add: return "+";
    case sub: return "-";
    case mul: return "*";
    case div: return "/";
    }
  }
  function add(a, b) { return a + b }
  function sub(a, b) { return a - b }
  function mul(a, b) { return a * b }
  function div(a, b) { return a / b }
}

calc(5, 5, 5, 5);
/* ((5+5)+5)-5
   ((5+5)-5)+5
   ((5+5)*5)/5
   ((5+5)/5)*5
   ((5-5)+5)+5
   ((5*5)/5)+5
   ((5/5)*5)+5 */