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/olara87 Dec 31 '21
if I remember correctly, the issue was to pass down two digits and since you cannot do that with a hashmap i ended up using a second method that combines both digits into one. For example, if you need to pass down (1,3) I would call the second method I made and pass down the value n1 + "," + n2.