I have to say I am a big fan of loops. For many of the problems I have wanted to solve they have been right there beside me cheering me on. The tough thing is deciding when to do which?
I did this Coin Changer Kata in Java, and was given some wonderful advice.
In case you don’t know, the Coin hanger kata is the performance of the coin changer problem. Meaning in the old days when people used cash, you would get your change back. Either a human or a machine would give you the change regardless a computer would have to say which and how many coins you get back. So if you were to get back 25 cents, you would be given one quarter instead of 25 pennies.
Back to the Kata, I had used a while loop in my initial function. Then I took it out into a separate function and kept it the same shape but was given a new pointer. Replace the while loop with a for loop and it becomes cleaner:
public static int addCoins(int amount, int coin, List<Integer> change) {
while(amount >= coin){
change.add(coin);
amount -= coin;
}
return amount;
public static int addCoins(int amount, int coin, List<Integer> change) {
for(; amount >= coin; amount -= coin)
change.add(coin);
return amount;
Three things I learned in this change.
First, we removed an unnecessary line of code and placed the logic in the for
loop. This makes the code more efficient, and gives us a for loop which you know my feelings for.
Second, I had no idea I could pass nothing for the initialization. Since I had always seen some version of int i = 0
I assumed it always had to be present. Alas, amount
is already initialized previously so no need. Magical!
Lastly, recently Java allowed 1 line for
loops to not need {}
. This is a style preference, for my video I think I will still use the brackets because it feels right but it is nice to know there are options.
Java’s strongly typed language has been interesting to get used to. These few tips have been quite helpful in understanding it better.
Best,
Merl