简体   繁体   English

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

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

I have the following issue: I have a fixed sum [30] and array of numbers. 我有以下问题:我有一个固定的总和[30]和一个数字数组。 My questions is how do I subtract random numbers of num from sum until i get the rest number >1, <2 like 1.09 or 1.05? 我的问题是如何从总和中减去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() 的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(again) 执行console.log(再次)

[30] [30]

[7.99,
6.99,
4.99,
6.99,
1.99,

[1.05]

You need to use 0/1 knapsack dynamic programming here. 您需要在此处使用0/1 背包动态编程。 It is standard knapsack problem. 这是标准的背包问题。

Suppose, you are trying in first number. 假设您正在尝试输入第一个数字。 You may either subtract this number from sum or ignore this number. 您可以从总和中减去该数字,也可以忽略该数字。 So you will try all possibilities. 因此,您将尝试所有可能。 This kind of taking/non-taking is called 0/1 knapsack. 这种采取/不采取行动被称为0/1背包。

You can learn 0/1 knapsack from this link: https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/ 您可以通过以下链接学习0/1背包: https//www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/

The function expects you to give it a target sum (as a number, not array with 1 element), the array of possible subtraction values and a target array of 2 elements - min and max. 该函数希望给它一个目标和(作为一个数字,而不是包含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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM