![](/img/trans.png)
[英]Get and SUM the value of dynamic and multiple element using jQuery/Javascript
[英]How to use javascript to get the element value to match sum?
有兩個數組,總和為 9。
它只會返回 true 或 false
IE:
array1[1,2,4,9] sum=9 返回 false
array2[1,2,4,5] sum=9 返回真
它需要數組中的兩個數字來匹配總和。
我在我的 JS 中嘗試了什么:
function hasPairWithSum(arr, sum) { var len = arr.length; for(var i =0; i<len-1; i++) { for(var j = i+1;j<len; j++) { if (arr[i] + arr[j] === sum) return true; } } return false; } console.log(hasPairWithSum([1, 2, 4, 9], 9)); console.log(hasPairWithSum([1, 2, 4, 5], 9));
好吧,我想要一種不同的方式來達到目標
function ContainsSum(arr, sum) { return arr.some((n, i) => arr.some((m, x) => n + m === sum && i != x)) } console.log(ContainsSum([1, 2, 4, 9], 9)); console.log(ContainsSum([1, 2, 4, 5], 9));
一個快速的解決方案是這樣的
function twoSum(arr, S) { var hashTable = {}; // check each element in array for (var i = 0; i < arr.length; i++) { // calculate S - current element var sumMinusElement = S - arr[i]; // check if this number exists in hash table // if so then we found a pair of numbers that sum to S if (hashTable[sumMinusElement.toString()] !== undefined) { return true; } // add the current number to the hash table hashTable[arr[i].toString()] = arr[i]; } // return false as default return false; } console.log(twoSum([3, 5, 2, -4, 8, 11], 7));
它使用哈希表
這是使用生成器函數和遞歸生成對的不同方法,以及includes
迭代器和謂詞並從生成器中提取項目以針對謂詞測試它們的includes
函數:
function* getPairs(arr) { if (!arr.length) return false; const [h, ...tail] = arr; for (let v of tail) { console.log(`[${h}, ${v}]`); yield [h, v]; } yield* getPairs(tail); } function includes(iterator, predicate) { let result = iterator.next(); while (!result.done) { if (predicate(...result.value)) { return true; } result = iterator.next(); } return false; } const sumEquals = sum => (a, b) => a + b === sum; const pairEquals = ([a, b]) => (i, j) => a === i && b === j; console.log(includes(getPairs([2, 4, 9]), sumEquals(9))); console.log(includes(getPairs([2, 4, 5]), sumEquals(6))); console.log(includes(getPairs([2, 4, 5]), pairEquals([2, 5])));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.