My code is: -
function pairwise(arr, arg) {
var retArr=[];
if(arr.length===0){
return 0;
}
var reduction=arr.reduce(function(previous,current,index){
for(var i=index;i<arr.length;i++){
console.log("before "+retArr);
console.log(retArr.indexOf(i)===-1);
if(previous+arr[i]===arg&&retArr.indexOf(i)===-1){
retArr.push(index-1,i);
console.log("after "+retArr);
console.log(retArr.indexOf(i)===-1);
return current;
}
}
return current;
});
console.log("Greg "+retArr);
retArr=retArr.reduce(function(prev,lst){return prev+lst;});
return retArr;
}
pairwise([1, 1, 1], 2);
This is a JS program to detect pairs of numbers in an array which add up to the second argument. It then returns the sum of the indexes of the pairs. Once an index has been used once it cannot be reused. For the given call I need a return of 1 but am currently getting 4. The console.log outputs as: -
before
true
after 0,1
false
before 0,1
true
after 0,1,1,2
false
Greg 0,1,1,2
I cant get my head around why the third Boolean returns as true. Surely it should return false as 1 is already in the retArr array. Can anyone tell me why this is not the case? Is it due to the scope of the retArr variable or something to do with the way reduce works? I am totally out of ideas.
Any help with this gratefully received.
Aucun commentaire:
Enregistrer un commentaire