从数组中随机选取一个元素,重复直到满足条件

pick a random element from an array, repeat until a condition is met

我有以下问题:我有一个固定的 sum [30] 和数字数组。我的问题是如何从总和中减去 num 的随机数,直到得到其余数 >1,<2,如 1.09 或 1.05?

var num= [0.99, 1.99, 2.99, 3.99, 4.99, 5.99, 6.99, 7.99, 8.99, 9.99];
var sum= [30];

console.log()

[30]

[0.99,
1.99,
0.99,
4.99,
6.99,
1.99,
2.99,
4.99
2.99]

[1.09]

console.log(再次)

[30]

[7.99,
6.99,
4.99,
6.99,
1.99,

[1.05]

这里需要用到0/1背包动态规划。这是标准的背包问题。

假设,您正在尝试输入第一个数字。您可以从总和中减去该数字或忽略该数字。所以你会尝试所有的可能性。这种taking/non-taking被称为0/1背包。

你可以从这个link学习0/1背包:https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/

该函数希望您给它一个目标总和(作为一个数字,而不是具有 1 个元素的数组)、可能的减法值数组和一个包含 2 个元素的目标数组 - 最小值和最大值。

var num = [0.99, 1.99, 2.99, 3.99, 4.99, 5.99, 6.99, 7.99, 8.99, 9.99];
var sum = 30;
var target = [1, 2];

function subtract(sum, num, target) {

  // pick a random index of whatever array is provided.
  const randomIndex = Math.round((num.length - 1) * Math.random());

  // * 100 / 100 is to successfully round to the 2nd decimal place.
  const newSum = Math.round((sum - num[randomIndex]) * 100) / 100;

  if (newSum >= target[1]) {
    console.log(`Subtracted ${num[randomIndex]}. Result is ${newSum}.`);
    subtract(newSum, num, target);
  }
  else if (newSum > target[0] && newSum <= target[1]) {
    console.log(`Subtracted ${num[randomIndex]}. Result is ${newSum}. Done.`);
  }
  else {
    console.log(`Couldn't subtract ${num[randomIndex]}. Result is ${sum}.`);
    subtract(sum, num, target);
  }
}

subtract(sum, num, target);