I was working on a Dynamic Programming Problem and was able to code up a Javascript solution:
function howSum(targetSum,numbers,memo = {}){
//if the targetSum key already in hashmap,return its value
if(targetSum in memo) return memo[targetSum];
if(targetSum == 0) return [];
if(targetSum < 0) return null;
for(let num of numbers){
let aWay = howSum(targetSum-num,numbers,memo);
if(aWay !== null){
memo[targetSum] = [...aWay,num];
return memo[targetSum];
}
}
//no way to generate the targetSum using any elements of input array
memo[targetSum] = null;
return null;
}
Now I was thinking over how I could translate this into a CPP code.
I would have to use a reference to an unordered map for the memo object.
But how should I go about returning the empty array and null values as in the base condition?Should I return an array pointer and realloc it when inserting an element?Wouldnt that be a C way of programming it?
Also how should I go about passing the default parameter to the memo unordered map in C++?Currently I have overloaded the function which creates the memo unorderd map and passes its reference.
Any guidance will be appreciated as I can solve future questions.
std::optionalandstd::varianttemplates for these kinds of situations, in general. However C++ is not Javascript. Looking at this overall logic: in C++ the situation where this this returnsnullwould be likely handled by throwing an exception to indicate a fatal error. You cannot really translate Javascript into C++, or any language into any other language, for that matter, by attempting to do it one line at a time. This always ends in tears. The right way is to analyze what the existing code does, and reimplement its overall logic in the new language.NULLconstants are only valid for pointer types, and C++ functions cannot return arrays. C++ does not work this way. Therefore you will need to find some other replacement for these concepts, for your C++ code, and that's a decision that you will need to make yourself, since only you knows how the replacement code will be used.