Home > Software engineering >  Is it possible to transfer the solution of Dynameic programming from Python to Java?
Is it possible to transfer the solution of Dynameic programming from Python to Java?

Time:10-03

I found the Dynamic Programming solution to the Coin Change problem in Python.

def change(coins, amount):
    result = [amount 1] * (amount 1)
    coins_results = [[] for _ in range(amount 1)]

    result[0] = 0

    for i in range(1, amount 1):
        for coin in coins:
            if i >= coin and result[i - coin]   1 < result[i]:
                result[i] = result[i-coin]   1
                coins_results[i] = coins_results[i-coin]   [coin]
                

    if result[amount] == amount 1:
        return []

    return coins_results[amount]

However, when I try to transfer it to Java, I found some difficulties in this line.

coins_results[i] = coins_results[i-coin]   [coin]

In java, it does not allow to directly combine two arrays or add one element in the array. I have tried different ways but no luck. Could anyone give some help? Thank you

CodePudding user response:

First of all, welcome to StackOverflow. I recommend that you read this article on writing good questions here. Your title is too broad and will discourage people from clicking on your question. I would recommend something like "How do I combine two arrays in Java like you can combine them in Python" You can edit your own question to make improvements like this.

You are correct in saying that you cannot combine two arrays/ add one element in Java. This is because java arrays are static, and can only store the number of elements they are defined to have.

You can instead use something from the List interface as Gene said. I would recommend using an ArrayList. This article has a lot of good information and code examples for using them. Here are a couple of examples that will cover pretty much everything you would need for this problem.

// This creates a new ArrayList 
ArrayList<Integer> arrayList = new ArrayList<>();

// This adds elements to the ArrayList
arrayList.add(100);

// This gets elements from a list (similar to array[index])
arrayList.get(0);
arrayList.get(0) = 200;

// You can also add an entire list to the ArrayList
arrayList.addAll(someOtherList);

// Lastly, you can create nested ArrayLists by setting the type to another ArrayList
ArrayList<ArrayList<Integer>> nestedArrayList = new ArrayList<>();

CodePudding user response:

In Java, using ArrayList, which is essentially the same as Python List, the exact equivalent of the line you gave would be

coins_results[i] = new ArrayList<>(coins_results[i - coin]);
coins_results[i].add(coin);

I'm not claiming this is a great way to implement this DP, but for homework it should be fine.

You'll need to study the Java language harder. It's quite different from Python.

  • Related