Reputation: 883
I am trying to write a function that add the first element of an array to the other element until it has a single value in javascript. If I pass only one element in the array, the programme works but if I pass more than one element, the function returns undefined. Any help would be appreciated.
function fold(input) {
if (input.length === 1) {
return input[0];
} else {
var newArray = add(input[0], input.slice(1, input.length));
if (newArray.length > 1) {
fold(newArray);
} else {
return newArray[0];
}
}
}
var arr = [1, 4, 7];
var sum = fold(arr);
console.log("the sum is " + sum); //should return 13
Upvotes: 1
Views: 111
Reputation: 2099
I add 2 ways more to solve this problem. The best method is way 3. The idea of this way, is "build floor" for remain element.
Consider array has n elements.
Step 0: Build floor for array[1], array[2], ... array[n] by add the value of array[0]
Step 1: Build floor for array[2], array[3], ... array[n] by add the value of array[1]
Step 2: Build floor for array[3], array[4], ... array[n] by add the value of array[2]
...
Step n-1: Build floor for array[n] by add the value of array[n-1]
And when finish this step, array[n] is the value you need last!
//way1 = your way
function add(additem,arr){
return arr.map(x => x + additem);
}
function fold(input){
if(input.length===1){
return input[0];
}
else {
var newArray=add(input[0],input.slice(1, input.length));
if(newArray.length > 1){
return fold(newArray); // return here
}
else{
return newArray[0];
}
}
}
//way2
function way2(array){
result = array;
for(var i=0;i<result.length-1;i++){
result = result.map(x=>x+result[i]);
}
return result[result.length-1];
}
//way3
function way3(array){
var result = array;
for(var i=0;i<result.length;i++)
for (var j=i+1;j<result.length;j++)
result[j] = result[i] + result[j];
return result[result.length-1];
}
var arr=[2,5,4,3,1,3,4,9];
var sum=fold(arr);
console.log("Initial arr = " + arr);
console.log("way1 = the sum is: " + sum);
console.log("way2 = the sum is: " + way2(arr));
console.log("way3 = the sum is: " + way3(arr));
Upvotes: 0
Reputation: 68933
If nothing is returned from a function then by default undefined
is returned. You have to return
the function:
Change
fold(newArray);
To return fold(newArray);
function add(additem,arr){
return arr.map(x => x + additem);
}
function fold(input){
if(input.length===1){
return input[0];
}
else {
var newArray=add(input[0],input.slice(1, input.length));
if(newArray.length > 1){
return fold(newArray); // return here
}
else{
return newArray[0];
}
}
}
var arr=[1,4,7];
var sum=fold(arr);
console.log("the sum is " + sum); //should return 13
Upvotes: 2