This article mainly introduces how to select and equal to the number of n in the array using JavaScript. If you need it, you can refer to the problems in real life, the data model may be abstracted as follows:
Select several numbers from an array, and sum them to the specified values.
Most readers should have had online shopping experience. Online Shopping generally has a single collection function. If the reader buys 70 yuan of goods, but the price must be 100 yuan, the system will automatically recommend some goods, the total cost is about 100 RMB.
How does the system determine which products are recommended? This is actually the model we just mentioned. We can put the prices of Hot-selling goods in an array, and then use algorithms to find out which prices in the array are 30 yuan.
To put it bluntly, I would like to share with you the Algorithm Implementation of a JavaScript version.
Algorithm code:
Function getCombBySum (array, sum, tolerance, targetCount) {var util = {/* get combination from arrayarr: target arraynum: combination item lengthreturn: one array that contain combination arrays */getCombination: function (arr, num) {var r = []; (function f (t, a, n) {if (n = 0) {return r. push (t) ;}for (var I = 0, l =. length; I <= l-n; I ++) {f (t. concat (a [I]),. slice (I + 1), n-1) ;}) ([], arr, num); return r ;}, // take array index to a arraygetArrayIndex: function (array) {var I = 0, r = []; for (I = 0; ICall description:
Array: data source array. Required.
Sum: The sum of values. Required.
Tolerance: tolerance. If this parameter is not specified, the sum must be equal to the sum parameter. If this parameter is specified, the result may fluctuate within the tolerance range. Optional.
TargetCount: Number of operands. If this parameter is not specified, the result contains all possible conditions. If this parameter is specified, a fixed number of numbers can be filtered out. If this parameter is specified as 3, the result contains only three numbers. Optional.
Return Value: The returned result is an array of numbers. The elements in the inner array are operands, and the elements in the outer array are all possible results.