I want to memoize the return result of my function that take two int. i know i could convert the vector as a string like 1-2
but is there another way to do it ?
I tried to set an array as a map but there is no comparison between array
let map = new Map();
function gridTraveler(m, n){
if (m === 0 || n === 0)
return 0;
if (m === 1 && n === 1)
return 1;
if (map.has([m,n]))
return map.get([m, n]);
let res = gridTraveler(m-1, n) + gridTraveler(m, n-1);
map.set([m, n], res);
return res;
}
2
Answers
Updated:
Guessing this is what you want:
Origin:
If you want to use array value as the key, you must keep the reference.
To memoize the function
gridTraveler
without converting keys to strings, you can serialize the parameters as a unique object key.In JavaScript, objects or arrays used as keys in Maps are compared by their reference, not by their content MDN Documentation. Therefore, you need a method to generate a consistent, unique object reference for each pair of parameters.
Here’s an approach keeping integers only:
Use a nested map: The outer map keys are
m
, and eachm
maps to another map where the keys aren
.Check and set values in this two-level map structure.
Here’s how you can implement it:
In this version,
map
is a map where each key is anm
value, and each value is another map (let’s call itmMap
). ThemMap
has keys ofn
and stores the results. This avoids the need for string conversion and keeps the benefits of memoization.