0

我正在尝试编写一个算法来生成一个基本的减法问题。类似于 18-10-4=4。该算法应接受以下参数:

操作数最小值、操作数最大值、结果最小值、结果最大值、操作数数量

它应该为每个操作数在 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

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

4

1 回答 1

0

首先生成所需的结果。

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

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

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

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

于 2013-11-08T12:24:01.583 回答