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

http://mathforum.org/library/drmath/view/57913.html

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

println(coinsCombo.size)

Explaining C++, Java and Scala to my son

Last night my son was asking about computers again.  I think the conversation came about, what language is on my screen.  I told him its Java and Scala.  I talked about what is assembly, C, C++ and Objective-C and how it relates to Scratch and Kojo.

He asked about why it was named as C++, then I showed him a Java typical loop which is based C where we increment a counter.

int c = 0;
while (c <= 10) {
 System.out.println(c);
 c++;
}



He asked how the loop will be done in Scala.  I started w/ a for comprehension, as he is familiar w/ loops on Scratch and Kojo.

for (c <- 0 to 10) {
 println(c)
}
Then he asked me about the for, <-, etc.

I then changed the code into

0 to 10 foreach println


His reaction "that is so awesome it's like english!"

Sunday, June 3, 2012

misconception about h2 in memory db

Seems sometimes I have seen h2 url connection as "jdbc:h2:mem", which is different from "jdbc:h2:mem:".  The former will create a persistent db in the current path db called mem, the later will create a in memory db.  The official docs explains in in more detail h2 docs.

A good way to know if its in memory or not is just check your current path.  If you have mem.h2.db and  mem.trace.db on the file system, then you are not using the in memory db.

Most of the time though more than 1 connection is needed.  The first reaction is to remove the extra ":", rather than looking at the docs.  The correct fix will be to name the memory db such as "jdbc:h2:mem:foo".  Or if you use JPA sometimes the abstraction is just to thick, and most developers forget how connections are managed.  A connection is closed per test, in general this is the last connection which leads to new db across a test suite.  So to keep the db alive through out the lifetime of the JVM just add ";DB_CLOSE_DELAY=-1"