Wednesday, April 28, 2010

Binary Search Algorithm

Apparently, only 10 percent of programmers can correctly code the binary search algorithm. What follows is my attempt to prove once and for all that I belong to that select group of programmers! I implemented the algorithm in Excel VBA.
Option Explicit
'++++++++++++++++++++++++++++++++++++++++++++++++
' Author: Ram Limbu
' Date: 2010/04/28
' Description: Binary Search Algorithm in VBA
'++++++++++++++++++++++++++++++++++++++++++++++++

Sub BinaySearch()
Dim UpperLimit As Long
Dim LowerLimit As Long
Dim Mid As Long
Dim Val As Long
Dim NotFound As Boolean
Dim WS As Worksheet

On Error GoTo ErrRtn

'prompt user to enter the number to search
Val = InputBox("Please, enter the number to search")

'set WS to the first Worksheet
Set WS = ThisWorkbook.Worksheets(1)

NotFound = True
LowerLimit = 1

UpperLimit = WS.Cells(65536, 1).End(xlUp).Row

If UpperLimit = 1 And IsEmpty(WS.Cells(1, 1).Value) Then
MsgBox "The Column A on Worksheet1 is empty. Exiting ..."
Exit Sub
End If

While NotFound And LowerLimit <= UpperLimit
Mid = (LowerLimit + UpperLimit) \ 2 ' perform integer division
If Val = WS.Cells(Mid, 1) Then
NotFound = False
ElseIf Val < WS.Cells(Mid, 1) Then
UpperLimit = Mid - 1
Else
LowerLimit = Mid + 1
End If
Wend

If NotFound Then
MsgBox Val & " wasn't found"
Else
WS.Cells(Mid, 1).Select
MsgBox Val & " was found at row " & Mid
End If
Exit Sub
ErrRtn:
MsgBox Err.Description
End Sub

The assumptions are as follows: (1) The data set is pre-ordered and (2) located on Column A of the first Worksheet. To keep the code simple, no data validation is performed.

Monday, April 26, 2010

The Makings of Obama

The life story of President Barack Obama is too well-known to repeat here.  However, having just read his acclaimed memoir Dreams From My Father (1995), I just had to add my two cents' worth to the growing discipline of Obamalogy.

[caption id="attachment_303" align="alignright" width="220" caption="Young Obama with his (from left) grand father, mother and half-sister Maya in Hawaii early 1970s. Picture sourced from wikipedia"][/caption]

Written after becoming the first African American president of Harvard Law Review and years before he ran for his first political office, the book strikes readers with the honesty and poignancy of the voice of a young African American man searching for his place in the world.

Born in Hawaii to a white American mother and a black Kenyan father, the young Obama feels trapped between two worlds, and groans under the unbearable burden of the 'unique and universal' history of his people in the US.  He recounts the angst and sense of helplessness felt by himself and his black college friends in a world in which they feel the rules of the game have been written by somebody else and even their perceived identity foisted on them by others.

The search for his identity takes Obama to the ancestral land of his forefathers in a remote village in Kenya.  There, he learns the full story of his own absent father, who, despite being a brilliant Harvard scholar, died a broken man thanks to a combination of his naive idealism, incurable character flaws and ancient tribal grudges.

Obama largely won his presidency in 2008 on the back of his sublime oratory reminiscent of Abe Lincoln. His simple, direct prose is equally a joy to read.

Towards the end of the book, a female African history professor that Obama meets in Kenya tells him, "In the end, I'm less interested in a daughter who's authentically African than one who is authentically herself." I think there is a priceless lesson for all of us in this beautiful thought.

Friday, April 23, 2010

Remembering the Forgotten Soldiers of a Vanished Empire

It is that time of year again when Australians and New Zealanders remember their fallen war heroes and celebrate the veterans as part of the ANZAC Day festivities. It is an occasion when the self-sacrifice of the few are mourned and mythologized, and the values they fought for are cheered and cherished by the multitude. It is a day when the national fabric is examined, repaired and renewed in solemn ceremonies held across Australia, New Zealand and Gallipoli, Turkey.

On this occasion, I shall remember another group of heroes, second to none in valour, sacrifice, comaraderie and courage under fire, whose stories remain largely untold, who have been shoved into the shadows of history, who have been disowned by their own compatriots. I am talking about Gurkhas, the forgotten soldiers of a vanished empire.

A fortuitous by-product of the 19th century British imperial adventures in India, Gurkhas shared many commonalities with their ANZAC counterparts. Both Gurkhas and ANZACs, along with colonials such as Sikhs in India, fought in wars in which they had no discernible stakes. Both served masters whose chief interest in them lay in using them as shock troops to further their imperial gains. Both were heaped with soaring rhetorical bouquets but cast away thoughtlessly as soon as they outlived their usefulness. Both were used as political pawns by their respective leaders eager to please an empire where the sun never set.

The crucial difference between the Gurkhas and ANZACs lies in the way they were perceived and treated by their own countrymen. ANZACs were retrospectively elevated to the sacred rank of national heroes and living treasures. They formed the bedrock of their nation's founding myth. In the Australian national narrative, the new European settlers' claim to the Great Southern Land, whose original inhabitants were dispossessed, marginalized or killed after the European arrival in 1788, did not become legitimate until young Australians were mowed down by Ottoman Turkish machine guns on the shores of Gallipoli Peninsula in 1915. Such is the price exacted by the birth of a nation state.

Gurkhas occupied the opposite end of the national mythology spectrum. They were an unpleasant reminder of a humiliating defeat inflicted on Nepal by the British East India Company in the Anglo-Nepalese War (1814 to 1816). In a treaty that followed the war, Nepal was forced to cede one-third of its territory, put up with a British Resident in Kathmandu and permit the British East India Company to recruit Nepalese youth into its private army, effectively becoming a British client state. Such is the price exacted upon a nation that comes second best in a collision with a super power.

Furthermore, the British chose to recruit only from those Nepalese ethnic groups that it classified as the "martial races", which also happened to be the newly conquered peoples of Nepal by the Gorkha Kingdom. Hence, the Gorkha ruling elite had at least two reasons to banish Gurkhas from national consciousness and write them out of history books.

On this ANZAC Day this Sunday, when fresh wreaths are laid down and the Last Post sounded for the fallen ANZAC diggers, some of us whose stories are interleaved with those of the Gurkhas will mourn and pay homage to the memory of these forgotten soldiers of a vanished empire, whose exploits in Gallipoli matched and even outshone those of the ANZAC heroes.

Sunday, April 18, 2010

Miserere mei, Deus, or How Two Wunderkinds Foiled a Papal Conspiracy

The story has all the elements of Da Vinci Code minus the horrible murders: A powerful organization that wants to keep the lid on a sacred work it deems too painful for ordinary mortals to bear. An accomplished music composer and priest who sings in the Papal Chapel in Rome from the age of 9 until his death. A Pontiff who makes smoking tobacco an excommunicable offence, orders the most notorious persecution of a scientist in history and pillages the Partheon. An 18th century child prodigy who creates the first known bootleg copy of a piece of music. A 20th century boy with the voice of an angel who sings it into a global sensation. And the celebrated Old Testament King who starts it all.



Welcome to the enchanting world of Miserere mei, Deus, a late Renaissance work for choirs composed by the Italian priest Gregorio Allegri (1582 - 1652), who was an early candidate for the intriguing phenomenon known as the one hit wonder. Although Allegri composed many other works, he, like Pachelbel of Canon and Gigue in D fame, is today solely remembered for a single work, Miserere me, Deus, which is shrouded in secrecy, legend and mystery thanks in no small part to the Vatican.

Allegri was appointed to the Papal Choir in Rome during the reign of Pope Urban VIII (1568 - 1644), who was a scion of the important Florentine family of the Berberini. A great patron of the arts, the Pope earned future notoriety by coercing Galileo to recant his heliocentric theory of the solar system and looting the metal girders from the Partheon to manufacture canons, an act of unimaginable vandalism that prompted the jibe "What the barbarians did not do, the Berberini did".

In the subsequent years, the only place where Miserere could be heard was in the Sistine Chapel in Rome, where it was played during the Holy Week. Like modern-day pilgrims' visit to Google's headquarters in Mountain View, California, it became fashionable for 18th century artists, socialites and aristocrats on European Grand Tour to attend the performance of Miserere in the Papal Chapel and twitter about it in their diaries and letters back home.

Then, suddenly, in 1770,  Miserere became public property thanks to a precocious 14-year old boy named Mozart.  The visiting child prodigy from the Archbishopric of Salzburg listened to the performance of Miserere once, transcribed everything from memory, went back next day to listen to one more performance in order to make some corrections in his copy, and shared his booty with a visiting English traveler, composer and musicologist, Dr. Charles Burney. Dr. Burney published the score in 1771. The Vatican had no choice but to remove the ban and applaud the genius of history's first and most famous music bootlegger.

Some time in the late 19th century, a copyist's error crept into the score of Miserere, the so-called top C, which became part of the canonized version of the work as performed today. Many connoisseurs believe that this chance error actually served to enhance the beauty of the original score, in itself a contentious notion that has added to the work's enduring mystique.

Before the teenage Mozart blew the Vatican ban on Miserere, only three authorized copies of the score were reported to have been made and distributed outside the Vatican. One of the recipients of this papal favor, the Holy Roman Emperor Leopold I, is reported to have remonstrated with the Pontiff that the copy that he received did not match the score as performed in the Papal Chapel as the score was missing ornamentation. Ever since then, rumors and myths have circulated about secret ornamentation that were passed from performer to performer in the Papal Chapel but missing from many unadorned scores that floated around Europe.

The modern version of Miserere itself is an end product of many revisions and editing as the work crossed both temporal and spatial boundaries after its release from the gilded vaults of the Vatican.

It was another wunderkind, a 12 year old British boy named Roy Goodman who propelled Miserere into popular consciousness with his celebrated performance with the Choir of King's College in the March 1963 recording for Decca label. In a pleasing symmetry spanning a couple of centuries, the Renaissance polyphonic masterpiece set to Psalm 51, which was written by King David in a fit of repentance after his adulterous affair with Bathsheba, was finally introduced into the bazaar of popular culture by another daring youngster.

Roy Goodman, currently one of the world's most successful freelance conductors, was recently interviewed by Margaret Throsby on ABC Classic FM radio. You can listen to the interview here.

Saturday, April 10, 2010

Remembering Girija

Reading through some obits of late Girija Prasad Koirala (1925 - 2010) in the Nepalese media, it seems that in the eye of some commentators, Koirala managed to redeem himself somewhat in the final decade of his life. To begin with, he is praised for standing up to the then Nepalese King Gyanendra, who assumed absolute power in a short-sighted royal coup in 2002 that spelled the end of monarchy in Nepal. Koirala is also credited with persuading parliamentary parties to sign a 12-point agreement with Maoists in Delhi in 2005 that paved the way for the peace process that halted a decade-long armed Maoist insurgency.

The vast majority of the Nepalese people remained hostile to Koirala until the very end, however. Many were unmoved by the news of his death, openly expressing glee and hope that his death would herald a new dawn for Nepal. Others pointed out that even his practical rapproachment with the Maoists was motivated by what many consider to be the most serious blemish on his legacy: nepotism and self-aggrandizement. According to this interpretation, Koirala wanted to resurrect his political fortunes and dynastic ambitions by aligning himself with his erstwhile sworn foes, the Maoists.

Whatever one's opinions about Koirala, he was indisputably one of the most divisive, controversial and dominant political players in the post-1990 Nepal. His early political apprenticeship itself reads like that of a Mafioso enforcer. Living in the shadows of his illustrious older brother BP, who surely was the toughest act to follow in the Nepalese politics, Koirala did the dirty work for his party, the Nepalese Congress. Organizing Biratnanar Jute Mill workers to agitate against the autocratic Rana regime, smuggling weapons across the Nepal-India border to arm anti-Rana forces, hijacking a currency-laden Royal Nepal Airlines plane, printing counterfeit Indian Rupees and eliminating party rivals were all in the day's work for a young Koirala.

In his autobiography, BP, whose literary legacy might yet outshine and outlive his considerable political legacy, famously dismissed his younger brother GP as a party hawaldar or foot soldier, anointing his niece Sailaja as his political heir.

In the wake of the 1990 People's Movement that restored multi-party democracy in Nepal, Koirala emerged as an influential member of the powerful Nepalese Congress triumvirate along with Ganeshman Singh and Krishna Prasad Bhattarai. In the political chaos that followed, Koirala managed to sideline his two key party rivals amidst bitter public feuds, and did his best to undermine a short-lived government of Communist Party of Nepal (United Marxist Leninist). In the end, he surpassed his older brother BP's wildest dreams by becoming Prime Minister for five times on the back of his undoubted skills at mobilizing the party faithful.

As a reporter for The Kathmandu Post, I had occasion to cover many tedious ceremonies and functions in which Koirala cut ribbons and/or starred as the chief guest. One such occasion left an indelible mark on my mind.

The function was held at the Blue Star Hotel. Koirla was not holding any official position at the time - of course, nothing less than the Prime Minister's Office would have suited his ego - even though his party had formed the government. One of the senior ministers in the government, Bal Bahadur Rai, was also invited to the function.

Rai committed the unpardonable sin of arriving at the function after his party overlord Koirala, whose career was far from over despite appearances. As if to prove this point, a sanctimonious Koirala went on to give a very public dressing down to the embarrassed senior minister, scolding him like a mischievous school boy for arriving late at the "people's function". All that Minister Rai, who looked more like a dreamy, self-satisfied Abbot of a Buddhist monastery than a senior Nepali Congress leader and cabinet minister that he was, could do to counter the hypocritical and self-righteous tirade from his boss was to grin sheepishly and fold his hands together in a gesture of feigned humility and remorse.