Monthly Archive for January, 2011

Project Euler : Finding Minimal Sum Path In A Matrix

The problem 81 of Project Euler gives a square matrix and requires one to find the minimal sum path. Specifically, it only required the sum of the numbers on the path. The question immediately reminded me of problem 67 and I set out solving with the same logic.

The logic has been explained in the following post of mine: Project Euler : Maximum Sum Traversing Top To Bottom In A Triangle.

The following lines of code did the work for me:

    public static int getMinimalSumPath(int[][] numbers) {
        int dimension = numbers.length - 1;
        for (int x = dimension; x >= 0; x--)
            for (int y = dimension; y >= 0; y--) {
                if (x == dimension && y == dimension) continue;
                int val1 = x < dimension ? numbers[x + 1][y] : Integer.MAX_VALUE;
                int val2 = y < dimension ? numbers[x][y + 1] : Integer.MAX_VALUE;
                numbers[x][y] += val1 < val2 ? val1 : val2;
            }

        return numbers[0][0];
    }

Popularity: 13% [?]

Project Euler : Counting The Number Of Right Triangles In A Grid

The problem 91 of Project Euler was a bit tricky. It requires one to find the number of right angled triangles in a n X n grid, with one point (0,0) fixed. For example, as shown on the problem page, a 3 X 3 grid contains 14 triangles. The problem required the answer for a 51 X 51 grid.

Well, at first I started with a pencil-paper approach. I listed down all the cases I could think of and checked my calculation for the 3 X 3 grid. Got the answer right. But applied the same to the larger 51 X 51 grid I realized that there were cases I had not enumerated all the cases. I am still not sure if the problem can be solved using just a pencil and a paper.

I did not want to do a brute force way of picking up two arbitrary points and checking if they form a right angled triangle. In my solution I have never tried to determine the actual triangles. As you shall see, all I do is to find the number of possible triangles by using a parameter and bounding it within an interval. The range of the interval is my solution for that particular point.

I went the mathematics way. One of the points is fixed at (0,0). Select one point as (a,b). The slope of the line joining these two points is \frac{b}{a}. So the equation of a line perpendicular to this one and passing through the point (a,b) would be :

y = -\frac{a}{b}(x - a) + b

Now points which lie on the above line will all form right angled triangles with the points (0,0) and (a,b). The following conditions need to be satisfied in our particular problem:

  • The solutions to the above equation are integers.
  • The points lie within a grid of n X n. So 0 \leq x \leq n and 0 \leq y \leq n.

There are two cases we need to consider. One where a is a multiple of b and the other where it is not.

Let us first consider the case where a is not a multiple of b. We rewrite the equation as follows:

y = -\frac{c}{d}(x - fc) + fd

where f is the gcd of a and b. Now since y is an integer, we can impose the following condition on x :

x = fc + kd

where k is some parameter, in which case the value of y becomes:

y = fd - kc

And now imposing the second criteria, we can limit the values of the parameter k as thus:

0 \leq x \leq n

\Rightarrow -\frac{fc}{d} \leq k \leq \frac{n - fc}{d}

Similarly, imposing the same conditions for y, we get

\frac{fd - n}{c} \leq k \leq \frac{fd}{c}

The intersection of the two intervals gives us the eligible values for the parameter k as :

max ( -\frac{fc}{d}, \frac{fd - n}{c} ) \leq k \leq min ( \frac{n - fc}{d}, \frac{fd}{c} )

For k = 0 we get the point (a,b). For all other values of k we get the points which complete the right angled triangle. So the number of right angled triangles in this case will be the range of k – 1.

Now the other case. Let a = pb. The equation then becomes :

y = -p (x - a) + b

Let q = x - a. Then we have

y = -pq + b

Once again the applying the boundary conditions we get:

\frac{b - n}{p} \leq q \leq \frac{b}{p}

-a \leq q \leq n - a

Once again taking the intersection of the intervals gives us:

max ( \frac{b - n}{p}, -a ) \leq q \leq min ( \frac{b}{p}, n - a )

For k = 0 we get the point (a,b). For all other values of k we get the points which complete the right angled triangle. So the number of right angled triangles in this case will be the range of k – 1.

Add to this the trivial case of 3n^{2} right angled triangles formed when one of the points lie on the axis. It is easy to see these if you sit with a pencil and a paper.

I went ahead to code the above conditions. The code is given below. On my laptop I was able to run this code for a grid of 4000 X 4000 in 1 second.

In the code given below, I have used (xIdx, yIdx) as the point (a,b). f and p are as described above.

    public int getCount(int n) {
        int count = 0;

        for (int xIdx = 1; xIdx <= n; xIdx++)
            for (int yIdx = xIdx; yIdx <= n; yIdx++) {
                int tempCount = xIdx % yIdx == 0 ? countForXMultipleOfY(xIdx, yIdx, n) : countForXNotMultipleOfY(xIdx,
                        yIdx, n);
                count += xIdx != yIdx ? 2 * tempCount : tempCount;
            }

        return (int) (count + 3 * Math.pow(n, 2));
    }

    private int countForXMultipleOfY(int xIdx, int yIdx, int n) {
        int p = xIdx / yIdx;

        int lowerBoundary = NumberUtil.larger((yIdx - n) / p, xIdx * -1);
        int upperBoundary = NumberUtil.smaller(yIdx / p, n - xIdx);

        return upperBoundary > lowerBoundary ? upperBoundary - lowerBoundary : 0;
    }

    private int countForXNotMultipleOfY(int xIdx, int yIdx, int n) {
        int f = MathUtils.gcd(yIdx, xIdx);

        int lowerLimit = NumberUtil.larger(-1 * xIdx / (yIdx / f), (yIdx - n) / (xIdx / f));
        int upperLimit = NumberUtil.smaller(yIdx / (xIdx / f), (n - xIdx) / (yIdx / f));

        return upperLimit > lowerLimit ? upperLimit - lowerLimit : 0;
    }

Popularity: 16% [?]

First Time Travelling In Sleeper Bus

I have always preferred train and after yesterday night’s experience I see no reason why I would want to change the preference. Not being able to book a tatkal tickets in Kacheguda-Bangalore Express I had resigned myself to a bus journey. Having a sleeper bus ticket in hand I thought the experience might be better than that of semi-sleeper ones. Alas, it turned out otherwise.

My seat number was U11. There were 12 seats in the bus, so I was pretty much in the last row. Just as the bus started I got out my laptop and started watching a movie. Movie + checking EPL scores + looking at my location on the goolgle map killed about 3 hours of time. By then everybody was asleep and the lights had been put out. I packed up and lay down to sleep.

It’s amazing that when you are occupied by something how you tend to ignore everything else around you. Now that I had nothing to do but close my eyes, I realized how much the bus was tossing me around. The driver makes a turn and I get pushed across the wall of the bus. A speed-breaker and I get tossed up. And whenever the driver braked sharply, I feared I would fall down. Somehow I managed to sleep.

And arriving at the destination at 6 in the morning didn’t help either.

Nice thing I have already booked my tickets for Holi. Journey by train is way better than bus.

Popularity: 2% [?]

Airtel Call Center People Are Really Dumb

Airtel Logo

This is the second time I’ve really had to call them, and it was just as bad as the last time. Sometimes you get the feeling that the person on the other end of the phone doesn’t understand English at all. Here I was telling him that a certain number I have been asked to call is not getting connected from my handset. And those people reply – Sir, please call the number we have provided you. I do not know any simpler way of putting this!

I wanted to activate Airtel Mobile Office on my Sony Xperia X1a handset. I called up the call center and asked them to activate the RC98 plan. In this plan you pay Rs. 98 for broadband connection having 30 days validity and 2gb data transfer free. Also you get free Airtel to Airtel calls worth Rs. 98. This seemed like a good offer to me. The airtel guy who answered the call told me that settings shall be sent to my mobile and that I had to activate the connection by dialing *567*14#. Simple!

Then started the problems. I did what was needed to be done on my part and was waiting for the settings to arrive. I get an sms telling me that settings shall be sent momentarily. A minute later I get another message telling me that settings have already been delivered to my mobile. WTH! I checked if settings had been updated and the answer was no. Still I tried connecting to internet and obviously my phone tells me that no network settings are available. What do I do?

I call up the call center once again. I go through all the steps to make sure that no mistake had been committed on my part. The airtel person tells me that he’ll send the settings once again, and that if I am still not able to connect then I should call up 12118 for further support. The whole process repeats and no settings delivered.

What was to be done – call 12118. I dial the number. A brief pause and then a message – The dialed number is invalid! Frick!

I call the call center again. Go through the whole thing. Tell them that 12118 is not going through from my mobile phone. The reply – Sir, please dial 12118 for any further assistance. To which I tell him once again that I am not able to dial the said number. The reply – Sir, please dial 12118 for any support regarding mobile internet.

I had serious doubts if he could understand english. So I repeated the whole thing in hindi, slowly and politely. The reply – Sir, please dial 12118 for any further assistance.

I gave up on the guy and disconnected. 121 again. A new guy. Thank lord! I tell him the whole story. He was a smart fellow. Tells me to hold on while he checks back. Sure. Couple of minutes pass by listening to Airtel’s new song. Song stops and he answers back – Sir, please call the alternate number provided to you. And what is the number I ask? 121 he replies and disconnects before I could say a word!

I gave up altogether. Googled up and realized that I could request for the settings from my phone itself. Did that and I have Airtel Mobile Office (EDGE) working on my Xperia X1. :D

Popularity: 7% [?]

Project Euler : Finding Largest 9-Pandigital Number Formed As A Concatenated Product

Problem 38 of Project Euler states the problem of finding the largest 1-9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1, 2, .. ,n) where n > 1. As an example, take the number 192 and its products with 1, 2 and 3.

192 * 1 = 192

192 * 2 = 384

192 * 3 = 576

The concatenated number 192384576 is a 9-digit pandigital number. Another example is that of multiplying 9 with (1, 2, 3, 4, 5) to yield the number 918273645.

The above serves as a hint. We now know that the required answer is at least greater than 918273645. Let us try to eliminate a few options.

Consider all 2 digit numbers in the interval [91, 98]. Their multiplication with 1, 2 and 3 will yield 2, 3 and 3 digit numbers respectively. Concatenating these numbers will result in a 8 digit number. But we need a 9-digit number. So we can rule out this case.

Consider all 3 digit numbers in the interval [918, 987]. Their multiplication with 1 and 2 will yield 3 and 4 digit numbers respectively. With the same logic as the previous case, we can rule out these numbers.

Consider all 4 digit numbers in the interval [9182, 9876]. Their multiplication with 1 and 2 will yield 4 and 5 digit numbers respectively. This is the range we are looking for.

After reducing the search space to 694 numbers, a simple java code did the work. It makes a call to NumberUtil.isNPandigital(int) which returns true if the number is pandigital and false otherwise.

public class Problem_38 {
    public static int getValue() {
        for (int i = 9876; i > 9183; i--) {
            int val = i * 100002;
            if (NumberUtil.isNPandigital(val)) return val;
        }

        return -1;
    }
}

Popularity: 10% [?]

Chelsea’s Slump

Chelsea FC Pictures, Images and Photos

It’s much easier for anybody to criticize the Chelsea team now after a streak of poor performances. I will not go into how bad our players are and  what could have been simply because it is the same set of players that got us the double last year. I have faith in the ability of our stars to do well. But yes, even I will admit that the league title is definitely out of our hands and we must fight for a champions league qualification for the next year, while trying to go as far as possible in the two competitions we are still alive in – the FA cup and the Champions League.

It is rightly said that to be at the top you need to invest more and more money. You need to buy the right kind of players. One example I always come across is a Juventus manager making major changes to his team even after winning the league. You need to induct new faces in your team. It need not be wholesale changes like Real Madrid or Manchester City does, but something more like Barcelona bringing in David Villa, or Manchester United buying Javier Hernandez. Chelsea has failed miserably in this respect.

Back when Roman Abramovich took over the club, he infused over 100 millions to build up a team. Even today we have almost the same set of players. And this summer, a few of them were allowed to leave. While that was a good move to let older players, who have huge pay checks and play lesser, to move on, the failure was in not covering up with good substitutes. Caravalho, Ballack, Deco, Joe Cole were all left out. Caravalho was Terry’s partner at the back most of the last season. Mourinho plays him as his preferred defender even now. And who did we get to cover up for the experienced defender? Well, we put our faith in the young Bruma. He might be a promising young lad, but you cannot expect him to replace Caravalho. And with Alex injured, Ivanovich has to play at center – he was playing right back earlier. And if Terry or Ivanovic decide to rest, we are forced to bring in Bruma.

If we care to look at the midfield, you’ll find Lampard, Essien, Mikel, Ramires, Benayoun and Zhirkov. I think this is a good enough midfield. Sadly though, Benayoun and Zhirkov have been sidelined for long period with injuries and Ramires hasn’t yet come to terms with the physical style of play in England. He gets dispossessed very easily.  And when Lampard was out as well, we were forced to bring in McEachren.

The point I am trying to highlight is that compared to the bench strength of last year, we hardly have any war hardened campaigners this season. Considering the financial stability and a good youth system to feed promising young lads that the club is aspiring for, this was to be expected. Carlo Ancelotti must have been ready to see a couple of players injured, but to have Terry, Alex, Lampard, Zhirkov and Essien all on the treatment table at the same time was improbable to think of. Unfortunately, it came to that. And to make matters worse, we learn later that during those days Drogba had been playing with malaria.

Given all the injuries, a few losses is acceptable. Manchester United drawing a lot of matches played in our favor. But what hurt us later was a loss of form of these star players. I suppose in sports self belief is very important. When you are one to one with the goal keeper, you need to believe that you can put the ball past him. This is what is missing in our strikers right now. Malouda, Drogba, Anelka (that he should be kicked out is a whole different story), Sturridge and Kalou all fail to finish. Our mid field is doing relatively well enough to have lots of possession, but it’s the final third where we fail. And the only way to correct this is to go out, try to score some goals and get the confidence back.

A right blend of youth and experience is the key to success. Until recently Chelsea were the pensioners. This is the first time they have really tried to bring in younger players from their youth academy into the top flight. There are bound to be difficult days during the transition period. But once done, we shall be able to find a system like Manchester United’s and get things working smoothly. Until then we need to be patient. Look at Arsene Wenger’s team. For quite a few years now have they gone without any trophy, but the effort of drafting in youngsters is paying dividends now. Not only have they got a youthful team who are damn quick at counter attack, they also have made financial profits in the previous season.

So instead of calling for sacking or making some drastic change, we need to have patience and put our trust in the current manager. He has won the Champions League with Milan and got the double in his first year in charge at Chelsea, he knows the players very well and he surely is the right man to pull us out of the slump.

Popularity: 1% [?]