用于创建数学减法方程的简单JavaScript算法

时间:2013-11-08 06:43:32

标签: javascript algorithm math

我正在尝试编写一个会产生基本减法问题的算法。像18-10-4 = 4的东西。该算法应接受以下参数:

Operand Min,Operand Max,Result Min,Result Max,操作数

它应该在oMin和oMax之间为每个操作数选择多个随机数,并在rMin和rMax之间为结果选择一个随机数。所以像这样:

var generateSubtractionProblem = function (oMin, oMax, rMin, rMax, oQuantity) {
    var result,
        operands = []
        maxDiff = oMax - (oMin * (oQuantity - 1)),
        minDiff = oMin - (oMax * (oQuantity - 1)),;

    // Pick result
    // Generate operands within range that when subtracted produce result
    if (rMax < minDiff || rMin > maxDiff) {
      console.log('Cannot produce result');
      return {
        result: 2,
        operands: [4, 2]
      };
    }

    if (maxDiff < rMax) {
      console.log('Max difference is ' + maxDiff);
      rMax = maxDiff;
    }

    result = this.randomInRange(rMin, rMax, rPrecision);

    for (var i = 0; i < oQuantity; i += 1) {
      switch (i) {
        case 0:
          operands[i] = this.randomInRange((oMin * (oQuantity - 1)) + result, oMax, oPrecision);
          break;
        case 1:
          operands[i] = operands[i - 1] - result;
          break;
        default:
          operands[i] = this.randomInRange(oMin, (oMin * (oQuantity - i)), oPrecision);
          break;
      }
    }

    return {
        result: result,
        operands: operands
    }
}

generateSubtractionProblem(5, 20, 0, 5, 3);
// { result: 4, operands: [18, 10, 4] }... 18-10-4=4

任何语言的例子都会有所帮助。

1 个答案:

答案 0 :(得分:0)

首先生成所需的结果。

接下来生成第一个操作数。它的最小值必须至少为'result + operandMin *(numberOfOperands - 1)。

生成剩余的操作数。它们的范围必须介于

之间

(firstOperand - sum(otherOperands)) - (numberOfOperands - numberOfGeneratedOperands) * OperandMax

(firstOperand - sum(otherOperands)) - (numberOfOperands - numberOfGeneratedOperands) * OperandMin