r/learnjava • u/ibnahmadbello • Dec 31 '21
Convert JavaScript function to Java
Hello, I am following a YouTube video on dynamic programming. So the guy solve a problem on number of route available in a given grid that requires you to go right or down. He did the solution in JavaScript, I am having problem to replicate it in Java. This is the JavaScript function:
const gridtravel = (m, n, memo = {} => {
const key = m + ',' + n;
if (key in memo) return memo[key];
if(m === 1 && n === 1) return 1;
if(m === 0 || n === 0) return 0;
memo[key] = gridtravel(m - 1, n, memo) + gridtravel(m, n - 1, memo);
return memo[key];
}
This is my trial in Java;
Map<String, Integer> memo = new Map<>();
String key = m + ',' + n;
if (memo.contains(key)) return memo.get(key);
if(m == 1 && n == 1) return 1;
if(m == 0 || n == 0) return 0;
memo.put(key, gridtravel(m - 1, n) + gridtravel(m, n - 1));
return memo.get(key);
}
I don't know how to replicate with the memo object use in JavaScript. The function is suppose to have two parameter of row and column. This approach is trying to get an optimized solution
1
Upvotes
1
u/ibnahmadbello Dec 31 '21
Not yet. I took a walk away hoping to get an idea/clue. Please I wouldn't mind a hint to how you figured it out. Thanks.