r/learnjava • • 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

16 comments sorted by

View all comments

1

u/Housy5 Jan 02 '22 edited Jan 02 '22

Idk about converting javascript to java but the classes inside the javax.script package will allow you to run javascript inside of java