I want someone to show me a simpler way to write my sum_pairs(arr,sum) function which return the first 2 values in arr that adds up to form sum . My code works but i think it is complex , i need someone to simplify it . So, this is my code .
function sum_pairs(ints,s){
let arr=[];
let arrOfIndex=[];
for(let i=0;i<ints.length;i++){
for(let a=0;a<ints.length;a++){
if(a!=i){
if(ints[i]+ints[a]==s){
let newArr=[ints[i],ints[a]];
let sumIndex=i+a;
arr.push(newArr);
arrOfIndex.push(sumIndex);
}
}
}
}
let sortedArray=arrOfIndex.sort((a,b)=>a-b);
return arr[arrOfIndex.indexOf(sortedArray[0])];
}
console.log(sum_pairs([7,2,5,8,4,3],7))//[2,5]
You could take a single loop with a hash table for the second pair element.
It works by looking up the actual value and if found, then this value is part of a pair. In this case return the delta of the sum and the value and the value.
If not found, add a new entry to the hash table with the missing value for getting a sum.
Proceed until found or end.
function sum_pairs(ints, s) {
var hash = Object.create(null),
i,
value;
for (i = 0; i < ints.length; i++) {
value = ints[i];
if (hash[value]) return [s - value, value];
hash[s - value] = true;
}
}
console.log(sum_pairs([7, 2, 5, 8, 4, 3], 7));
All pairs (with an array without duplicates)
function allPairs(ints, s) {
var hash = Object.create(null),
i,
value,
pairs = [];
for (i = 0; i < ints.length; i++) {
value = ints[i];
if (hash[value]) pairs.push([s - value, value]);
hash[s - value] = true;
}
return pairs;
}
console.log(allPairs([7, 2, 5, 8, 4, 3], 7));
Finally find duplicate pairs as well :-)
function allPairs(ints, s) {
var hash = Object.create(null),
i,
value,
pairs = [];
for (i = 0; i < ints.length; i++) {
value = ints[i];
if (hash[value]) {
pairs.push([s - value, value]);
hash[value]--;
continue;
}
if (!hash[s - value]) {
hash[s - value] = 0;
}
++hash[s - value];
}
return pairs;
}
console.log(allPairs([4, 3, 3, 4, 7, 2, 5, 8, 3], 7));
Steps
n_composition = sum - nlet n = 0;
let n_comp = 0;
let sum_pairs = (arr, sum) => {
for(let i = 0, len = arr.length; i < len; ++i){
n = arr[i];
n_comp = sum - n;
if (arr.includes(n_comp)){
return [n, n_comp];
}
}
return null;
}
console.log(sum_pairs([7,2,5,8,4,3],7))//[2,5]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With