Monthly Archive for August, 2011

Java ArrayList Is Actually Just An Array !

I was reading The Art of Computer Programming Vol 1, the chapter about arrays and list. Knuth describes the differences and mentions how it’s very easy to add a new element to a list in a constant time if we have the node where the insertion needs to happen. Same for deletion. That is when I realized I did not know how the ArrayList implementation handles it. I did a code walk through of that class – something Prasun had advised me long ago but I always ignored.

I always knew that ArrayList used array for implementation, which is how it can guarantee the O(1) element access time. But I did not know how the other methods worked. For instance, one need not provide any initial size of the ArrayList. How does Java handle it? I remember Prasun telling me that the initial size in such cases is 10. But then what happens in the case of an overflow? What is the new space that gets assigned to the list?

But I was more interested in the add(index, element) and the remove(index) methods. And they are not constant time! They are O(n) operations. Say we want to remove(6). Java actually copies over all the elements from 7..n to indexes 6..n-1 and then sets the nth element as null. This is so not what we learn as deletion in list where it was just a matter of changing a couple of pointers (the next and prev ones).

Popularity: 2% [?]

Project Euler : Count Of Lychrel Numbers Below 10000

Problem 55 of Project Euler explains what Lychrel numbers are and asks one to find the number of those below 10000. The only sticking point in the whole procedure is that after a few iterations the number become so large that BigInteger needs to be used. But otherwise, just follow the wording of the statement and the problem will be solved.

Here’s the outermost loop which does the counting:

    private static final int ARRAY_SIZE = 1000000;
    private static final BigInteger BIG_ARRAY_SIZE = BigInteger.valueOf(ARRAY_SIZE);

    public static int countOfLychrelNumbers(int upperLimit) {
        int count = 0;

        State[] lychrelNumbers = ArrayUtils.createArray(ARRAY_SIZE, State.NOT_VERIFIED, new State[0]);
        for (int i = 0; i <= upperLimit; i++) {
            if (lychrelNumbers[i] == State.NON_LYCHREL) continue;
            if (lychrelNumbers[i] == State.LYCHREL || testForLychrelProperty(lychrelNumbers, i)) {
                count++;
            }
        }

        return count;
    }

    private enum State {
        LYCHREL, NON_LYCHREL, NOT_VERIFIED
    }

It’s in the testForLychrelProperty method that all the caching logic comes in. It makes sense to cache the results. However, I have imposed a cache limit as well. Here’s the messier code with caching logic:

    private static boolean testForLychrelProperty(State[] lychrelNumbers, int number) {
        int iterCount = 1;
        State state = State.NOT_VERIFIED;
        BigInteger num = BigInteger.valueOf(number);
        List<BigInteger> found = new ArrayList<BigInteger>();
        found.add(num);
        while (iterCount < 50) {
            BigInteger reverse = NumberUtil.reverse(num);
            BigInteger sum = reverse.add(num);
            if (!num.remainder(BigInteger.TEN).equals(BigInteger.ZERO)) found.add(reverse);
            state = sum.compareTo(BIG_ARRAY_SIZE) < 0 ? lychrelNumbers[sum.intValue()] : State.NOT_VERIFIED;
            if (state == State.LYCHREL || state == State.NON_LYCHREL) {
                break;
            }
            if (PalindromeUtil.checkIfPalindrome(sum.toString())) {
                state = State.NON_LYCHREL;
                break;
            }
            num = sum;
            found.add(sum);
            iterCount++;
        }

        if (state == State.NOT_VERIFIED) state = State.LYCHREL;

        setState(lychrelNumbers, found, state);
        return state == State.LYCHREL;
    }

The setState method simply updates the cache with the latest result. Here is it’s implementation:

    private static void setState(State[] lychrelNumbers, List<BigInteger> numbers, State state) {
        for (BigInteger number : numbers) {
            if (number.compareTo(BIG_ARRAY_SIZE) > 0) return;
            lychrelNumbers[number.intValue()] = state;
        }
    }

All in all, the code runs in some 180ms on my laptop.

Popularity: 6% [?]

Project Euler : Largest Sum Of Digits In Exponentiation

The problem 56 of project euler requires one to sum the digits of the exponentiation a^b, where 1<= a,b <= 100, and find the largest sum.

Well, let’s just say I did it by proper brute force. Here’s my java code:

    public static int largestSumOfDigitsInExponentiationNew(int baseMax, int exponentMax) {
        int largest = 0;

        for (int i = 1; i <= baseMax; i++) {
            BigInteger num = BigInteger.valueOf(i);
            BigInteger prev = num;
            largest = Problem_56.checkLargestSum(prev, largest);
            for (int j = 2; j <= exponentMax; j++) {
                prev = prev.multiply(num);
                largest = Problem_56.checkLargestSum(prev, largest);
            }
        }

        return largest;
    }

    private static int checkLargestSum(BigInteger number, int curentLargest) {
        int sum = NumberUtil.getSumOfDigits(number);
        return curentLargest < sum ? sum : curentLargest;
    }

Popularity: 6% [?]

Facebook Status

I miss those days when I used to type ANNA and google suggested me KOURNIKOVA

– When Anna Hazare was on an indefinite fast for  the Jan Lokpal bill.

Popularity: 1% [?]

Yea Chelsea Won, But Where’s The Magic?

Two years ago, and the trio of Drogba, Anelka and Malouda formed the lethal frontline and Chelsea netted more than 100 times in the Premiere League. Fast forward to the 2011, the same players are struggling to find the back of the net just once! It’s sad, disappointing and to a certain extent frustrating.

There was the era when Joe Cole would weave down the right flank and Ballack would power his way through the center. But we do not have them any more. We have instead chosen to replace them with players like Ramires, Benayoun, McEacharen. Chelsea need to realize that the days of powerplay are over, that we need a creative midfielder to make the best use of Torres, that the golden days of Drogba are done – yeah, sadly, but I do admit it.

The problem with the current crop of players is that I do not have confidence in half of them. I’ve never liked Anelka. Drogba is past his prime. Malouda, well, half the time he’s amazing and the other times he a flop. I think it’s only because of his understanding and teamwork with Cole that he keeps his place in the starting lineup. Kalou has been a disappointment. And being a deep lying midfielder, Mikel misplaces a lot of his passes.

I love Terry as a captain. Lampard is good going forward. Cech is an amazing keeper. I also like Cole, Ivanovich and David Luiz. Ramires keeps himself busy going back and forth. And I believe in Torres, a lot.

There you go, half my starting likeup doesn’t impress me. I would want Josh to play instead of Mikel. Now that we have got Lukaku, let him start instead of Kalou.

But unless Chelsea really up their game it’s going to be another slow and long season. And I do not want to sit hoping in front of the television only to be disappointed every other time.

Popularity: 1% [?]

I Need A Break

Yeah, I definitely do. Mostly because of late all that I have done seems to be directly related to my work. I have hardly had any spare time for myself. Contrast this to FICO and I had a lot of free time earlier. I used to spend an hour almost everyday towards Project Euler problems. That is something I haven’t done in a while now. Also I have always wanted to try my hand at an Android App. I have a something that I would like to make for myself, but once again I need more time.

Yea, I definitely do need a break. This long weekend and the trip to Hyderabad could not have come at a better time. It’ll be refreshing to get away from Bangalore and have a couple of peaceful days.

Until then, I’ll just listen to the song by Scorpions – Holiday:

Let me take you far away, you’d like a holiday!

Longing for the Sun, you’re welcome, to the island without name.

Popularity: 1% [?]