The number of n (JavaScript implementations) that are selected and equal to the fixed value from the array

Source: Internet
Author: User

Real-life problems may be abstracted into such a data model:

Select several numbers from an array to add the sum of the numbers to the specified value.

Most readers should have the experience of online shopping, online shopping will generally have a single function, if the reader bought 70 yuan of merchandise, but must be full of 100 yuan to pack mail, then the system will automatically recommend some products, add up almost 100 dollars.

How does the system determine which products to recommend? This is actually the model just mentioned, we can put the price of hot goods into an array, and then use the algorithm to find out what the price of the array and 30 yuan.

Needless to say, the side dishes for everyone to share a JavaScript version of the algorithm implementation.

Algorithm code:

1 functionGetcombbysum (array,sum,tolerance,targetcount) {2   varUtil = {3     /*4 get combination from array5 arr:target Array6 num:combination Item Length7 Return:one array that contain combination arrays8     */9Getcombination:function(arr, num) {Ten       varR=[]; One(functionf (t,a,n) A       { -           if(n==0) -           { the               returnR.push (t); -           } -            for(varI=0,l=a.length; i<=l-n; i++) -           { +F (T.concat (A[i]), A.slice (i+1), n-1); -           } + }) ([],arr,num); A       returnR; at     }, -     //Take the array index to a array -Getarrayindex:function(array) { -       vari = 0, -R = []; -        for(i = 0;i<array.length;i++){ in R.push (i); -       } to        +       returnR; -     } the},logic = { *     //sort the array,then get what ' s we need $Init:function(array,sum) {Panax Notoginseng       //Clone Array -       var_array =Array.concat (), theR = [], +i = 0; A       //Sort by ASC the_array.sort (function(A, b) { +         returnAb; -       }); $       //Get all number when it's less than or equal sum $        for(i = 0;i<_array.length;i++){ -         if(_array[i]<=sum) { - R.push (_array[i]); the}Else{ -            Break;Wuyi         } the       } -        Wu       returnR; -     }, About     //Important function $Corefunction(array,sum,arrayindex,count,r) { -       vari = 0, -K = 0, -Combarray = [], A_sum = 0, +_cca = [], the_cache = []; -        $       if(Count = =_returnmark) { the         return; the       } the       //get current count combination theCombarray =util.getcombination (arrayindex,count); -        for(i = 0;i<combarray.length;i++){ in_cca =Combarray[i]; the_sum = 0; the_cache = []; About         //calculate the sum from combination the          for(k = 0;k<_cca.length;k++){ the_sum + =Array[_cca[k]]; the _cache.push (Array[_cca[k]); +         } -         if(Math.Abs (_sum-sum) <=_tolerance) { the R.push (_cache);Bayi         }       the       } the        -Logic.core (array,sum,arrayindex,count-1, R); -     } the      the   }, theR = [], the_array = [], -_targetcount = 0, the_tolerance = 0, the_returnmark = 0; the   94   //Check Data the_targetcount = Targetcount | |_targetcount; the_tolerance = Tolerance | |_tolerance; the   98_array =Logic.init (array,sum); About   if(_targetcount) { -_returnmark = _targetcount-1;101   }102   103Logic.core (_array,sum,util.getarrayindex (_array), (_targetcount | |_array.length), R);104    the   returnR;106}
View Code

Invocation Description:

Array: Data source arrays. Must be selected.

sum: Sums of sum. Must be selected.

tolerance: tolerance. If you do not specify this parameter, the sum must be equal to the summation parameter, which specifies that the result will float within the tolerance range. Optional.

Targetcount: Number of operands. If you do not specify this parameter, the result contains all possible cases, specifying that this parameter can filter out a fixed number of additions, and if specified as 3, then the result contains only three numbers added. Optional.

return Value: returns the array structure of arrays, the elements in the inner array are operands, and the elements in the outer array are all possible results.

original content, reproduced annotated source!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.