A friend is doing an online Scala course and shared this.
# Write a recursive function that counts how many different ways you can make
# change for an amount, given a list of coin denominations. For example, there
# are 3 ways to give change for 4 if you have coins with denomiation 1 and 2:
# 1+1+1+1, 1+1+2, 2+2.
If you are attending and still working on a solution, don’t read this!
(disclaimer: even if my Python solution may be wrong, I don’t want to influence your thinking if you are on the course, one way or the other! I guess it is the thinking that goes into it that yields learning, not just the “solving”…)
That aside…
I thought I’d have a go at it in Python as I don’t have the Scala chops for it (I am not on the course myself, just interested in learning Python and Java and welcome “drills” to practice on).
Here’s my solution, which I’d like to port to Java using as compact a notation as possible:
def show_change(money, coins, total, combo):
if total == money:
print combo, '=', money
return 1
if total > money or len(coins) == 0:
return 0
c = coins[0]
return (show_change(money, coins, total + c, combo + [c]) +
show_change(money, coins[1:], total, combo))
def make_change(money, coins):
if money == 0 or len(coins) == 0:
return 0
return show_change(money, list(set(coins)), 0, [])
def main():
print make_change(4, [2, 1])
if __name__ == '__main__':
main()
Question
- How compact can I make the above in Java, allowing the use of libraries external to the JDK if they help?
I tried doing the porting myself but it was getting very verbose and I thought the usual “there must be a better way of doing this”!
Here my attempt:
import java.util.ArrayList;
import java.util.List;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
public class MakeChange {
static int makeChange(int money, int[] coins) {
if (money == 0 || coins.length == 0) {
return 0;
}
return showChange(money, Ints.asList(coins), 0, new ArrayList<Integer>());
}
static int showChange(int money, List<Integer> coins, int total,
List<Integer> combo) {
if (total == money) {
System.out.printf("%s = %d%n", combo, total);
return 1;
}
if (total > money || coins.isEmpty()) {
return 0;
}
int c = coins.get(0);
List<Integer> comboWithC = Lists.newArrayList(combo);
comboWithC.add(c);
return (showChange(money, coins, total + c, comboWithC) + showChange(money,
coins.subList(1, coins.size()), total, combo));
}
public static void main(String[] args) {
System.out.println(makeChange(4, new int[] { 1, 2 }));
}
}
Specifically, what I dislike a lot is having to do the stuff below just to pass a copy of the list with an element appended to it:
List<Integer> comboWithC = Lists.newArrayList(combo);
comboWithC.add(c);
Please show me how compact and readable Java can be. I am still a beginner in both languages…
Really, almost everything you’re doing here is directly convertible to Java, without much extra verbosity.
For example:
The obvious Java equivalent is:
A few extra words here and there, an extra line because of the closing brace, and of course the explicit types… but beyond that, there’s no big change.
Of course a more Python and Javariffic (what is the equivalent word?) version would be:
The obvious Java equivalent is:
So, Java gets one extra closing brace plus a few chars of whitespace; still not a big deal.
Putting the whole thing inside a class, and turning
maininto a method, adds about 3 more lines. Initializing an explicit array variable instead of using[2, 1]as a literal is 1 more. AndSystem.out.printlnis a few characters longer thanprint, andlengthis 3 characters longer thanlen, and each comment takes two characters//instead of one#. But I doubt any of that is what you’re worried about.Ultimately, there’s a total of one line that’s tricky:
A Java
int coins[]doesn’t have any way to say “give me a new array with the tail of the current one”. The easiest solution is to pass an extrastartparameter, so:In fact, nearly everything can be trivially converted to C; you just need to pass yet another param for the length of the array, because you can’t calculate it at runtime as in Java or Python.
The one line you’re complaining about is an interesting point that’s worth putting a bit more thought into. In Python, you’ve got (in effect):
With Java’s List, this is:
This is more verbose. But that’s intentional. Java
List<>is not meant to be used this way. For small lists, copying everything around is no big deal, but for big lists, it can be a huge performance penalty. Python’slistwas designed around the assumption that most of the time, you’re dealing with small lists, and copying them around is perfectly fine, so it should be trivial to write. Java’sListwas designed around the assumption that sometimes, you’re dealing with huge lists, and copying them around is a very bad idea, so your code should make it clear that you really want to do that.The ideal solution would be to either use an algorithm that didn’t need to copy lists around, or to find a data structure that was designed to be copied that way. For example, in Lisp or Haskell, the default list type is perfect for this kind of algorithm, and there are about 69105 recipes for “Lisp-style lists in Java” or “Java cons” that you should be able to find online. (Of course you could also just write your a trivial wrapper around List that added an “addToCopy” method like Python’s
__add__, but that’s probably not the right answer; you want to write idiomatic Java, or why use Java instead of one of the many other JVM languages?)