Thursday, May 15, 2014

Project Euler : Probelm 78

The Project Euler : Problem 78 has been solved by comparatively less number of people than other problems on the same page. It is stated as
Let p(n) represent the number of different ways in which n coins can be separated into piles. For example, five coins can separated into piles in exactly seven different ways, so p(5)=7.
Find the least value of n for which p(n) is divisible by one million.
This is exactly the same as integer partitions - which is the number of ways in which a given natural number can be written as sum of smaller natural numbers. You can find the proof of the formula in this discussion.

I previously described two algorithms to calculate the integer partitions. The recursive algorithm suffers from being very slow, to the point of being useless. The iterative algorithm has acceptable speed, but its memory requirements prohibit it from being used for solving this problem.

So we need a much better way to calculate integer partitions. Fortunately, we can use some mathematics. You can check Wikipedia article on integer partitions, which mentions the following formula.
P(n) = P(n-1) + P(n-2) - P(n-5) - P(n-7) + …

There 2 things to notice.
  1. The sign of each term changes based on the formula mentioned below.
  2. Every term on the right hand side is of the form N-x. This x has to be a “Pentagonal Number” and is also given by the same formula below.
More concisely,
P(n) = SUM of [ (-1)^k . P (n - k(3k-1)/2) ]
for both positive and negative values of k as it goes from 1 to N.
Of course P(m) = 0, for any m less than 0.

We can use it to solve the Project Euler Problem 78 in a straight-forward way.

We start with calculating P(n) from 1 onwards up to an arbitrary number, say 1 million. To calculate P(N) at any iteration we have a nested loop that goes from N down to 1, examining only those numbers given by N-x, where x is a pentagonal number. We must consider both negative and positive values of x at every iteration and use proper sign to either add or subtract P(N-x). We will stop when we find a value of P(n) which is divisible by 1 million.

One thing to keep in mind is, the values for P(N) can get fairly large. There is no need to use anything like BigInteger, as we are only interested in the divisibility test, hence we can use the modulo arithmetic.

Here is an outline of the algorithm.
public static long GetNWithModulo1MPartitions () {

    final int MOD = 1000000 ; // divisible by 1M, from problem description
    finat int MAX = 1000000 ; // arbitrarily choosing max value for N
    int [] NumPartitions = new int [MAX] ;

    NumPartitions [0] = 1 ;
    NumPartitions [1] = 1 ;
    NumPartitions [2] = 2 ;

    for (int i = 3 ; i <= MAX ; i++ ) {
   
    long pn = 0 ;

    int sign = 0 ;
    long m1val = 0 ;
    long m2val = 0 ;

    int j ;
    for (j = 1 ; j <= i ; j++) {
        int m1 = i - (j * (3*j - 1) / 2) ; // using positive j
        int m2 = i - ((-1*j) * (3*(-1*j) - 1) / 2) ; // using negative j
        sign = (j%2 == 0) ? -1 : 1 ; // do we add or subtract ?
        // NOTE : in the following
        // if m1 or m2 is negative, the number of partitions is 0 by definition
        // We will add both, as one of them will be zero.
        m1val = (m1 < 0) ? 0 : (NumPartitions[m1] % MOD) ;
        m2val = (m2 < 0) ? 0 : (NumPartitions[m2] % MOD) ;

        pn = (pn + (sign * m1val) + (sign * m2val) ) % MOD ; // the real equation

        if ( pn < 0 ) {
            pn += MOD ; // force positive values
        } //
    }

    NumPartitions[i] = pn ;

    if ( pn == 0 ) {
        System.out.println ("Found N where P(N) is divisible by " + MOD + " and N = " + i) ;
        return ;
    }
    }

} //
That's a bit complicated. It certainly is too much for an interview question, even after giving the formula. The previous article on a recursive, as well as an iterative algorithm,  is a much better choice for a programming interview.

Sunday, April 13, 2014

Iron Lady

Movie Review : Iron Lady
Genre : Biography / Drama
Director : Phyllida Lloyd
Starring : Meryl Streep, Jim Broadbent, Susan Brown
Released : 2011
My Rating : 6 out of 10
A few days ago was the death anniversary of British ex-Prime Minister Margaret Thatcher and I was reminded of this movie. Eager to get a recap about a very influential and controversial figure in World History, I watched the movie with an open mind, as I really didn’t remember much about the so called Thatcherisms.

The movie opens with an old Mrs Thatcher living alone in an apartment, suffering from dementia. She often talks to her husband, seemingly unaware that he is dead. Most of the time she is just another old lady, except sometimes, she remembers her years as the Prime Minister. These earlier years, as a young candidate, her marriage, rise to the highest political office is shown to us via flashbacks. These flashbacks are generally short, providing just a glimpse of her days at the office. On the other hand, the flashbacks related to her family life are more illuminating.

The focus of the movie is clearly on the last days of Mrs. Thatcher, her battles with dementia and memory loss, with a sincere attempt of showing the loving relationship she shared with her husband. Rest of the material just builds the context.

That was my main problem with the movie. Margaret Thatcher is not just one of the many political leaders in recent history. Her influence on Britain as well as World, is large. She was  a polarizing figure, well known for a her fiscal conservative policies. I would have really liked if the movie had lived up to its title. There was so much opportunity. The script could have focused on some key events such as the Falklands War, or the union strikes, and tried to show her struggles, how she overcame the adversity. At the same time, it could have highlighted the strength and stubbornness of her character, and why she came to be known as the Iron Lady, with both good and bad connotations of the term. Especially now, as there are far more skeptics of the European Union than ever, and Mrs Thatcher’s views on the matter were essentially correct, although unpopular when she was expressing it. A focus on such things would have been so much more interesting. As it stands, the movie is not captivating at all.

There is nothing wrong in making a movie about people suffering from illnesses related to the old age. But if that's your goal, then you don’t need to chose Margaret Thatcher as the main subject. However, this does allow Meryl Streep to shine through. She won her third Oscar, only her second as an actress in a leading role. The previous came from her deeply emotional performance in Sophie’s Choice, almost 30 years ago. The range of roles she has played in all those years is unparalleled. It’s yet another performance, where she just immerses herself in her character. Helping her do that is her makeup, for which the makeup artists (Mark Coulier and J. Roy Helland) won a well deserved Oscar.

The rest of the cast lends good support. As I said, the main problem is the script, trying hard not to present any sharp views in this controversial figure, and as a result giving us a very bland movie.

I can recommend this movie only for watching one more beautiful demonstration of Meryl Streep’s acting prowess. If you are interested in knowing about Margaret Thatcher as a person or as a Prime Minister, a Wikipedia article is going to be a better source. The movie is appropriately rated as PG-13, but even the older kids will be thoroughly bored.

Monday, April 7, 2014

Kasparov on Kasparov Part 2



Book Review : Gary Kasparov on Gary Kasparov Part 2 1985-1993
Author : Gary Kasparov
My Rating : 5 out of 5 stars

Kasparov’s massive book writing project is going strong. The second book in the series on Kasparov himself, has been available for a while now and is as good as all the other books. I have a talked a lot about his entire project and this series when I wrote the review of his first book.  If you are not familiar with his 10+ books so far, please click on that link for more information.

This book, as is to be expected, follows the same format and the presentation style. So I am going to skip reviewing that particular aspect.

As the title says, the games being focused here are from the period 1985 t o 1993. It starts with the second match for the World Championship title against his arch rival Karpov, and covers the period till Kasparov’s decision to break away from FIDE.

I noted a slight difference from the first book. Here, there are less autobiographical notes than the first book. This was a politically tough period due to the break up of former Soviet Union. Kasparov’s mother is Armenian and his family lived in Baku, which is in Azerbaijan. As a result of different ethnicity, his family was in danger during the turbulence. Kasparov talks about how they all made to safety, and how it affected his chess. But these life stories are a definite sideshow.

The focus is on games, which are played by an even more improved Kasparov from the first book. These are explained with passion and clarity. The last game from his second match with Karpov, when Kasparov became the Champion for the first time, is explained in nearly 10 pages! Not just dry variations after variations, but explanation that is accessible to someone like me who is just a woodpusher but still an enthusiast. Some of the annotations give such a nice insight into how he has approached and understood chess. In one game he explains that his opponent Karpov missed a better move due to his playing style, and Tal would have found it naturally. But then, Kasparov explains, he wouldn’t have created such position on the board, if he was playing against Tal! That’s match strategy 101 right there. Of course much easier said than done.

Kasparov is also known for his legendary opening research. He talks about it freely, how and when he studied the particular opening system, how he anticipated his opponents moves, and had the novelties in mind. Many of his games gave new direction for many variations, and he points that out while discussing the novelties and their impact.

Kasparov also explains what went through his mind, before and during the game. It’s not a secret that Kasparov had this intense desire to win and dominate. When he drew a series of games against the topmost players, he considered it as a slump! He wanted to take revenge, and make a point. He always wanted to assert via his games, that he was indeed the Champion. There is no gloating. He has chosen games, where he failed to win, especially against his new arch rival Anand. At the end of the book, he openly admits that breaking away from FIDE was the biggest blunder of his life. There is no sugar coating. Just plain truth as he sees it. It all makes for such a wonderful reading.

I absolutely recommend this book. Note that there is some overlap with his previous books about the World Championship matches with Karpov. I have them, and I do not mind the repetition. I am now waiting for his next installment and then hopefully a new series about the latest players.

Friday, March 21, 2014

Prisoners

Movie Review : Prisoners
Director : Denis Villeneuve
Genre : Thriller
Starring : Hugh Jackman, Jake Gyllenhaal, Maria Bello, Viola Davis, Paul Dano
Released : September 2013
My Rating : 8 out of 10

Hollywood has produced many movies about abductions, especially about child abductions. Like most Hollywood movies, such thrillers are often formulaic. In spite of some notable exceptions like “Changeling”, it’s natural to ask, what can a new movie do to stand out? Watch “Prisoners” and you will know the answer.

The movie starts with two families meeting for a Thanksgiving dinner. After the dinner, their two young girls go out to play without telling their parents. When the girls do not come back, and are not found after a search by the family members, they call police. A suspicious van was seen parked in the neighborhood. With that as the only clue, police search for the van. When it is located, the driver seems to be a mentally unstable person. He is arrested, but there is no sign of girls or any indication that he was involved. Without further evidence, the police have no choice but to release him, in spite of the parents strongly protesting against it.

The movie takes a unique turn after this, which I would prefer to not reveal, even though the trailers might have given it away. Of course there is the mystery of what happened to the girls, and who did it. I think many viewers are going to guess it early and correctly. That definitely is a flaw in the script.

The strength of the script is in its ability to force us to take sides, to make assumptions, to associate guilt and to question ourselves, what’s right and what’s wrong. The characters are complex, sometimes we empathize with them, sometimes we find them irrational. There are hardly any coincidences, and there are no weird twists. But there are mistakes and there are lucky breaks. It feels like a true detective story, with many moral dilemmas.

The cast is impressive. Hugh Jackman, perhaps the highest profile actor among them, gives a very believable and strong performance as Keller Dover, father of one of the missing girls. Jake Gyllenhaal gives yet another wonderful performance as Detective Loki. He definitely has a knack for choosing roles, this is so different than Source Code and Proof.  Viola Davis, as Nancy Birch, mother of a missing girl has a short role, like she had in Doubt, and shines here as well. Another good actress who shines in a short role is Melissa Leo (Frozen River). Everyone else does a tremendous supporting job as well, not a single performance is weak.

This is an English language debut movie for director Denis Villeneuve. He has kept the movie sincere as well as taut. It felt a bit longer than needed to me, but it’s always gripping.

The movie makes for an uncomfortable viewing, but not because of blood and gore. The topic is unsettling, and the past revealed by the story is tragic as can be expected. With that note, I highly recommend it. It will make you feel, and make you think. It goes without saying that this movie is not for kids.

Saturday, March 8, 2014

Redneck Woman

Every song, rather every good song, has a story, or a message or a point to make. As a listener, we may or may not relate to it. Generally, we tend to like songs that we can relate to, goes without saying. There are exceptions. Gretchen Wilson's "Redneck Woman" is a song that I of course cannot relate to literally, but I still enjoy it immensely. And it's clear that I am not alone. It reached the top of the Billboard Country charts, and also won her the Grammy for Best Female Country singer.

May be behind the rebellious, in-your-face lyrics, there is an idea of staying true to your heritage that appeals us.
Some people look down on me,
    but I don't give a rip
I'll stand barefooted in my own front yard with a baby on my hip

'Cause I'm a redneck woman
    I ain't no high class broad
I'm just a product of my raising
    I say, 'hey ya'll' and 'yee-haw'

And I keep my Christmas lights on
     On my front porch all year long
And I know all the words to every Charlie Daniels song

So here's to all my sisters out there keeping it country
Let me get a big 'hell yeah' from the redneck girls like me, hell yeah
There is a raw sharp edge to her voice that I really like. So it pains me to say this, but Gretchen Wilson turned out to be a one hit wonder. There are other songs from her that I like, especially "When I think about cheating", but overall, not much followed the success of this debut song.

Enjoy ..

Wednesday, February 12, 2014

GaDiMa-6

One of the Hindi Movie directors I admire is Raj Khosala. When he was in his prime in 50s and 60s, he rarely played safe, and produced movies that although commercial, traveled different paths than main stream movies. His movies "Woh Kaun Thi", and "Mera Sayaa" have some minor similarities. Both were suspenseful, with Sadhana as lead actress (his favorite choice), and both had wonderful songs by Madan Mohan. Both the movies were also inspired by other movies.

While "Woh Kaun Thi" was loosely based on "Woman In White", the later "Mera Saaya" was almost a remake of a Marathi movie "Paathlaag" (meaning 'chase'). Both the movies, Marathi as well as Hindi had haunting title songs. The music for Marathi movie was composed by Datta Dawajekar, with lyrics by GaDiMa. Needless to say Asha sounds amazing, as usual, in this title song.

या डोळयांची, दोन पाखरे, फिरतील तुमच्या भवती
पाठलाग ही सदैव करतील, असा कुठे ही जगती

I distinctly remember, as a child, being spooked by the eerie tune of this song, so I don't think I ever paid any attention to the lyrics, till I grew up. The interesting thing here is, the comparison of eyes with haunting birds, is not just in the mukhada. GaDiMa developed it as the theme of the entire song, in both the antaras.

दर्शन तुमचे, हाच असे हो या पक्ष्यांचा चारा
सहवासवीण नकोच यांना अन्य कोठचा वारा
तुमचा परिसर यास नभांगण, घरकुल तुमची छाती!

The second antara is beautiful, and the second line is my favorite.

सावलीत ही बसतील वेडी, प्रीतीच्या दडूनी
एका अश्रुमाजी तुमच्या, जातील पण बुडूनी
नव्हेत डोळे, नव्हेत पक्षी, ही तर अक्षय नाती!

This ability of infusing beautiful poetry using simple words in routine songs, in words that were written on demand, as opposed to ones that flow suddenly from an inspiration, is all but lost now. That's what made GaDiMa, and Sahir so great.

Enjoy ...

Monday, January 27, 2014

Yogisms

When I moved to US from India, I had no idea who Yogi Berra was. Soon, I started noticing that journalists sometimes insert his quotes in their stories on many diverse topics. In India, the term "Yogi" has some specific meanings. With that kind of name, and those uniquely styled quotes made me really curious about him. He seemed like some modern day Confucius!

Wikipedia didn't exist then. (Really!) So I found out about him the old fashioned way - by asking around. Turned out that he was one of the greatest Baseball players, Lawrence Berra, and a celebrated Yankees coach, and the name "Yogi" was given to him jokingly for his sitting style.

He stopped playing even before I was born. Although I enjoy Baseball, and watch the play-offs, specially when SF Giants are playing, I am not a fan enough to learn history, or dig up old videos to see him in action. But I did try to read up about his quotes. Were these intentional? Turns out, these brilliant quotes were just accidental.

I just decided to note my favorites, "Yogisms". Why and why today? Why not? :-)

The following are used so often, that we have stopped noticing the tautology and the paradox. I really find it amazing that we have actually adjusted our minds to use these appropriately.
It ain't over, till it's over.
It's Deja'vu all over again.
Nobody goes there anymore. It's too crowded.
Some can be very thought provoking. It's remarkable that someone can say these without actually meaning to be intellectual.
The future ain't what it used to be.
If the world were perfect, it wouldn't be
.
Some are just funny, but still require a bit of attention to notice the humor.
I usually take a two hour nap from one to four.
Always go to other people's funerals, otherwise they won't go to yours.
The real Yogism's to me are the ones that make you go, "What? Come again ...".
When someone asked him what's the time, he replied, "You mean, now?"
It gets late early out here.
90% of the game is half mental.

While giving directions to his home, "When you come to a fork in the road, take it."
You can observe a lot by watching.
If the people don't want to come out to the ballpark, nobody's going to stop them.
Never answer an anonymous letter.
We made too many wrong mistakes.
A nickel ain't worth a dime anymore.
Naturally, the question is, how much of this is falsely attributed to him. I don't know. He has published a book called the "The Yogi Book" that explains the stories behind his quote. I haven't read it. May be I should. But he himself answered that question best, by saying,
I didn't really say everything I said.



Monday, January 20, 2014

Euclid's Window



Book Review : Euclid’s Window
Author : Leonard Mlodinow
My Rating : 4 out of 5

The complete title of the book is “Euclid's Window: The Story of Geometry from Parallel Lines to Hyperspace”.

Geometry is a very special subject. It’s one of the oldest branches of knowledge - we started studying it to solve real life problems related to land and measurements. There is an even more important reason for calling it a special subject. That reason is Euclid, one of the most revered figures in Mathematics. He created an edifice for Geometry, whose schematic has been used to organize all mathematical knowledge.

His approach is irresistibly beautiful. At the core are the axioms, the self evident truths about the topic. Using these, and basic laws of logical reasoning, we prove simple theorems. Then we use these simple theorems to prove more complex theorems, and so on. This approach is at the foundation of modern mathematics.

Naturally, the book starts with Euclid and the Greek mathematicians. We proceed to Descartes who gave us the first main enhancement, what we now call Cartesian Geometry. If you have read many books on popular science/math, then some of the material so far will be a repetition for you. It’s still well written.

Then the author moves on to non-Euclidean geometry and the book becomes very interesting. Let me take a detour and give an idea as to what is non-Euclidean geometry.

Note that, in Euclid’s scheme, everything is built on a few trivial self-evident truths, called axioms. There is no way to prove them, but everything else is proven using them. If you change an axiom, you get a very different theory. This is not a random act. The only reason to change an axiom would be if it doesn’t feel as a self-evident truth.

Euclid’s 5th and last axiom roughly (very roughly) states that in a plane, 2 parallel lines do not meet if extended forever. It is not trivial as first 4 axioms. Compare it with the absolute simplicity of the 4th axiom which states that “all right angles are equal to one another”. The 5th axiom, often called as “The Parallel Postulate” has never appeared to be self-evident to mathematicians. Its history and surrounding controversy is a big topic in itself.

The Parallel Postulate reflects our intuitive idea about space. We mentally extend two parallel lines on a plain paper to infinity, and feel that they will never meet each other. But how do we know that space will indeed behave this way at astronomical distances? This is an important and interesting topic that ties mathematics with physics at a fundamental level. Author Leonard Mlodinow does a great job at explaining this in a very accessible and entertaining way. What he is telling is more a story of our understanding of space than a story of Geometry, but that’s a minor complaint against the title of the book.

The author explains how it was not easy challenging Euclid. Gauss did not publish any of his ideas because of the fear of backlash. Others were bolder, and persisted. Eventually these ideas were accepted as valid for Mathematics. But is their any real value in these competing geometries? Or is this just a mathematical curiosity? After all, given a line and a point outside that line, we really cannot draw 2 distinct lines that are in the same plane and are parallel to the original line. So why care about non-Euclidean geometry?

The answer, as we know now, came via Einstein. His work on the General Theory of Relativity proved that space is not Euclidean. You can really construct a triangle in space whose angles total to more than 180 degrees. This is one of the many seemingly bizarre, counter-intuitive ideas that have been brought to us by the 20th century. Here, the author focuses more on how our understanding of space changed with the theory of relativity, and less on other paradoxical aspects of the theory and justifiably so.

The last segment in the book is about how String Theory is changing that understanding even more radically, with its 10+ spatial dimensions. That’s another challenging task, and again I think the author did a great job.

I have to add a note on the style. Leonard Mlodinow has a peculiar sense of humor. I enjoyed his witty remarks throughout the book. He also tries to illustrate some points by creating scenes involving two brothers, most likely his sons, if I remember correctly. I was mildly annoyed by these examples. These two aspects of the book might irritate some readers.With these caveats I definitely recommend this book. This is not a mathematical textbook, it’s more a history. The reader is not expected to be a math graduate, but just a curious individual. So go for it.

Monday, December 16, 2013

Safe House



Movie Review : Safe House
Director : Daniel Espinosa
Genre : Action / Mystery
Starring : Denzel Washington, Ryan Reynolds, Brendan Gleeson, Vera Farmiga
Released : February 2012
My Rating : 4 out of 10

I generally like action movies featuring secret agents, spies, special forces and what have you. I do not expect much realism. Let there be convenient coincidences and unbelievable twists. Let the protagonists have super human skills. Just don’t give me time to think and keep me glued. For example, that’s what movies like Taken and Bourne movies did. Alas, it’s much harder to use that formula and there are many more flops than successes.

Safe House has the right although generic idea consisting of three main elements. First, a rogue agent, Tobin Frost (Denzel Washington), once an elite, now a legend. He has resurfaced and is in possession of secrets that he plans to use for blackmail. Second, a young aspiring agent Matt Weston (Ryan Reynolds) who is trying to prove himself. He unexpectedly finds himself in a tricky situation of trying to outsmart Frost. Third and last, a mole high up in the command chain that knows every move these two are going to make.

It’s starts off well. Weston is stuck in a claustrophobic job of maintaining a safe house. He clearly is not prepared for these complications. Before he even gets a chance to comprehend the situation, he is a target of well trained mercenaries who are more well informed than he is. It builds up an interesting foundation.

That should lead to a movie that just breezes through 90-100 minutes of fast paced scenes, witty dialogues and some double crosses thrown in for good measure. It should, but it doesn’t. There is a lot of running around and lot of chasing that doesn’t really go anywhere. And there are a lot of gunshots and ambushes that fail to raise our heartbeat. Even at two hours, it feels way longer than needed. The suspense is beyond predictable. That’s not a the real shortcoming. The fact is. we just don’t care what it is when the movie ends.

The screenplay is repetitive and unimaginative. I have never been to Capetown, South Africa, but I am willing to bet there aren’t that many areas there, where you can have a shooting match without ever being noticed by anyone, let alone cops.

It seemed to me that most of the actors were aware of all the flaws. Hardly anyone tries to be believable, as if their heart is simply not in it. Except Ryan Reynolds, who tries too hard. But at least he tried. I cannot say that about Denzel Washington, who otherwise is a fine actor. The rest of the cast gets very little screen time anyways.

There are many better spy thrillers out there. My recommendation is to skip this one.

Sunday, December 1, 2013

My first song :-)

More than a year ago, I noticed that one of my blog articles is getting lot of hits. I wrote that article, ”How To Write Lyrics For Hindi Movies”, as a sarcastic take on the quality (or lack of it) of lyrics found in Hindi movies. It was written almost 20 years ago on a Usenet group, and I just archived it on my blog. The search engines don’t have much sense of humor, so as you can see, this article appears at the top of search results! My apologies to those who were looking for real information.

That got me thinking. Why just lyrics? Why not compose a whole song? So here it is. A song written by me, tuned by me (!) and also sung by me :-) Don’t be afraid, read on.

First the lyrics.
agar maiN tum se yeh kahooN, mere dile mein hai too hi too
     mujhe hai bas teree hi aarazoo,
meree saaNso meiN hai too basee, aur manzil hai too meree
     ruh ko bhi hai teree justajoo

tere deedaar-e-ruKH-e-roshan binaa, zulmat-e-shab ho kaise fanaa
    gar haal-e-dil yeh kar duN main bayaaN
kya mere pyaar ko apnaaogi, ya rooth ke thukaraaogi
   kya hogaa tumhaaraa faisalaa

o meri jaan, o meri jaan
tere bin main kaise rahooN mujhe na KHabar hain na pataa
o meri jaan, o meri jaan
kuchh to kaho, yuN chup naa raho, ab aur naa lo imtihaaN
If you are feeling adventurous enough, you can listen to me singing it.



Now some clarifications. I have no illusion of being any artist. I am no singer, no lyricist and no composer. This is just a bit of fun. The lyrics are indeed written by me, and yes, I am the one singing it, if at all it can be called singing.

But the tune is not mine. It’s from one of my favorite Country songs, I told you so.

That’s the point of this exercise. If you are willing to plagiarize a tune, it’s extremely easy to come up with “your” song. The original lyrics give you an idea on where to start. The ready made tune provides a nice rhythm so that you can write fluid lyrics without having to worry about mundane stuff like meter ;-). In a couple of hours, you have a “new” song ready. No hard work required.

Maybe even more clarifications are needed. I am not advocating theft. Plagiarism is bad. It’s indefensible. Arguments such as “paying tribute”, “borrowing ideas”, or “making it more popular” are all flimsy, and wrong. I am just trying to illustrate how easy it is to plagiarize.

Monday, October 28, 2013

Calculating Integer Partitions

This post can serve as a nice interview question. Because some problems can be deceptively simple. Knowing the formula MAY NOT be enough to write an algorithm to compute it. Allow me to explain using the example of Integer Partitions. If you want the explanation on how this formula is derived, you can read it here.

To recap, Integer Partitions of a number, are ways the number can be expressed as sum of smaller numbers. And, P(N), the number of integer partitions of a positive integer N can be expressed as
P(N) = PP(N,1) = PP(N-1, 1) + PP(N, 2)
Where PP(N,k) is the number of partitions in which the smallest addend is at least k. And
PP(N,k) = 0 if N < k
PP(N,k) = 1 if N = k
otherwise
PP(N,k) = PP(N-k,k) + PP(N,k+1)

Here is how it can serve as an interview question to test the programming skills. The “natural” recursive solution can be easily implemented as follows.

public static int recursivePP (int N, int k) {
    if ( N <= 0 ) return 0 ;
    if ( N < k ) return 0 ;
    if ( N == k ) return 1 ;
    return recursivePP(N-k, k) + recursivePP(N, k+1) ;
}

This is grossly inefficient. Because intermediate results are unnecessarily computed multiple times. Every time the recursion reaches a particular pair (a,b) it will issue another recursion and calculate it all over again. So the code is natural, but not smart. It would take forever to compute say P(100) this way. What’s needed is a solution based on dynamic programming that builds P(i) as i goes from 1 to N. To do that we need to store the table of values for P(N,k).

Consider the following code.
public static long[][] PPvalues = new long[100][100] ;

public static long iterativePP (int N) {

    if ( N <= 0 ) return 0 ;

    // init P(N,k) for N=1, k=1
    PPvalues[1][1] = 1 ;

    for (int i = 1 ; i <= N ; i++) {
       
    // mark PP(N,k) where N == k
    PPvalues[i][i] = 1 ;

    for (int j = i-1 ; j > 0 ; j--) {

        long pp1 = ((i-j) < j) ? 0 : PPvalues[i-j][j] ;
        long pp2 = (i < (j+1)) ? 0 : PPvalues[i][j+1] ;
        PPvalues[i][j] = pp1 + pp2 ;

    } //
    } //

    return PPvalues[N][1] ;
}

Now this performs incredibly faster than the recursive solution. O(N^2) is not ideal, but it’s not bad either. This answer should usually be enough for an interview question.

Unfortunately, it’s not enough for finding out the value of P(N) for large values of N. The reason is the memory complexity of the algorithm which is also O(N^2), and our computers have a very finite memory.  For example, even with 8G of RAM I could not calculate the value of P(10000) because there is simply not enough memory to allocate the table.

That was a real bummer. There is no quick and easy way to optimize this to take less memory. Using a better data structure to store only half the table, as P(N,k) = 0 for N < k, of course won’t help much, only by a factor of 2.

One possibility is to compute only a section of the table at any given time. Note that the formula requires only the current column and the previous column, to calculate the value of any cell. You can start from last 2 (rightmost) columns, and keep computing the table leftwards. So you have to store only 2 columns (current and previous), thus significantly reducing memory. That’s a good optimization. The resulting code will be too complex for an interview question though.

Fortunately, there is a better formula for coming up with an algorithm to calculate integer partitions. It is based on pentagonal numbers. But that’s a math question, not a programming question. I will explain that in another blog post.

Monday, October 14, 2013

Boardwalk Empire

Review : Boardwalk Empire
Aired on HBO (2010, 2011, 2012, 2013)
My Rating : 8 out of 10

There was a time when I had no patience for spending many hours to watch a seemingly endless storyline of a TV series. There is always a worry that so much investment of time may not be worth it in the end. That has changed now due to the quality, as well as easy availability of the content. For a well made series, the length becomes an advantage, as characters and subplots can be fully developed, to make it a very satisfying viewing experience.

The pilot for Boardwalk Empire was directed by Martin Scorsese. It was heavily promoted and reportedly is the costliest pilot ever. It was fabulous, and I got totally hooked onto it. I have watched the first 3 seasons live, and this is a combined review for all.

It’s hard to give a concise synopsis of a story that so far has had 35 plus hours of screen-time, and it’s not even necessary. At its core, Boardwalk Empire is a gangster story. But it’s not just a long Irish version of Godfather. Stylistically it’s closer to Goodfellas. There is no one single plot here. The series revolves around ambitions and internal conflicts of every character punctuated by the ever changing alliances of convenience and double crossings.

The premise is loosely based on historical facts of prohibition era Atlantic City, and its powerful political boss of Irish origin Enoch Johnson, named Enoch “Nucky” Thompson here. Nucky (Steve Buscemi) has the complete control of the city - as the gangster boss, leader of the bootlegging operation, city treasurer and a socialite who throws lavish parties. As a help, his brother Eli (Shea Whigham) is the sheriff. A returned war veteran Jimmy Darmody (Michael Pitt) is Nucky’s lieutenant. Chalky White (Michael Kenneth Williams), leader of the local black gang, runs the bootlegging operation for Nucky. A federal agent Nelson Van Alden (Michael Shannon) comes to New Jersey to investigate the rampant violations related to sale of alcohol. Nucky meanwhile falls for the beautiful housewife Margaret (Kelly Macdonald). These are just the some of the main characters that live in the Atlantic City. There are others, from the Jewish gang of Arnold Rothstein (Michael Stuhlbarg) from New York, and the Italians from Chicago including a budding Al Capone (Stephen Graham).

The list of characters may seem rather large, but each one is fully developed. This character development, along with the superlative acting by each is reason enough to be glued to this series. But there are many other strengths. I can guarantee that you would be impressed by the smartness of the dialogues. How often do you pay attention to the music of a TV serial ? You will do that here. It is superb. The production is simply magnificent. It works quite well as a period drama too.

The central character is of course Nucky Thompson, played by Steve Buscemi, the only widely known actor in the entire cast. As an authoritative leader, Nucky is amoral but not irrational. Steve Buscemi brings out all the different shades of the character, and there are many. As the series progresses we learn more and more about him, and other characters. Every actor gives his or her best, and it’s hard to pick a favorite. I can assure you that you will like a few characters so much, that you would complain that they needed more screentime. Which ones, depends on you.

This is a great series but it’s not perfect. It suffers from the same trap every series suffers. The desire to extend it, and keep it running. That requires infusion of completely new characters, and some improbable turns. In spite of that, repetitiveness is unavoidable. In an ideal world, every good series will conclude at the right time. In this world, the temptation to squeeze more money out of the same formula trumps artistic integrity. I wasn’t happy with the 3rd season, for these exact reasons, although it was no less captivating. On the same note, I am perplexed about the current season 4. What more is left to be shown that can be called new?

I highly recommend watching this series. It feels like watching an Oscar calibre movie. I am obliged to include a strong warning. This is not for the faint of the heart. It’s about gangs, correctly rated as TV-MA. You should know what that means before you decide to watch it.

Tuesday, September 24, 2013

Kenya : Rural Images

This is my last post on the images from Kenya. I was ready to post this a few days ago, but decided to wait till the deplorable and horrible nightmare that was happening in Nairobi to be over. Having been to Kenya just three months ago and enjoyed the hospitality of the people there, my heart goes out to them. Truly sad.

So I am presenting these images without much commentary. Most of these were shot from a moving car, as we traveled through the rural areas to go from one wildlife area to another.


Last but not the least, some images from a bead factory we visited in in the outskirts of Nairobi. This factory employs mostly single mothers who make all the beads and related clay items, by hand.


 Previously :
Maasai Mara : Zebras and Wildebeest
Maasai Mara : Buffalo And Antelopes
Maasai Mara : Elephants And Monkey
Kenya : Giraffe, Hippo, Crocs and "Hakuna Matata"  

Monday, September 16, 2013

Kenya : Plants

Every place has unique flora and fauna. But when we mention Kenya, it's always the fauna that comes to our mind. Hardly anyone would think about the flora. I have tried to photograph some interesting plants, but I will be honest. Taking pictures of plants and flowers was not on my mind. I was focused on taking snaps of the abundant wildlife. Still once in a while something would catch my eye, and here it is.

You can click on any photo to start a slideshow.

The first tree that comes to mind at the mention of the the savannah is the iconic Acacia. They are everywhere.

Not just in the savannah.

But in the middle of farms as well.

Of course, Kenya is known for coffee. The beans on this are still not ripe yet.

Nothing but thorns!

Now some flowers. I do not know their names, sorry. If you know, please send a note, and I will update the post.
The next one is a very big flower.

The next one is one of the most common flowers. We saw it everywhere.

The purple flower shoots are coming up through a cactus.

The next one is also coming up through some cactus and thorny branches.

A shower of flowers !

The next is of course leaves arranged like a flower.


A pleasant surprise for me was the variety of cacti. I never thought I would be seeing so many different cacti. I love the cacti and succulents. Together as a species, they exhibit an amazing diversity of symmetries and geometry. I do not know names of most of them.

The first cactus is "candelabra spurge". It is really huge.

The resort at Lake Naivasha has a thicket of these with a paved pathway through these giants. The first one has a vine of purple flowers climbing on this cactus.


Now some cacti with flowers.

The most interesting plant for me was "golden showers". It has beautiful flowers, and the vine just spreads.


It can also climb a tall tree, and then you can see why it was named this way!


Wednesday, July 24, 2013

Maasai Mara : Lions and Cheetah

This is the last post related to animals in Kenya.

Like every tourist, I wanted to see a lion on my visit to Maasai Mara. The area has a good population of lions, supported by a couple of millions of herbivores. So there is always a good chance of seeing the feline predators - which includes lions, cheetah and a leopard.

We didn't see any leopard, as it is the shyest of the three. But the lions have gotten used to tourists, and boy, were we lucky or what!

First, photos of a Serval, a wild cat that gave us a fleeting view. It's hard to focus on a small animal that's hiding in tall grass, or running away from you :-( So apologies for these photos not being sharp.




I wish I had seen a cheetah sprinting behind a gazelle, but I had to be content with seeing one resting. It was about 50 feet away from us. Beautiful animal.

It was aware of us, but made no effort to move away.

The next photo is an unforgettable scene for me. Something that I have seen only in nature shows, and something I have dreamt of seeing.


A vast savannah, a predator waiting in the golden grass, looking at its food and thinking about how to make the move. The problem here was, the antelopes had noticed the lioness and the distance was too much. There was no scope for her catching them. The antelopes were aware of it, and kept on eating their grass, only to pause occasionally to make sure the lioness was not moving towards them. A common scene from the constant battle of life and death that goes on here.


The waiting game continued till we were there, giving me an opportunity to take some photos when the lioness turned her face towards us for some fleeting moments. That look can send shivers down your spine. It was good to be secure in the safari vehicle.
 
That lioness was less than 50 feet away from us, and I was thinking of it as the highlight of my visit to the Mara. I had no idea then that I would come even closer to another apex predator, a male lion, no less. This time the king and his queen were on a honeymoon. Really!


How close ? Take a look - we were much closer to the couple than those vehicles.


Then they got up and walked all the way to our vehicle. Literally just 5 feet away.



Fortunately, they were interested only in each other, and not in us.



They paid no attention to us, allowing me to take some more photos



That's one good looking but extremely scary animal.



That, was indeed the highlight of my trip!

This concludes the photos of animals. Next would be plants, and then some images of the rural Kenya.


 


Related Posts Plugin for WordPress, Blogger...