Java snippets of the day

Palindrome test

import java.util.Scanner;

public class PalindromeTest {
    static boolean isPalindrome(String source) {
		// Trivial case
        if (source == null)
            return false;
		// We ignore case when checking for palidrome
        String toTest = source.toLowerCase();
		// We start at the two ends of the string
        int start = 0;
        int end = toTest.length() - 1;
		// When the ends doesn't meet
        while (start < end) {
			// If they are not characters (like punctuation and spaces, we ignore them by
			// moving the pointer to the next character
            while (!Character.isLetter(toTest.charAt(start)))
                start++;
			// Similiar for the end pointer
            while (!Character.isLetter(toTest.charAt(end)))
                end--;

			// Compares the end and start pointer
            if (toTest.charAt(start) != toTest.charAt(end))
                return false;

			// Match, move to the next position
            start++;
            end--;
        }
		// The whole string has been testetd, so it's a palidrome
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isPalindrome("Dammit I'm mad"));
        System.out.println(isPalindrome("Was it a car or a cat I saw"));
        System.out.println(isPalindrome("A man, a plan, a canal - Panama!"));
        System.out.println(isPalindrome("Are we not drawn onward, we few, drawn onward to new era?"));
        System.out.println(isPalindrome("Go hang a salami; I'm a lasagna hog!"));
        System.out.println(isPalindrome("aaaaaaaaaaao"));
    }
}

String permutation

	import java.util.ArrayList;

	public class PermutationPrinter {

		// Returns the list of possible permutations
		static ArrayList getPermutations(String target) {
			ArrayList result = new ArrayList();
			if (target.length() == 1) {
				// There's only one permutation for "a", right?
				result.add(target);
			} else {
				// There's target.length() way to select a character from a string, so...
				for (int i = 0; i < target.length(); i++) {
					// We iteratively pick characters
					char theChar = target.charAt(i);
					// Take them out of the question, then find the rest 's permutation, the string is
					// smaller by one character, and it will keep getting smaller until there's only 1
					// character left
					ArrayList smaller = getPermutations(target.substring(0, i) + target.substring(i + 1));
					// For each permutation string of the smaller string, add the original character into it
					for (String s: smaller) {
						 result.add(theChar + s);
					}
				}
			}
			// Return theh result
			return result;
		}

		public static void main(String[] args) {
			ArrayList p = getPermutations("1234");
			for (String s: p) {
					System.out.println(s);
			}
		}
	}

A readable example of how code become unreadable

Consider the following problem: You need to calculate how many dots are there in a square triangle for a specific width, for example

.
..
...

Has an area of 6

.
..
...
....

Has an area of 10
The catch is, you are not allowed to use the mathematical formula to calculate the number instantly, so there’s two ways remaining to solve this problem:

  • Use two for loops
  • Recursion

We will follow the second direction because it’s probably shorter to write, so someone wrote

public class TrianglePrinter {
    static int getTriangleArea(int width) {
        int result = 0; // Default return
        if (width > 0) { // Stop condition
            result = getTriangleArea(width - 1) + width; // Split the problem
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(getTriangleArea(4));
    }
}

This can be “optimized” to become a one-line method, short code gives longer lives!

public class TrianglePrinter {
    static int getTriangleArea(int bottomWidth) {
        return (bottomWidth > 0) ? getTriangleArea(bottomWidth - 1) + bottomWidth : 0;
    }

    public static void main(String[] args) {
        System.out.println(getTriangleArea(4));
    }
}

Then when it is compacted (like, in Javascript…)

public class TrianglePrinter {
    static int g(int w) {
        return (w > 0) ? g(w - 1) + w : 0;
    }

    public static void main(String[] args) {
        System.out.println(g(4));
    }
}

Report on a conference

Just finished the morning session of the international conference on information technology for education 2010. Generally speaking, I’m disappointed at the organization skills and the content of the conference.
They started an hour late (9am instead of 8) and even so, they used the first hour to let the sponsoring organizations advertise themselves. Boring, and they haven’t provided us a single bottle of water. The tea break only has some cheap snack, coffee and soya. The tea is too bitter, it’s not something you can hold and sip while talking to someone else.
The technical presentation brings nothing new either. The first, G-system from a university in Canada is about linking everything to create an “internet of things”. Translate into normal English: ubiquitous computing. It’s not something that you need to goto Canada to do. It’s really just as simple as making a new command for Mozilla Ubiquity. If that presentation is to attract student to canada, I would say they haven’t chosen the best representative for their education.
The second keynote, a datamining report from the head of computer science dept. At NUS, my previous dream school. Well, it’s not so dreamy anymore. Hearing him talk about splitting set and reducing sample all I can feel is a non-functional (in academic speak: conceptual) version of a spatial database. I have never agreed with PhD comics like that before. Their best research is esentially fruitless, despite the $50 million funding they got from companies each year.
The third speech is about internet trends. The translator seems to be a representative for the speaker’s company. The guy keeps making stuff up during the translation using his prior knowledge about the speaker. The speech, in sort, describe stuff that i have been tumblr-ing for the past year. Nothing new again.
Fourth speech, a PhD working for Dell’s R and D dept., opening a college in Vietnam (and I guess the fee will be sky high). It’s the same old blame on education: you cannot do anything right after you graduated. I would say bullshit! If you are so good you should have thought if something better than that.
Yeah, so rounded up: I don’t feel this conference is really presenting any useful work and more or less something made up so the experts can get a trip abroad (which their hosting institution paid for).

Just finished the morning session of the international conference on information technology for education 2010. Generally speaking, I’m disappointed at the organization skills and the content of the conference.
They started an hour late (9am instead of 8) and even so, they used the first hour to let the sponsoring organizations advertise themselves. Boring, and they haven’t provided us a single bottle of water. The tea break only has some cheap snack, coffee and soya. The tea is too bitter, it’s not something you can hold and sip while talking to someone else.
The technical presentation brings nothing new either. The first, G-system from a university in Canada is about linking everything to create an “internet of things”. Translate into normal English: ubiquitous computing. It’s not something that you need to goto Canada to do. It’s really just as simple as making a new command for Mozilla Ubiquity. If that presentation is to attract student to canada, I would say they haven’t chosen the best representative for their education.
The second keynote, a datamining report from the head of computer science dept. At NUS, my previous dream school. Well, it’s not so dreamy anymore. Hearing him talk about splitting set and reducing sample all I can feel is a non-functional (in academic speak: conceptual) version of a spatial database. I have never agreed with PhD comics like that before. Their best research is esentially fruitless, despite the $50 million funding they got from companies each year.
The third speech is about internet trends. The translator seems to be a representative for the speaker’s company. The guy keeps making stuff up during the translation using his prior knowledge about the speaker. The speech, in sort, describe stuff that i have been tumblr-ing for the past year. Nothing new again.
Fourth speech, a PhD working for Dell’s R and D dept., opening a college in Vietnam (and I guess the fee will be sky high). It’s the same old blame on education: you cannot do anything right after you graduated. I would say bullshit! If you are so good you should have thought if something better than that.
Yeah, so rounded up: I don’t feel this conference is really presenting any useful work here, another day wasted in commute between countries while they actually could have used it to do real work.