Recursive function issue in JS - javascript

So I need to solve this problem STRICTLY using recursion
// 2. Compute the sum of an array of integers.
// sum([1,2,3,4,5,6]); // 21
And then I'm testing this solution in PythonLive
var sum = function(array) {
if(array.length===0){
return array
}
return array.slice(0,array.length)+sum(array.pop())
};
sum([1,2,3,4,5,6]);
Then at step 6 it says "TypeError: array.slice is not a function"
I don't understand why if it already worked taking 6 off the array and returning the remaining array...
Can someone explain me what am I doing wrong please?
thanks! :)

If you look at the return values you will see that you are always returning an array. This can't be right when you want a number as a final result. When array.length === 0 you can safely return 0 because that's the same of an empty array. That's your edge condition. After that you just want the sum of one element plus the rest.
You can also just return the array length when it's zero making for a very succinct solution. && shortcircuits returning the left element if it's false (like 0) otherwise the second:
var sum = (array) => array.length && array.pop() + sum(array)
console.log(sum([1,2,3,4,5,6]));
If you prefer slice you could also this, which is basically the same:
var sum = (array) => array.length && array[0] + sum(array.slice(1))
console.log(sum([1, 2, 3, 4, 5, 6]));

Recursive sum function:
const sum = list => {
if (!list.length) return 0;
return list.pop() + sum(list);
};
Because .pop mutates the array, you don't need to use slice. For a non-destructive version (doesn't alter the original array):
const sum = ([first, ...rest]) => {
if (first === undefined) return 0;
return first + sum(rest);
};

The issue with your code is that you are processing the values the wrong way around, it should be
return sum(array.slice(0,array.length-1)) + array.pop();
In fact since array.pop() removes the element, you can just do it this way around:
return array.pop() + sum(array);
You also need to return 0 when array.length===0, otherwise the sum will fail.
if (array.length===0) return 0;
However it's much simpler just do this with reduce:
let arr = [1,2,3,4,5,6];
console.log(arr.reduce((t, v) => { return t + v; }, 0));

Another encoding using an explicit empty and pure expressions
const empty = x =>
x === empty
const sum = ([ x = empty, ...rest ]) =>
empty (x)
? 0
: x + sum (rest)
console.log
( sum ([ 1, 2, 3, 4, 5 ]) // 15
, sum ([]) // 0
)
Your other question that asks how to sum a nested array was put on-hold for reasons I don't understand. You can adapt the above implementation to support input of nested arrays
const empty = x =>
x === empty
const sum = ([ x = empty, ...rest ]) =>
empty (x)
? 0
: Array.isArray (x)
? sum (x) + sum (rest)
: x + sum (rest)
console.log
( sum ([ 1, [ 2, [ 3, 4 ], 5 ]]) // 15
, sum ([ 1, 2, 3, 4, 5 ]) // 15
, sum ([[[]]]) // 0
, sum ([]) // 0
)

Related

Ways to get sum of two lowest positive integers (JS debugging failure)

I was doing this Codewar challenge of getting sum of two smallest integer.
so I was trying to solve with this:
function sumTwoSmallestNumbers(numbers) {
const m = numbers.sort( (a, b) => a - b )[2];
const a = numbers.filter(v => v < numbers.sort( (a, b) => a - b )[2]);
const b = a.reduce( (acc, n) => acc + n);
return b
};
It works, and later on I feel that const m is redundant, so I commented the whole const m line and then it doesn't work now, by "doesn't work" I mean it's giving incorrect outcome, not typeErrors.
My question is, how is that possible??
I mean on const a I literally rewrote what const m was referring to.
How is deleting something that is repeated affects the outcome?
Thanks in advance, I appreciate your time.
Simply, it is because the function Array.prototype.sort in javascript modifies the actual contents of the same instance of the array as well as returns the reference to the same array, In other words, it does not return a new array with the modified contents, it modifies the same array. That's why it doesn't work when you remove the line :
const m = numbers.sort( (a, b) => a - b )[2];
But, why doesn't it work when you tried to put the same logic with the next line of code?
const a = numbers.filter(v => v < numbers.sort( (a, b) => a - b )[2]);
The issue happens when the smallest value of the array is at an index larger than 2, for example:
[ 15, 28, 4, 2, 43 ]
when we try to execute the code on this array, lets take it a step by step to catch where it gets wrong.
function sumTwoSmallestNumbers(numbers) {
const a = numbers.filter(v => v < numbers.sort( (a, b) => a - b )[2]);
const b = a.reduce( (acc, n) => acc + n);
return b
};
const arr = [ 15, 28, 4, 2, 43 ]
const result = sumTwoSmallestNumbers(arr)
console.log(result)
When executing the previous code, the first thing the function will do is the filtering.
It will iterate through the elements of the array:
Starting from index 0 => arr[0] = 15
Testing the condition: 15 < numbers.sort( (a, b) => a - b )[2] => (15 < 15) => false
Notice! as I explained earlier, that the function sort will change the actual array rather than generating a new one, that means that when attempting to test the condition the first time, the array will be sorted, which means that if it is not already sorted, the order of its elements will defiantly change, which is a bad thing considering that the change happened during an ongoing loop through the arrays elements.
Before continuing the iteration of filter, let's make it clear that the new order of the array after the sorting has been executed when attempting to check the condition is as follows:
[ 2, 4, 15, 28, 43 ]
Index 1 => arr[1] = 4
Testing the condition: 4 < numbers.sort( (a, b) => a - b )[2] => (4 < 15) => true
Index 2 => arr[2] = 15
Testing the condition: 15 < numbers.sort( (a, b) => a - b )[2] => (15 < 15) => false
... The rest of the elements
Conclusion
As you can notice, the value 15 has been checked twice, and the value 2, has not been checked at all, which is because of the sudden change in the order of the array during the currently ongoing iteration of the filter method. Which has lead to placing the value of 2 in an already checked location, and the value of 15 into a location that has not been checked yet.
! Notice This is not an optimal solution to such a problem, it does too much work to get to the solution, (filtering, sorting, reducing), which are expensive operations to execute.
A better solution will be something like this, which involves a single loop through the elements of the array O(n):
function sumTwoSmallestNumbers(numbers) {
let lowest = Math.min(numbers[0], numbers[1]),
secondLowest = Math.max(numbers[0], numbers[1])
for(let i = 2; i < numbers.length; i++){
if(numbers[i] < lowest){
secondLowest = lowest
lowest = numbers[i]
}else if(numbers[i] < secondLowest)
secondLowest = numbers[i]
else continue
}
return lowest + secondLowest
}

Javascript. Reduce an array by adding only odd numbers. Javascript returns NaN when I use %2 on a number with if [duplicate]

This question already has answers here:
How to use array reduce with condition in JavaScript?
(9 answers)
Closed 1 year ago.
I am trying to sum all odd numbers of an array.
The following method does not work and returns NaN. Could someone explain me why?
I found a workaround so I do not need an alternative code. It would be great if you could explain me why (a supposed number)%2 is NaN. Thanks a lot.
(I have just started learning Javascript. So sorry if this is ... )
let arr=[1,2,3,4,5,6,7]
let result = arr.reduce((accumulator, currentValue) => {
if (currentValue%2 >0){
return accumulator + currentValue}})
console.log(result)
You are not returning the accumulator if the it's an odd number, so the last result is undefined + 7 which is NaN.
Always return the current accumulator for even numbers, or the accumulator + the number if it's an odd number.
const arr=[1,2,3,4,5,6,7]
const result = arr.reduce((accumulator, currentValue) =>
currentValue % 2 > 0 ? accumulator + currentValue : accumulator
)
console.log(result)
You return undefined for all even values (this is standard for all functions without a return statement) and undefined can not be used to add a number.
For preventing this, you need to return the accumulator.
let arr = [1, 2, 3, 4, 5, 6, 7],
result = arr.reduce((accumulator, currentValue) => {
if (currentValue % 2 > 0) {
return accumulator + currentValue;
} // or use else here
return accumulator;
});
console.log(result);
You just need to add an else clause inside the reduce method.
Because for even numbers you don't return anything which means the function returns undefined and now when the code encounters an odd number it does undefined + something which is NaN.
let arr = [1, 2, 3, 4, 5, 6, 7];
let result = arr.reduce((accumulator, currentValue) => {
if (currentValue % 2 > 0) {
return accumulator + currentValue;
} else {
return accumulator
}
});
console.log(result);

Trying to solve using recursion without using other algorithms

I am trying to get better at understanding recursion so that I can get better at implementing dynamic programming principles. I am aware this problem can be solved using Kadane's algorithm; however, I would like to solve it using recursion.
Problem statement:
Given an array of integers, find the subset of non-adjacent elements with the maximum sum. Calculate the sum of that subset.
I have written the following partial solution:
const maxSubsetSum = (arr) => {
let max = -Infinity
const helper = (arr, len) => {
if (len < 0) return max
let pointer = len
let sum = 0
while (pointer >= 0) {
sum += arr[pointer]
pointer -= 2
}
return max = Math.max(sum, helper(arr, len - 1))
}
return helper(arr, arr.length - 1)
}
If I had this data:
console.log(maxSubsetSum([3, 5, -7, 8, 10])) //15
//Our subsets are [3,-7,10], [3,8], [3,10], [5,8], [5,10] and [-7,10].
My algorithm calculates 13. I know it's because when I start my algorithm my (n - 2) values are calculated, but I am not accounting for other subsets that are (n-3) or more that still validate the problem statement's condition. I can't figure out the logic to account for the other values, please guide me on how I can accomplish that.
The code is combining recursion (the call to helper inside helper) with iteration (the while loop inside helper). You should only be using recursion.
For each element of the array, there are two choices:
Skip the current element. In this case, the sum is not changed, and the next element can be used. So the recursive call is
sum1 = helper(arr, len - 1, sum)
Use the current element. In this case, the current element is added to the sum, and the next element must be skipped. So the recursive call is
sum2 = helper(arr, len - 2, sum + arr[len])
So the code looks like something this:
const maxSubsetSum = (arr) => {
const helper = (arr, len, sum) => {
if (len < 0) return sum
let sum1 = helper(arr, len - 1, sum)
let sum2 = helper(arr, len - 2, sum + arr[len])
return Math.max(sum1, sum2)
}
return helper(arr, arr.length - 1, 0)
}
Your thinking is right in that you need to recurse from (n-2) once you start with a current index. But you don't seem to understand that you don't need to run through your array to get sum and then recurse.
So the right way is to
either include the current item and recurse on the remaining n-2 items or
not include the current item and recurse on the remaining n-1 items
Lets look at those two choices:
Choice 1:
You chose to include the item at the current index. Then you recurse on the remaining n-2 items. So your maximum could be item itself without adding to any of remaining n-2 items or add to some items from n-2 items.
So Math.max( arr[idx], arr[idx] + recurse(idx-2)) is the maximum for this choice. If recurse(idx-2) gives you -Infinity, you just consider the item at the current index.
Choice 2:
You didn't choose to include the item at the current index. So just recurse on the remaining n-1 items - recurse(n-1)
The final maximum is maximum from those two choices.
Code is :
const maxSubsetSum = (arr) => {
let min = -Infinity
const helper = (arr, idx) => {
if ( idx < 0 ) return min
let inc = helper(arr, idx-2)
let notInc = helper(arr, idx-1)
inc = inc == min ? arr[idx] : Math.max(arr[idx], arr[idx] + inc)
return Math.max( inc, notInc )
}
return helper(arr, arr.length - 1)
}
console.log(maxSubsetSum([-3, -5, -7, -8, 10]))
console.log(maxSubsetSum([-3, -5, -7, -8, -10]))
console.log(maxSubsetSum([-3, 5, 7, -8, 10]))
console.log(maxSubsetSum([3, 5, 7, 8, 10]))
Output :
10
-3
17
20
For the case where all items are negative:
In this case you can say that there are no items to combine together to get a maximum sum. If that is the requirement the result should be zero. In that case just return 0 by having 0 as the default result. Code in that case is :
const maxSubsetSum = (arr) => {
const helper = (arr, idx) => {
if ( idx < 0 ) return 0
let inc = arr[idx] + helper(arr, idx-2)
let notInc = helper(arr, idx-1)
return Math.max( inc, notInc )
}
return helper(arr, arr.length - 1)
}
With memoization:
You could memoize this solution for the indices you visited during recursion. There is only one state i.e. the index so your memo is one dimensional. Code with memo is :
const maxSubsetSum = (arr) => {
let min = -Infinity
let memo = new Array(arr.length).fill(min)
const helper = (arr, idx) => {
if ( idx < 0 ) return min
if ( memo[idx] !== min) return memo[idx]
let inc = helper(arr, idx-2)
let notInc = helper(arr, idx-1)
inc = inc == min ? arr[idx] : Math.max(arr[idx], arr[idx] + inc)
memo[idx] = Math.max( inc, notInc )
return memo[idx]
}
return helper(arr, arr.length - 1)
}
A basic version is simple enough with the obvious recursion. We either include the current value in our sum or we don't. If we do, we need to skip the next value, and then recur on the remaining values. If we don't then we need to recur on all the values after the current one. We choose the larger of these two results. That translates almost directly to code:
const maxSubsetSum = ([n, ...ns]) =>
n == undefined // empty array
? 0
: Math .max (n + maxSubsetSum (ns .slice (1)), maxSubsetSum (ns))
Update
That was missing a case, where our highest sum is just the number itself. That's fixed here (and in the snippets below)
const maxSubsetSum = ([n, ...ns]) =>
n == undefined // empty array
? 0
: Math .max (n, n + maxSubsetSum (ns .slice (1)), maxSubsetSum (ns))
console.log (maxSubsetSum ([3, 5, -7, 8, 10])) //15
But, as you note in your comments, we really might want to memoize this for performance reasons. There are several ways we could choose to do this. One option would be to turn the array we're testing in one invocation of our function into something we can use as a key in an Object or a Map. It might look like this:
const maxSubsetSum = (ns) => {
const memo = {}
const mss = ([n, ...ns]) => {
const key = `${n},${ns.join(',')}`
return n == undefined
? 0
: key in memo
? memo [key]
: memo [key] = Math .max (n, n + maxSubsetSum (ns .slice (1)), maxSubsetSum (ns))
}
return mss(ns)
}
console.log (maxSubsetSum ([3, 5, -7, 8, 10])) //15
We could also do this with a helper function that acted on the index and memoized using the index for a key. It would be about the same level of complexity.
This is a bit ugly, however, and perhaps we can do better.
There's one issue with this sort of memoization: it only lasts for the current run. It I'm going to memoize a function, I would rather it holds that cache for any calls for the same data. That means memoization in the definition of the function. I usually do this with a reusable external memoize helper, something like this:
const memoize = (keyGen) => (fn) => {
const cache = {}
return (...args) => {
const key = keyGen (...args)
return cache[key] || (cache[key] = fn (...args))
}
}
const maxSubsetSum = memoize (ns => ns .join (',')) (([n, ...ns]) =>
n == undefined
? 0
: Math .max (n, n + maxSubsetSum (ns .slice (1)), maxSubsetSum (ns)))
console.log (maxSubsetSum ([3, 5, -7, 8, 10])) //15
memoize takes a function that uses your arguments to generate a String key, and returns a function that accepts your function and returns a memoized version of it. It runs by calling the key generation on your input, checks whether that key is in the cache. If it is, we simply return it. If not, we call your function, store the result under that key and return it.
For this version, the key generated is simply the string created by joining the array values with ','. There are probably other equally-good options.
Note that we cannot do
const recursiveFunction = (...args) => /* some recursive body */
const memomizedFunction = memoize (someKeyGen) (recursiveFunction)
because the recursive calls in memoizedFunction would then be to the non-memoized recursiveFunction. Instead, we always have to use it like this:
const memomizedFunction = memoize (someKeyGen) ((...args) => /* some recursive body */)
But that's a small price to pay for the convenience of being able to simply wrap up the function definition with a key-generator to memoize a function.
This code was accepted:
function maxSubsetSum(A) {
return A.reduce((_, x, i) =>
A[i] = Math.max(A[i], A[i-1] | 0, A[i] + (A[i-2] | 0)));
}
But trying to recurse that far, (I tried submitting Scott Sauyet's last memoised example), I believe results in run-time errors since we potentially pass the recursion limit.
For fun, here's bottom-up that gets filled top-down :)
function f(A, i=0){
if (i > A.length - 3)
return A[i] = Math.max(A[i] | 0, A[i+1] | 0);
// Fill the table
f(A, i + 1);
return A[i] = Math.max(A[i], A[i] + A[i+2], A[i+1]);
}
var As = [
[3, 7, 4, 6, 5], // 13
[2, 1, 5, 8, 4], // 11
[3, 5, -7, 8, 10] // 15
];
for (let A of As){
console.log('' + A);
console.log(f(A));
}

The syntax of concat in javascript

let items = ['Tom','Bill','Kim'];
let result = items.reduce((str, item) => str + '<'.concat(item).concat('>'),"");
console.log(result);
May I ask what the ending "" does to the code?
It's not related to concat, it's related to reduce. It's the second argument to reduce, which sets the initial value of the accumulator. E.g., it "seeds" the accumulation, so it's often called the "seed value" or just "seed."
Without that argument, the first call to the callback would get the entries at indexes 0 and 1 as its first two arguments. With that argument, the first callback receives "" as its first argument and the entry at index 0 as its second argument.
Side note:
It's probably worth noting that that use of concat probably isn't the best way to do what that callback is trying to do. The author of that code is mixing string concatenation via + with concat, which is a bit odd. I'd use one or the other, or a template literal:
Using +:
let items = ['Tom','Bill','Kim'];
let result = items.reduce((str, item) => str + '<' + item + '>', "");
console.log(result);
Using concat:
let items = ['Tom','Bill','Kim'];
let result = items.reduce((str, item) => str.concat('<', item, '>'), "");
console.log(result);
Using a template literal:
let items = ['Tom','Bill','Kim'];
let result = items.reduce((str, item) => `${str}<${item}>`, "");
console.log(result);
It's the second argument to reduce as the initial value for accumulator.
Understand this way - With a single example
// Add all numbers in arr
const numbers = [1, 2, 3, 4]
let sum = 0 // this is the initial value
for (let n of numbers)
sum += n
console.log(sum)
// Again add all numbers in arr using reduce
const numbers = [1, 2, 3, 4]
let sum = 0
sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue
}, sum)
/**
* First round - accu = 0, currVal = 1 => accu = 1
* Second round - accu = 1, currVal = 2 => accu = 3
* Third round - accu = 3, currVal = 3 => accu = 6
* Fourth round - accu = 6, currVal = 4 => accu = 10
* Returns accu = 10
*/
console.log(sum)
// Reduce takes a callback
// Accumulator will get the initial value using sum
// currentValue is the each iteration value
Internally reduce returns accumulator + currentValue and save it to accumulator each iterate.

Using Math.max and Math.min to remove highest and lowest number from array

Need to remove the highest and lowest numbers from the array and sum the remaining numbers together. (duplicate values can stay e.g. [2, 2, 3, 5, 8] just removes the 2 once.)
Created 2 separate min and max values and then subtracted them from total of array.
Also should return 0 when array is empty?
Passes a few tests but cannot see why it does not pass all of the criteria specified above?
function sumArray(array)
{
var sum = 0;
var min = Math.min(...array); // lowest in array by spreading
var max = Math.max(...array); // highest in array by spreading
if(array === null)
{
return 0;
}
for (var i = 0; i < array.length; i++ )
{
(sum += array[i]);
}
return ((sum - max) - min);
}
Well, for one thing, if you need this check:
if(array === null){
return 0;}
...you need it before the code above it using array.
Also, you shouldn't include the min and max values in the sum in the first place. You can't just subtract them — after all, a value may appear more than once in the array. (Your code will have the wrong result for [2, 2, 3, 4, 5], for instance, because it counts 2 twice but only subtracts it once.) So instead of subtracting them after the fact, just don't add them in the loop in the first place.
Reduce would be a simpler way to sum your array up
function sumArray(array) {
// Nothing to do so we retrun zero
if(!Array.isArray(array) || array.length == 0) return 0;
var min = Math.min(...array); // lowest in array by spreading
var max = Math.max(...array); // highest in array by spreading
// Sum up the numbers in the array
var sum = array.reduce((acc, val) => acc + val, 0);
// Do the math
return sum - max - min;
}
console.log(sumArray([2, 2, 3, 5, 8]))
console.log(sumArray())
console.log(sumArray([]))
console.log(sumArray([0]))
console.log(sumArray([null, 0, 12]))
console.log(sumArray([null]))
I suppose, I am not supposed to show this ?
(because there are so many here who can do this same answer)
function sumArray(array)
{
if (array === null) return 0
let sum = array.reduce((a,c)=>a+c) // sum array values
, min = Math.min(...array) // lowest in array by spreading
, max = Math.max(...array) // highest in array by spreading
console.log({sum,min,max})
return (sum - max - min)
}
console.log('sumArray',sumArray([2, 2, 3, 4, 5]))
I would guess that your code does not meet the criteria if the array has a length of 1. Only one value can be removed then and the sum of the remaining ones is 0, but you are in fact subtracting it twice.
Also in the case of the empty array, max() and min() will return -Infinity and Infinity respectively, which do sum to NaN not to 0. Your === null check doesn't test for an empty array ([], with a .length of 0), but for a non-existing array.
So to deal with those issues, I would write
function sumArray(array) {
if (array.length <= 2) return 0;
const min = Math.min(...array);
const max = Math.max(...array);
const sum = array.reduce((a,b) => a+b, 0);
return sum - max - min;
}
If your function is supposed to also work with non-array values such as null and return 0 for them, add a second check:
if (!Array.isArray(array) || array.length <= 2) return 0;
You can sort the array and remove the first and last value instead of identifying max and min values individually.
You can also wrap null in an array to avoid creating special cases for in the execution flow:
const sumArray = arr =>
(arr || Array.of(arr))
.sort((a, b) => a - b)
.slice(1, (arr && (arr.length - 1)))
.reduce((sum, n) => sum + n, 0)
console.log(sumArray([2, 2, 3, 5, 8]))
console.log(sumArray(null))
console.log(sumArray([]))

Categories