Related
I want to achieve the same result I can get with this code:
function fibs(n) {
let fibs = []
for (let i = 0; i <= n; i++) {
if ((i <= 1)) fibs.push(i)
else fibs.push(fibs[i - 1] + fibs[i - 2])
}
return fibs
}
console.log( fibs(8) )
with a recursive function.
Obviously, when you console.log(fibs(8) it renders a list like this: [0, 1, 1, 2, 3, 5, 8, 13, 21]
My recursive function looks like this:
function fibsRec(n) {
if (n < 2) return n
return fibsRec(n - 1) + fibsRec(n - 2)
}
console.log( fibsRec(8) )
and if you console.log(fibsRec(8)) it returns 21, which is the 8th Fibonacci number, but doesn't give me the list of all the Fibonacci numbers before it. How can I get the list without a loop, just from my recursive function?
How can I get the same outcome as fibs() with fibsRec()
where it goes wrong
Let's review. If fibsRec is meant to return an array, we can first notice that return n isn't going to work. n is just a number and we need an array.
function fibsRec(n) {
if (n < 2) return n // <- problem one
return fibsRec(n - 1) + fibsRec(n - 2) // <- problem two
}
Second, if fibsRec is going to be returning arrays, we cannot simply call + for fibsRec(n - 1) and fibsRec(n - 2). Watch what happens if we were to try -
const a = [1,2,3]
const b = [4,5,6]
console.log(a + b) // 1,2,34,5,6
Maybe you're thinking that's an odd result. Really JavaScript should throw an error for such misuse of +, but instead it tries its "best" to perform the addition. To do so, it coerces each array to a string first, then combines the strings together -
const a = [1,2,3]
const b = [4,5,6]
console.log(String(a)) // 1,2,3
console.log(String(b)) // 4,5,6
console.log(a + b) // 1,2,34,5,6
behaviour-oriented design
To understand how fibsRec needs to behave, let's first define some outputs for known inputs -
f(n)
output
f(0)
[]
f(1)
[0]
f(2)
[0,1]
f(3)
[0,1,1]
f(4)
[0,1,1,2]
f(5)
[0,1,1,2,3]
f(6)
[0,1,1,2,3,5]
...
...
To fix the first problem, easy mode, change return n to return a range 0..n instead -
function fibsRec(n) {
if (n < 2) return range(0,n) // <- fix one
return fibsRec(n - 1) + fibsRec(n - 2) // ...
}
const range = (a, b) =>
a >= b
? []
: [a, ...range(a + 1, b)]
you can't + arrays, but you can fibplus them...
To fix the second problem, we need a function that can "add" fibonacci sequences (arrays) because + just isn't going to cut it. We'll call our function fibplus -
function fibsRec(n) {
if (n < 2) return range(0,n)
return fibplus(fibsRec(n - 1), fibsRec(n - 2)) // <- fix two
}
We just have to define how fibplus will add the sequences to achieve the correct result. Let's work off an example. To compute fib(6) we need to "add" fib(5) and fib(4). We could just try stacking the two sequences and adding down to get the result -
0 1 1 2 3 == fib(4)
+ 0 1 1 2 3 5 == fib(5)
------------------------------------
0 1 2 3 5 8 ~~ fib(6)
It's very close to fib(6) but notice it's off by one. Watch what happens when we prepend a 1 to the smaller number before adding -
1 -> 1 0 1 1 2 3
+ 0 1 1 2 3 5
------------------------------------
1 1 2 3 5 8 ~~ fib(6)
Now if we prepend a 0 to the sum ...
1 0 1 1 2 3
+ 0 1 1 2 3 5
------------------------------------
0 -> 0 1 1 2 3 5 8 == fib(6)
We now have fib(6)! We just need to write fibplus to implement this adding technique -
const fibplus = (a, b) =>
[0, ...zip(add, a, [1, ...b])]
const zip = (f, a, b) =>
a.map((v, i) => f(v, b[i]))
const add = (a, b) => a + b
functioning demo
Run the snippet below to verify the result in your own browser -
const fib = n =>
n < 2
? range(0, n)
: fibplus(fib(n - 1), fib(n - 2))
const range = (a, b) =>
a >= b
? []
: [a, ...range(a + 1, b)]
const fibplus = (a, b) =>
[0, ...zip(add, a, [1, ...b])]
const zip = (f, a, b) =>
a.map((v, i) => f(v, b[i]))
const add = (a, b) => a + b
console.log(String(fib(20)))
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181
visualizing
So indeed we were able to make fibsRec work using fibplus, but by mirroring the original recursive process we inherited a lot of inefficiency as well. We can see the sheer amount of duplicated work -
#WillNess comments below and explains another way fibplus can be rewritten to save some work, but the real drawback of the approach above is the resulting exponential process. Let's see some other ways to get the result we are looking for.
other processes
I like the way you asked the question: "How can I get the same outcome?". Different procedures evolve different processes, and we are not required to create a recursive branching process. Instead a linear iterative process is more efficient and better suited for the desired output.
Note fibs returns an array, but I cast the output as a string for more digestible output -
const fibs = (n, a = 0, b = 1) =>
n <= 0
? []
: [a, ...fibs(n - 1, b, a + b)]
console.log(String(fibs(10)))
So how does it work? Recursion is a functional heritage and so using it with functional style yields the best results. This means avoiding things like mutation, variable reassignments, or other side effects. When a function is referentially transparent, its call can be replaced by its return value, without changing the meaning of our program.
fibs(6)
== fibs(6, 0, 1)
== [0, ...fibs(5, 1, 1)]
== [0, ...[1, ...fibs(4, 1, 2)]]
== [0, ...[1, ...[1, ...fibs(3, 2, 3)]]]
== [0, ...[1, ...[1, ...[2, ...fibs(2, 3, 5)]]]]
== [0, ...[1, ...[1, ...[2, ...[3, ...fibs(1, 5, 8)]]]]]
== [0, ...[1, ...[1, ...[2, ...[3, ...[5, ...fibs(0, 8, 13)]]]]]]
== [0, ...[1, ...[1, ...[2, ...[3, ...[5, ...[]]]]]]]
== [0, ...[1, ...[1, ...[2, ...[3, ...[5]]]]]]
== [0, ...[1, ...[1, ...[2, ...[3, 5]]]]]
== [0, ...[1, ...[1, ...[2, 3, 5]]]]
== [0, ...[1, ...[1, 2, 3, 5]]]
== [0, ...[1, 1, 2, 3, 5]]
== [0, 1, 1, 2, 3, 5]
wasteful intermediate arrays
You might notice that the many intermediate arrays is somewhat wasteful and the result could be accomplished with a single array. Let's make a push helper to do just that -
const push = (arr, val) =>
(arr.push(val), arr)
const fibs = (n, a = 0, b = 1, r = []) =>
n == 0
? r
: fibs(n - 1, b, a + b, push(r, a))
console.log(String(fibs(10)))
Let's see how this one works -
fibs(6)
== fibs(6, 0, 1, [])
== fibs(5, 1, 1, [0])
== fibs(4, 1, 2, [0,1])
== fibs(3, 2, 3, [0,1,1])
== fibs(2, 3, 5, [0,1,1,2])
== fibs(1, 5, 8, [0,1,1,2,3])
== fibs(0, 8, 11, [0,1,1,2,3,5])
== [0,1,1,2,3,5]
streams
Another fun way to calculate sequences of fibonacci numbers is to use streams. Streams deliver data over time as it is needed, instead of all at once. Because streams allow us to consume only as much as need, we can actually define fibs as an infinite stream. Notice it is no longer a function -
const fibs =
stream(0, _ =>
stream(1, _ =>
streamAdd(fibs, fibs.next)))
The building blocks of our streams are emptyStream and stream. To construct a non-empty stream, we give provide any value to stream and a thunk _ => ... where ... is computation of the next value, if any -
const emptyStream =
Symbol('emptyStream')
const stream = (value, next) => ({
value,
get next() { delete this.next; return this.next = next() }
})
Streams as defined here are not the same as JavaScript's built-in generators. The primary difference is they are persistent, meaning they can be replayed any number of times. JavaScript's generators have an internal "cursor" and once it advances, you can never rewind it. This is important for our fibs stream because you can see it consumes itself twice. If we used generators, advancing the generator for one operation would permanently advance it for all others.
Next we define generic stream operations. streamAdd combines two streams of numbers using addition -
const streamAdd = (s1, s2) =>
s1 === emptyStream || s2 === emptyStream
? emptyStream
: stream(s1.value + s2.value, _ => streamAdd(s1.next, s2.next))
And because fibs is infinite, we need some way to limit how much we bite off. streamTake will terminate an infinite stream after that limit is reached -
const streamTake = (s = emptyStream, n = 0) =>
s === emptyStream || n <= 0
? emptyStream
: stream(s.value, _ => streamTake(s.next, n - 1))
Finally, to fulfill the desired output, we convert the finite stream to an array -
function streamToArray(s = emptyStream) {
const r = []
while (s != emptyStream) {
r.push(s.value)
s = s.next
}
return r
}
Run the stream demo below to verify the result in your browser -
const emptyStream =
Symbol('emptyStream')
const stream = (value, next) => ({
value,
get next() { delete this.next; return this.next = next() }
})
const streamAdd = (s1, s2) =>
s1 === emptyStream || s2 === emptyStream
? emptyStream
: stream(s1.value + s2.value, _ => streamAdd(s1.next, s2.next))
const streamTake = (s = emptyStream, n = 0) =>
s === emptyStream || n <= 0
? emptyStream
: stream(s.value, _ => streamTake(s.next, n - 1))
function streamToArray(s = emptyStream) {
const r = []
while (s != emptyStream) {
r.push(s.value)
s = s.next
}
return r
}
const fibs =
stream(0, _ =>
stream(1, _ =>
streamAdd(fibs, fibs.next)))
console.log(String(streamToArray(streamTake(fibs, 20))))
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181
I would do this like this (it's also a little bit faster because of caching):
function fibsRec(n) {
const cache = {
1: 1,
0: 1
}
rec(n)
return Object.values(cache)
function rec(n) {
if (cache[n]) return cache[n]
cache[n - 1] ??= rec(n - 1)
cache[n - 2] ??= rec(n - 2)
return cache[n - 1] + cache[n - 2]
}
}
console.log(fibsRec(8))
Of course the easy answer would be to make a wrapper function that loops and calls fibsRec(i) each time, but that's not what you're looking for.
First, you need to think about what fibsRec is doing to see why this isn't naturally as simple as it sounds. As you already know it gets the nth fibonacci number by finding the (n-1)th and (n-2)th and to get those, it keeps going further back.
But that means that to get the n-1 and n-2 numbers, you need to generate the sequence to n-1 and n-2, not only that, but when you start generating that sequence for, let's say n-1, and you have to calculate it's previous indices, then you need two more sequences, and so on and so on. It's extremely inefficient.
But the reason I'm bringing this up, is to say that we can't just create an empty array and have it push the number we'd return before returning it, because we're making so many sequences, our array is gonna contain all those results.
Look at this:
function fibArray(n) {
const output = [];
function fibsRec(n) {
if (n < 2) {
output.push(n)
return n;
}
let num = fibsRec(n - 2) + fibsRec(n - 1)
output.push(num);
return num;
}
fibsRec(n);
return output
}
console.log( fibArray(8) )
See how many times we're calculating a number on the fibonacci sequence?
We definitely can't directly use this approach. But what we can use is dynamic programming. What we'll do is, memoize (save) each fibonacci number we calculate to a dictionary, and the next time we're looking for it, instead of recursing a new sequence, we'll just get it from the dictionary directly.
That way, we're getting each fibonacci number only once. So when we calculate it, we can push it to our output array, and it'll be a clean fibonacci sequence.
function fibArray(n) {
const output = [];
const fibs = {}; // Create memo (a dictionary)
function fibsRec(n) {
if (fibs[n]) return fibs[n]; // Check memo
if (n < 2) {
fibs[n] = n;
output.push(n)
return n;
}
let num = fibsRec(n - 2) + fibsRec(n - 1) // Start with n-2 to eventually call fibsRec(0) before fibsRec(1) and push them in that order
fibs[n] = num; // Memoize
output.push(num);
return num;
}
fibsRec(n);
return output
}
console.log( fibArray(8) )
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
}
I made this function to get all possible combinations of a set that sum to a target value, its works, but it is not as organize/efficient as possible yet.
After fry my brain trying to optimize this function i ran out of ideas and a litle bit blind, so i came here to get somes adivices and ideas for what more i can do.
const combinate = (set, target) => {
const result = []
set.forEach((element) => {
let division = Math.floor(target / element)
let remainder = target % element
while (remainder !== target) {
let combinations = []
for (let index = 0; index < division; index++) {
combinations.push(element)
}
if (remainder === 0) {
result.push(combinations.sort())
break
} else if (set.includes(remainder)) {
combinations.push(remainder)
result.push(combinations.sort())
break
} else {
division--
remainder += element
}
}
})
return result
}
Here I have some examples of expected outcomes for how this function it should work.
combinate([2, 3, 5], 8) -> [[2,2,2,2],[2,3,3],[3,5]]
I think your algorithm is fine.
I personally would structure the code differently, as I'm a fan of expression-only coding. My version might look like this:
// Ex: countDown (6) //=> [6, 5, 4, 3, 2, 1, 0]
const countDown = (n) =>
n < 0 ? [] : [n, ...countDown (n - 1)]
const subsetSum = ([n, ...ns], t) =>
n == undefined
? t == 0 ? [[]] : []
: countDown (Math.floor (t / n)) .flatMap (
(k) => subsetSum (ns, t - k * n) .map (ss => [...Array (k) .fill (n), ...ss])
)
console .log (subsetSum ([2, 3, 5], 8))
.as-console-wrapper {max-height: 100% !important; top: 0}
I count down rather than up just so the results come in the same order yours did. If I counted up, they would show up as [[3, 5], [2, 3, 3], [2, 2, 2, 2]].
But this is essentially the same algorithm as yours. If it's ill-performant, then I might look at a dynamic programming version where we calculate the results for each lower total, and then for our target total, we look up the values found by subtracting each of the number in our set, and for each of those results, we add one of that number. Here's one version:
const countUp = (n) =>
(n < 1) ? [] : [... countUp (n - 1), n]
const oneMore = (i) => (s) =>
s .split ('-') .map (Number) .map ((n, j) => j == i ? n + 1 : n) .join ('-')
const collect = (ns, t) =>
countUp (t) .reduce (
(rs, v) => [
...rs,
new Set (ns .flatMap ((n, i) => ([...rs [v - n] || []]) .map (oneMore (i))))
],
[new Set([ns .map (n => 0) .join ('-')])]
)
const subsetSum = (ns, t) =>
[...collect (ns, t) [t]]
.map (s => s.split ('-') .map(Number) .flatMap ((c, i) => Array (c) .fill (ns[i])))
console .log (subsetSum ([2, 3, 5], 8))
.as-console-wrapper {max-height: 100% !important; top: 0}
The main function here, collect accepts, say [2, 3, 5] and 8, and returns something like
[
new Set (['0-0-0']), // 0
new Set ([]), // 1
new Set (['1-0-0']), // 2
new Set (['0-1-0']), // 3
new Set (['2-0-0']), // 4
new Set (['1-1-0', '0-0-1']), // 5
new Set (['3-0-0', '0-2-0']), // 6
new Set (['2-1-0', '1-0-1']), // 7
new Set (['4-0-0', '1-2-0', '0-1-1']), // 8
]
where, say '1-1-0' represents one 2 and one 3 and zero 5s, which add up to 5, or '0-1-1' represents zero 2s and one 3 and one 5, which add up to 8. In retrospect, a better string format would probably have been the JSON-stringified version of something like {2: 1, 3: 1, 5: 0} But I'll leave that as an exercise.
The values are stored as Strings in Sets to eliminate duplicates as we go. For instance, when we hit 5, we can add a 2 to '0-1-0' or a 3 to '1-0-0', both of which end up as '1-1-0'. But we only want a single copy of that result.
We use two minor helper functions. countUp for instance, turns 7 into [1, 2, 3, 4, 5, 6, 7]. oneMore handles the string to Array of numbers back to string conversion such that
oneMore (0) ('1-7-4') //=> '2-7-4'
oneMore (1) ('1-7-4') //=> '1-8-4'
oneMore (2) ('1-7-4') //=> '1-7-5'
The main function simply extracts the last value computed by collect and then for each of the Strings in the set, converts that back into a proper array.
I have not tested for performance, but there's a real chance that this will be faster than the original algorithm. If nothing else, it demonstrates a substantially different technique.
There will be an array and a number.
I want to get all possible combinations from the array by number.
I mean if the array is [2,4,1,3,0,1] and the number is 5,
then the result will be [2,3] [4,1] [2,3,0] [4,1,0] [1,3,1,0].
So, I try this algorithm
function solution(arr, n) {
let result = []
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
let sum = arr[i] + arr[j]
if(sum === n) {
result.push([arr[i], arr[j]])
}
}
}
return result
}
But, this algorithm is only for two combinations.
I have been thinking how to do three combinations and four combinations during the last five hours.
What is the way to access it to solve that?
You can try something simple and naive:
const sumsTo = ([n, ...ns], t) =>
n === undefined ? [] : [ // if list is empty, no results
... (n === t ? [[n]] : []), // if n == t, include [n]
... sumsTo (ns, t - n) .map (s => [n, ...s]), // include n and recur
... sumsTo (ns, t) // skip n and recur
]
console .log (
sumsTo ([2, 4, 1, 3, 0, 1], 5)
/* display */ .map (JSON.stringify) .join ('\n')
)
.as-console-wrapper {max-height: 100% !important; top: 0}
Here we use a fairly simple recursion, always reducing the list of numbers to test and sometimes reducing the total we're seeking.
It will repeat arrays, for instance in this example, [4, 1]. If you want to remove duplicates, then we can just run a uniqueness function (such as const uniq = (xs) => [...new Set(xs)]) on the result.
The performance is likely to be terrible, but then it seems likely that no algorithm here will have great performance.
One elegant way to solve the problem is with a slightly modified k-combinatorial algorithm.
I don't know enough JavaScript to write it in your native language, but here is a Python implementation that I hope will suffice as well as pseudo-code:
def find_combination(input, value):
"""Find all combination in input which it's sum is equal to value and has minimum of two elements."""
for k in range(2, len(input) + 1):
result = gen_combination(input, k, value)
for x in result:
print(x)
def gen_combination(input, k, value):
"""Returns unique combinations of k-value from input which it's sum equal to value."""
output = []
_gen_combination_rec(input, output, k, value)
return output
def _gen_combination_rec(array, output, k, value, index=0, data=None):
"""Recursively traverse input to find combinations of k-value."""
if data == None:
data = [0] * k
if index == k:
sd = sorted(data)
if sd not in output and sum(data) == value:
output.append(sd)
data[index - 1] = 0
return
i = 0
n = len(array)
while i < n and index < k:
data[index] = array[i]
_gen_combination_rec(array[i + 1 :], output, k, value, index + 1, data)
i += 1
if __name__ == "__main__":
input = [2, 4, 1, 0, 3, 1]
find_combination(input, 5)
Here is the output of the above code when run from a terminal:
$ python main.py
[2, 3]
[1, 4]
[0, 2, 3]
[0, 1, 4]
[1, 1, 3]
[0, 1, 1, 3]
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));
}