This is what my canSum
function needs to do:
Given a target sum x
, return true
iff it is possible to get that sum by adding elements from a given array, assuming array elements can be used any number of times.
Examples:
canSum(7, {2,3}) -> true
canSum(7, {2,4}) -> false
Below is the JavaScript code which I rewrote in C++. For some reason, even though I used memoization, the C++ version takes too long for big inputs.
The JavaScript code, which works fine:
const canSum = (targetSum, numbers, memo={}) => {
if (targetSum === 0) return true;
if (targetSum < 0) return false;
for ( let num of numbers) {
const remainder = targetSum - num;
if (canSum( remainder, numbers, memo) === true) {
return true;
}
}
return false;
};
console.log(canSum(7, [2, 3])); // true
console.log(canSum(7, [5, 3, 4, 7])); // true
console.log(canSum(7, [2, 41])); // false
console.log(canSum(8, [2, 3, 5])); // true
console.log(canSum(300, [7, 14])); // false
My C++ code, which never gave any output for the last input item canSum(300, {7,14})
#include<bits/stdc++.h>
using namespace std;
unordered_map<int,bool> mymap;
bool canSum(int goal, vector<int> vec)
{
if (goal<0) return false;
if (goal==0) return true;
if (mymap[goal]) return mymap[goal];
for(auto&ell:vec)
{
if(canSum(goal-ell,vec)==true)
{
mymap.insert({goal,true});
return true;
}
}
mymap.insert({goal,false});
return false;
}
int main()
{
cout<<canSum(7, {2,3})<<endl;
cout<<canSum(7, {5,3,4,7})<<endl;
cout<<canSum(7, {2,4})<<endl;
cout<<canSum(8, {2,3,5})<<endl;
cout<<canSum(300, {7,14})<<endl;
return 0;
}
How can I optimize the C++ code, and why is the JavaScript code faster ?