Chitika

Friday, October 29, 2004

7427466391

Do you guys know this popular problem, which was used by Google as the second stage test for anyone "smart enough" to solve the problem to send their resume to Google?

f(1) = 7182818284
f(2) = 8182845904
f(3) = 8747135266
f(4) = 7427466391
f(5) = __________

The sequence was part of an e (logarithmic) number, whose sum is 49.
Having to rest my brain for the past 9 years, I decided to give it a shot.
Here's what I came up within an hour...

f(1) = 7182818284
f(2) = 8182845904
f(3) = 8747135266
f(4) = 7427466391
f(5) = 5966290435
f(6) = 2952605956
f(7) = 0753907774
f(8) = 0777449920
f(9) = 3069697720
f(10) = 1252389784
f(11) = 3163688923
f(12) = 9229576351
f(13) = 4822082698
f(14) = 8879332036
f(15) = 6832823764
f(16) = 8328237646
f(17) = 8194558153
f(18) = 2509961818
f(19) = 0727386673
f(20) = 0868058257
f(21) = 0582574927
f(22) = 7492796104
f(23) = 7961048419
f(24) = 4841984443
f(25) = 3463244968
f(26) = 6848756023
f(27) = 9418491463
f(28) = 5209618369
f(29) = 6965521267

Here's my source code, if you guys want to try it out..

private static final BigDecimal ZERO =
  new BigDecimal ("0");
private static final BigDecimal ONE = new BigDecimal ("1");

public static BigDecimal factorial (BigDecimal a) {
  if (a.intValue() == 1) return a;
  else return a.multiply (factorial (a.subtract(ONE)));
}

public static BigDecimal e (
    int elementCount,
    int precision) {
  BigDecimal result = ZERO;
  for (int i=1; i<elementcount; i++)
    result = result.add (
      ONE.divide (
        factorial (new BigDecimal(String.valueOf(i))),
        precision,
        BigDecimal.ROUND_FLOOR));
  }
  return ONE.add (result);
}

public static List parseE (
    BigDecimal e,
    int elementCount,
    int elementsSum) {
  List result = null;
  String s = e.toString().substring(2);
  for (int i=0; i<s.length()-elementcount; i++)
    String sub = s.substring (i, i + elementCount);
    int count = 0;
    for (int j=0; j<elementcount; j++)
      count += sub.charAt(j) - '0';
    }
    if (count == elementsSum) {
      if (result == null) result = new ArrayList ();
      result.add (sub);
    }
  }
  return result;
}

public static void main (String[] args) {
  BigDecimal e = e (1000, 1000);
  System.out.println ("e = " + e);
  List magicNumbers = parseE (e, 10, 49);
  if (magicNumbers != null) {
    int count = 0;
    for (Iterator it = magicNumbers.iterator();
         it.hasNext();) {
      String s = (String) it.next();
      System.out.println ("f(" + (++count) + ") = " + s);
    }
  }
}

It was fun.. :D


Thursday, October 28, 2004

SimpleDateFormat bug

I've just realized that SimpleDateFormat has an unexpected behavior. I don't know whether I should refer to this as a bug or not, you guys decide.. :D

Try this..

DateFormat df = new SimpleDateFormat ("dd/MM/yyyy");
try {
  System.out.println (df.parse("31/11/2004"));
  System.out.println (df.parse("-1/-1/-1"));
} catch (ParseException e) { }

In my current implementation, I perform some sanity checking towards this behavior, but am I the only one who has to deal with this?
I've been searching in Google, but I can't seem to find anyone else having the same problem as I do..
Anyway, I'm using JDK 1.4.1_01 for Win2K (just for the record)..


Friday, October 22, 2004

implementing Visitor pattern

During a development of any project, there will be many times where we have to deal with Collection classes, especially List & Map. Sometimes we have to iterate through a List to find an object which matches our criteria. Sometimes we iterate to filter out elements of the List which does not meet our purpose. Sometimes we iterate the List to summarize their values. There are plenty of stuffs we can perform while we're iterating a List.

Currently, I'm trying to implement the Visitor pattern while iterating through a List. There are several cases which I encounter, which requires me to iterate through a List and filter out elements of that List which does not meet the criteria set earlier. At first, this may seem to be a simple thing to do, just iterate, compare & remove. But, living up to the DRY (Don't Repeat Yourself) paradigm, I'm trying to *think* a level of abstraction to the problem.

Here's what a simple filter code would look like:

for (ListIterator it = aList.listIterator ();
     it.hasNext ();) {
  Customer c = (Customer) it.next ();
  String occupation = c.getOccupation ();
  if (occupation == null ||
      occupation.equals ("java developer")) {
    it.remove ();
  }
}

Now, when I require the similar filter logic (iterate, compare & remove) to be reused for different sets of data and compare rules, I'd have to recode the whole iteration again. And, this type of thing tends to increase in numbers before a project ends.

So, here's my current approach. I'm declaring an interface in which every filter class needs to implement.

public interface ListFilter {
  public boolean passes (Object o);
}

This filter will be used within the generic iteration. Here's an example where I use the generic (iterate, compare & remove) logic to filter the List based on more than one filter rules.

public static List filterList (
    List original, ListFilter[] filters) {
  if (original == null ||
      filters == null || filters.length <= 0) {
    return null;
  }

  // assume you have a method to clone the List
  List cloned = cloneList (original);

  for (ListIterator it = cloned.listIterator ();
       it.hasNext ();) {
    Object o = it.next ();
    for (int i=0; i<filters.length; i++) {
      ListFilter filter = filters[i];
      if (filter != null && !filter.passes(o)) {
        it.remove();
        break;
      }
    }
  }

  return cloned;
}

For the above sample case, where we'd like to filter out all unemployed Customers and all java developers from the sales options the company is trying to promote, then we could have implemented the ListFilter as follows:

public class OccupationFilter implements ListFilter {

  private List forbiddenOccupations;

  public OccupationFilter (List forbiddenOccupations) {
    this.forbiddenOccupations = forbiddenOccupations;
  }

  public boolean passes (Object o) {
    if (o != null && o instance of Customer) {
      if (forbiddenOccupations != null &&
          forbiddenOccupations.size() > 0) {
        Customer c = (Customer) o;
        String occupation = c.getOccupation ();
        if (forbiddenOccupations.indexOf(occupation) >= 0)
        {
          return false;
        } else {
          return true;
        }
      } else {
       return true;
      }
    }
    return false;
  }
}

And, since our generic filter logic is capable of applying multiple filters during a single iteration, it helps us to easily add more filters as we see fit. These filters can even act as singleton if they don't have a dynamic part of their rules.

I'm currently trying to abstract out a summary logic (iterate, compare, summary if necessary) from the same List iteration. I hope I can find a neat way to do it.. :D

Further Reading:
Refactoring: Improving the Design of Existing Code
Design Patterns
Head First Design Patterns


Tuesday, October 19, 2004

the Joel test

Looking at the Joel Test, I've come to realize why didn't I read it in August 2000, when it was released. Why did it take me 4 years to finally come across it?

Well anyway, my best project was 2 years ago, and it scores only 4 out of 12. Before reading the Joel Test, I was aiming to score 10-11 out of 12. I'm currently stuck in a project, which is not managed by me or my company, and it's currently scoring at 2. It's too political to even try to do something for the project, so either I find a company who is at 12 or for me to find a company which will allow me to change them into 12.

Anyway, I hope this dream can come true.. :D

Further Reading:
Joel on Software

Tuesday, October 12, 2004

Mark Eagle's Spring presentation

Over the weekend, I took the chance to watch the videotape of Mark Eagle's Introductionn to Spring in front of Atlanta JUG Meeting back in July 2004. The videotape was very good, even though it's mainly focusing on the presentation but not covering any of the audiences. I learned a lot from the presentation, and I'm suggesting anyone else to do the same.

It's a two-hour presentation, packed with good stuffs. Even though it's probably best to be there myself, watching a presentation which can be reversed and repeated over and over again, until I get the point, is also good.

So again, watch the videotape here, and let me know what you think.. :D

Further Reading:
Expert One-on-One J2EE Development without EJB
Spring Live
Spring in Action

Thursday, October 07, 2004

login GUI sample source code

Referring to my previous post, here's the source code that I made..
I decided to separate the implementation into:
- a Screen class which will manage the event handling & business delegation
- a Builder class which will be responsible for laying out the components
- constant classes, such as Fonts, Colors & Dimensions, for consistency, reusability & efficiency throughout any number of GUIs we may have
I used GridBagLayout extensively in this example, it's still one of my favourite layout because it can lay the components in almost any layout

Now, after exploring more and more, I'm considering JGoodies FormLayout & its contributor, FormLayout Maker for any well structured forms. And, ExplicitLayout for other layout which may never be possible to create using any layout manager ever existed.

Anyway, as the sharing goes..
I'm interested if anyone can suggest an idea on how the responsibility for the classes involved in a GUI be divided..
You can find my approach in the attached file, let me know yours.. :D

Further Reading:
Swing Second Edition
Java Swing Second Edition

Tuesday, October 05, 2004

Swing layout comparisons

An interesting comparison..

GBL <= TableLayout < HIGLayout < FormLayout
GBL <= TableLayout < HIGLayout < ExplicitLayout
HIGLayout < SpringLayout
BorderLayout < TableLayout
GridLayout < HIGLayout
GridLayout < FormLayout


Read their arguments here

I'm trying FormLayout Maker, and let's see how well it goes.. :D

Further Reading:
Swing Second Edition
Java Swing Second Edition

Monday, October 04, 2004

Swing layouts

Developing GUI layout in Swing requires a considerable amount of time, especially if you just starting to learn how to Swing. The easy layouts, such as FlowLayout, BorderLayout, BoxLayout, and GridLayout does not really take you anywhere, especially in the case of creating complex GUI.

Luckily, we have the powerful GridBagLayout, which is a bit complex for a startup, but can be very efficient for an experienced Swing GUI developer. However, after looking at JGoodies Forms, it's very interesting to explore more on what the community has to offer.

First, we have SpringLayout which were added into the J2SE 1.4 distribution. Then, we have FormLayout which is contributed by JGoodies. FormLayout is a very good layout which allows us to create form layouts in 1-2 hours max. I'm trying to explore through ExplicitLayout & TableLayout, and see if they have some added values as well.

I hope I can get a chance to explore more on many other available layouts.. :D

Links:
JGoodies Forms
ExplicitLayout
TableLayout

Further Reading:
Swing Second Edition
Java Swing Second Edition

Friday, October 01, 2004

Swing challenge

I'm currently challenging myself and a few other co-workers to implement a simple UI in Swing. The challenge is to create a simple XP-style login page, as can be found in the JGoodies website.



The challenge is to create it within a 10-coding hour limitation, and implementing it using standard Swing libraries. The final submission date is next Wednesday. I wanted to try to create the login page as best as possible without any help from third party libraries, such as JGoodies.

I wanted to compare the source codes that we have by then, and try to have a discussion over how the code should be best put. Then, I wanted to try the JGoodies on, and see the difference in the quality & productivity aspect. Since this is just a simple & fun challenge, I'm not hoping to receive many submissions. But, I'll try to create my version on it, and share it here once completed.. :D

Is there anyone willing to give this challenge a shot? :D

Further Reading:
Swing Second Edition
Java Swing Second Edition