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
4
u/olara87 Dec 31 '21
Ah Melvin's Video. Awesome stuff. I did exactly what you did. Also got stump on this one. Now that I know a little bit more, if I were to continue with this project, I would try to see if I can use a linkelist instead. Good luck!