JavaScript selects n numbers from the array and is equal to the fixed value, and the number of javascript

Source: Internet
Author: User
Tags javascript array

JavaScript selects n numbers from the array and is equal to the fixed value, and the number of javascript

Problems in real life may be abstracted into such a data model:

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=a.length; i<=l-n; i++){f(t.concat(a[i]), a.slice(i+1), n-1);}})([],arr,num);return r;},//take array index to a arraygetArrayIndex: function(array) {var i = 0,r = [];for(i = 0;i<array.length;i++){r.push(i);}return r;}},logic = {//sort the array,then get what's we needinit: function(array,sum) {//clone arrayvar _array = array.concat(),r = [],i = 0;//sort by asc_array.sort(function(a,b){return a - b;});//get all number when it's less than or equal sumfor(i = 0;i<_array.length;i++){if(_array[i]<=sum){r.push(_array[i]);}else{break;}}return r;},//important functioncore: function(array,sum,arrayIndex,count,r){var i = 0,k = 0,combArray = [],_sum = 0,_cca = [],_cache = [];if(count == _returnMark){return;}//get current count combinationcombArray = util.getCombination(arrayIndex,count);for(i = 0;i<combArray.length;i++){_cca = combArray[i];_sum = 0;_cache = [];//calculate the sum from combinationfor(k = 0;k<_cca.length;k++){_sum += array[_cca[k]];_cache.push(array[_cca[k]]);}if(Math.abs(_sum-sum) <= _tolerance){r.push(_cache);} }logic.core(array,sum,arrayIndex,count-1,r);}},r = [],_array = [],_targetCount = 0,_tolerance = 0,_returnMark = 0;//check data_targetCount = targetCount || _targetCount;_tolerance = tolerance || _tolerance;_array = logic.init(array,sum);if(_targetCount){_returnMark = _targetCount-1;}logic.core(_array,sum,util.getArrayIndex(_array),(_targetCount || _array.length),r);return r;}

Call 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.


Javascript array determines the number of elements with the same value

How efficient should the landlord be? It's easy. In short, I think it's quite difficult to traverse the two. here is a little bit better. Sort the array first and traverse it. I don't know if it's a little easier. I even don't know... after sorting, traversal may be faster ..
Var strArray = new Array ();
StrArray = {2,100, 2,100, 0}

StrArray. sort (function (a, B) {return a-B ;});

In javascript, how does one Delete the element of a value in an array?

Test = newArray (); Array. prototype. removeByValue = function (val) {for (vari = 0; I <this. length; I ++) {if (this [I] = val) {this. splice (I, 1); break ;}} test [0] = 'apple'; test [1] = 'ball'; test [2] = 'cat '; test [3] = 'Dog'; alert ("Array before removing elements:" + test); test. removeByValue ('cat'); alert ("Array after removing elements:" + test );
Reference: hi.baidu.com/...1.html

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.