# Monthly Archives: December 2011

## Algorithms: LCM and GCD

Least Common Multiple: lcm(a,b) = abs(a*b) / gcd(a,b) = abs(a) / gcd(a,b) * abs(b) Greatest common divisor: gcd(a,b) = gcd(b, a%b); Code: int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a%b); }

## Java: Quick Way to initialize arrays

Instead of: for (i = 0; i < array.length; i++) array[i] = <initValue> One can just do: Arrays.fill(array,<initValue>); Works for String[] at least.

## Java: ArrayList.toArray() usage shortcut

Saw this pretty neat shortcut to get a List<T>[] to T[]. Usage: List<String> res = new ArrayList<String>(); String[] result = res.toArray(new String[res.size()]);  I had originially seen this: String[] result = res.toArray(new String);  But supposedly using res.size() is better. StackOverflow

## Regular Expressions

“1+1=2” How do I use Java’s String.split so + and = will be matched on? Regular Expression : \\+|= Forgot about the existence of the OR |. public static final String EQUATION_TEST = “1+1=2”; String[] str = EQUATION_TEST.split(“\\+|=”); System.out.println(“EQUATION_TEST.split=”+str.length);// Should … Continue reading

## TopCoder: Good Question

I work through a simple TopCoder question a day and ran into this one that I liked. You can do it two ways, by regular expression or through coding logic.  Originally I did it through logic and later tried out … Continue reading

## Java: JDBC Basics

Running through this tutorail: http://docs.oracle.com/javase/tutorial/jdbc/basics/index.html Used JDBC before at Northrop figuring it out with working knowledge but never really went through a tutorial for it. Nice thing about the tutorial is that it populates a DB with data for you … Continue reading