Trying to solve using recursion without using other algorithms - javascript

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));
}

Related

Create a list of results of all recursive calls performed by a function call

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) )

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
}

improve function that all unique combinations between set values ​result in the sum of the target number

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.

What is the time complexity of Javascript Array.reduce() and Array.find()?

I am trying to return an array of indexes of values that add up to a given target. I am trying to solve it the fastest way I can!
Examples:
sumOfTwo([1, 2, 4, 4], 8) // => [2, 3]
sumOfTwo([1, 2, 3, 9], 8) // => []
So first I tried a simple brute-force. (Time complexity: O(n^2) )
function sumOfTwo(arr, target) {
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] + arr[j] === target) {
return [i, j];
}
}
}
return [];
}
Then I tried: (Time complexity: sorting O(n log n) + for loop O(n))
function sumOfTwo(arr, target) {
const sortedArr = arr.sort();
let idxFromBack = arr.length - 1;
for (let [idx, val] of sortedArr.entries()) {
if (val + arr[idxFromBack] > target) {
idxFromBack--;
}
if (val + arr[idxFromBack] === target) {
return [idx, idxFromBack];
}
}
return [];
}
Then I came with this solution that I don't even know the time complexity.
function sumOfTwo(arr, target) {
const complements = [];
for (let [idx, val] of arr.entries()) {
if (complements.reduce((acc, v) => (acc || v.value === val), false)) {
return [complements.find(v => v.value === target - val).index, idx];
}
complements.push({index: idx, value: target - val});
}
return [];
}
I know that I am using a for-loop but I don't know the complexity of the build-in high order functions .reduce() and .find(). I tried a couple of searches but I couldn't find anything.
If anyone can help me would be great! Please include Big-O notation if possible.
Repl.it: https://repl.it/#abranhe/sumOfTwo
Please also include the time complexity of the last solution.
The minimum time complexity of .reduce is O(n), because it must iterate through all elements once (assuming an error isn't thrown), but it can be unbounded (since you can write any code you want inside the callback).
For your
// Loop, O(n), n = length of arr:
for (let [idx, val] of arr.entries()) {
// .reduce, O(n), n = length of complements:
if (complements.reduce((acc, v) => (acc || v.value === val), false)) {
// If test succeeds, .find, O(n), n = length of complements:
return [complements.find(v => v.value === target - val).index, idx];
}
complements.push({index: idx, value: target - val});
}
the time complexity is, worst case, O(n^2). The reduce runs in O(n) time, and you run a reduce for every entry in arr, making it O(n^2).
(The .find is also an O(n) operation, but O(n) + O(n) = O(n))
Your code that sorts the array beforehand has the right idea for decreasing complexity, but it has a couple flaws.
First, you should sort numerically ((a, b) => a - b)); .sort() with no arguments will sort lexiographically (eg, [1, 11, 2] is not desirable).
Second, just decrementing idxFromBack isn't enough: for example, sumOfTwo([1, 3, 8, 9, 9], 9) will not see that 1 and 8 are a match. Perhaps the best strategy here would be to oscillate with while instead: from a idxFromBack, iterate backwards until a match is found or the sum is too small, and also iterate forwards until a match is found or the sum is too large.
You can also improve the performance of this code by sorting not with .sort((a, b) => a - b), which has complexity of O(n log n), but with radix sort or counting sort instead (both of which have complexity of O(n + k), where k is a constant). The optimal algorithm will depend on the general shape and variance of the input.
An even better, altogether different O(n) strategy would be to use a Map or object. When iterating over the array, put the value which would result in a match for the current item into a key of the object (where the value is the current index), and just look to see if the current value being iterated over exists in the object initially:
const sumOfTwo = (arr, target) => {
const obj = {};
for (const [i, num] of arr.entries()) {
if (obj.hasOwnProperty(String(num))) {
return [obj[num], i];
}
const matchForThis = target - num;
obj[matchForThis] = i;
}
return [];
};
console.log(
sumOfTwo([1, 2, 4, 4], 8), // => [2, 3]
sumOfTwo([1, 2, 8, 9], 9), // 1 + 8 = 9; [0, 2]
sumOfTwo([1, 2, 3, 9], 8) // => []
);
As a supplementary answer, here is the algorithm of the find method in the language spec:
When the find method is called, the following steps are taken:
Let O be ? ToObject(this value).
Let len be ? LengthOfArrayLike(O).
If IsCallable(predicate) is false, throw a TypeError exception.
Let k be 0.
Repeat, while k < len,
a. Let Pk be ! ToString(𝔽(k)).
b. Let kValue be ? Get(O, Pk).
c. Let testResult be ! ToBoolean(? Call(predicate, thisArg, « kValue, 𝔽(k), O »)).
d. If testResult is true, return kValue.
e. Set k to k + 1.
Return undefined.
Note the "repeat, while k < len" in step 5. Since time complexity in general measures the worst case scenario (aka the upper bound), we can assume that the searched element is not present in the collection.
The number of iterations made during step 5 then is equal to len which directly depends on the number of elements in the collection. And what time complexity has a direct correlation to the number of elements? Exactly, the linear O(n).
For a visual-ish demonstration, run the following snippet. Apart from some stray dots, the improvized graph should show a linear progression (takes a little while to display in Stack snippets, but you can watch it live in the devtools console):
const iter = 1e7;
const incr = 2e5;
const test = new Array(iter).fill(0);
const steps = Math.ceil(iter / incr);
for (let i = 0; i < steps; i += 1) {
const sub = test.slice(0, i * incr + incr);
const s = Date.now();
const find = sub.find((v) => v === 1);
const e = Date.now();
const d = e - s;
console.log("\u200A".repeat(Math.floor(d/3))+"*");
}

Recursive function issue in JS

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
)

Categories