Thursday, June 28, 2012

Coin problem, how do you solve it?

My son has this typical homework problem.  If you have 10c, 20c and 1 dollar.  How many ways can you make $2?

I am pretty sure there should be a combination formula for it, but I forgot.  So I tried google but seems there is no formula

Is there really no formula?

Anyway so he started to make a table of combination.  I told him I better start to see if I can code it, maybe it would help him to verify if the table of combination is correct.  I came up w/ this.  I hope its right otherwise his table of combination is wrong and my code is wrong.

val twoDollars = 200

val coinsCombo = for ( oneDollar <- 0 to (twoDollars/100);
 twentyCents <- 0 to (twoDollars/20);
 tenCents <- 0 to (twoDollars/10);
 if (oneDollar * 100 + twentyCents * 20 + tenCents * 10 == twoDollars) 
) yield (oneDollar, twentyCents, tenCents)
coinsCombo foreach println


No comments: