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

Show parent comments

1

u/ibnahmadbello Dec 31 '21

Linkedlist? Would give it a try and see.

1

u/olara87 Dec 31 '21

Although it wouldn't be optimized because with a linkedlist you are traversing through the list every time.

1

u/ibnahmadbello Dec 31 '21

And it is the optimization that I am after. My approach actually works but it is not optimized compare to the tutorial version.

1

u/olara87 Dec 31 '21

Have you figure this out yet? I was looking at my old code and I guess I was able to figure out the issue then.

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.

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.

1

u/ibnahmadbello Dec 31 '21

Let me see if I can try this approach. Would get back to you if it work for me.

1

u/ibnahmadbello Dec 31 '21

I have mixed the hint up. Already I have a method that return n1 + "," + n2. The mix up is here:

memo[key] = gridTraveler(n1 - 1, n2, memo) + gridTraveler (n1, n2 - 1, memo)

How do I replicate the memo pass as argument to gridTraveler.

2

u/ibnahmadbello Dec 31 '21

I have gotten it. Your hint is so much appreciated.

→ More replies (0)