Pages

Sudoku Game implemented in Java


Project Euler, Python and Notepad++

I have taken an interest in Project Euler lately. This project presents a series of challenging mathematical or computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.

The next thing for me to consider was what is the programming language to use. I thought of C# initially but soon change my mind because it is too heavy weight. I decide to use something light weight and dynamic. With a desire to learn something new, I have made Python to be my choice.

Lately I have also upgraded my Notepad++ to 5.8.5. After the update, I looked at what are the latest plugins I could add on. I have found the Python Script plugin. To my delight, Python was also installed together with this plugin in my Notepad++ folder. So I got Python for free.

Next I have to figure out how to use this plugin. Actually, this plugin is not for general Python application development, it is more for Notepad++ automation using Python scripting. First and foremost, the Python Console is very important. To open the Python Console, click [Plugins], [Python Script] and [Show Console] as illustrated.


You can see from the above screen shot that it was Python 2.6.5. There are quite a few methods to run a Python script from the [Run] menu but what I am going to present here is a different method, running the script within the Python Console.

The Python Script plugin for Notepad++ comes with a few objects defined. One of them is the notepad object. The method getCurrentFilename() returns the full path name of the file being edited. Hence, we can use the command execfile() with notepad.getCurrentFilename() to accomplish what we want. In summary, enter the following command.
execfile(notepad.getCurrentFilename())

You only need to key in the command once. After this, you use the [Up Arrow] key to retrieve the previous command for execution.

The following is three solutions which I have come up for Problem 1.
# Add all the natural numbers below one thousand that are multiples of 3 or 5.

# imperative paradigm
def methodA():
    sum = 0
    for num in range(1000) :
       if num % 3 == 0 or num % 5 == 0:
          sum += num
    print sum

# pythonistic 
def methodB():
    print sum([x for x in range(1000) if x % 3 == 0 or x % 5 == 0])

# functional paradigm
def methodC():
    print sum(filter(lambda x: x % 3 == 0 or x % 5 == 0, range(1000)))
 
print "This is Project Euler Problem 1" 
methodA()
methodB()
methodC()

Bubble, Selection & Insertion Sorts Demonstration

// Bubble Sort
for (int outer = a.length - 1; outer > 0; outer--) {
   for (int inner = 0; inner < outer; inner++) {
      if (a[inner] > a[inner + 1]) { 
         int temp = a[inner + 1];
         a[inner + 1] = a[inner];
         a[inner] = temp;
      }
   }
}
// Selection Sort
for (int outer = a.length - 1; outer > 0; outer--) {
   int max = outer;
   for (int inner = 0; inner < outer; inner++) {
      if (a[inner] > a[max]) {
         max = inner;
      }
   }
   int temp = a[outer];
   a[outer] = a[max];
   a[max] = temp;
}
// Insertion Sort
for (int outer = 1; outer < a.length; outer++) {
   int temp = a[outer];
   int inner = outer;
   while ((inner > 0) && a[inner - 1] > temp) {
      a[inner] = a[inner - 1];
      inner--;
   }
   a[inner] = temp;
}

A Dive Into Hangzhou - Part 2

The original tour plan was DIY. However, we were enticed by a 1-day package that the travel agency at Friendship Hotel was offering at RMB175 that covered a number of attractions. Oh well, we convinced ourselves, we've been travelling around freestyle for a number of days and are starting to get worn out. So how about a break and let others take care of the logistics, drive us around and give a running commentary to boot? 8am to 5pm sounded like a very efficient schedule with all transport and admission taken care of -- we were sold on this proposition.

Because of the early start time of the tour, we had a rather rushed breakfast at the revolving restaurant on top of the Friendship Hotel. Nothing much was lost by way of the West Lake view, though, as it turned out to be an especially misty morning. "Thick mist over water" is the summary. The hearty and healthy breakfast spread made us happy. Then it's off to the day's adventure in Hangzhou!

First stop of the itinerary was the east shore of West Lake where the tourist boat was waiting to take us to the largest island in the lake. The jetty is near one of the top scenic/vantage areas around West Lake, called Orioles Singing in the Willows (柳浪聞鶯). King Qian, a good king to the people and filial son to his mother, reputedly planted the willows and brought in orioles for his mother to enjoy. Well, they are still there for the world's enjoyment today.


The boat quickly brought us to one of the islands on the lake, from which we viewed the famous 3 Pools Mirroring the Moon (三潭印月). If you have a RMB1 note, you can see this on its back. The guide said that once a year, at full moon in the 8th month of the lunar calendar, visitors can see 32 "moons" at this spot. How? There are 3 stone lantern-like structures rising from the lake. Each has 5 round windows through which candlelight shines out. When these lantern-like structures are lit once a year at Mid-Autumn, their windows glow, making 3 x 5 = 15 "moons". Their reflection in the lake adds 15 more "moons" to the count. Finally, the real (full) moon in the sky and its reflection in the lake caps the count at 32! How fascinating. Visitors crowd the lake annually to catch this sight.


Another ferry conveyed our group to the next destination on the east shore -- the Yue Fei Mausoleum. This is the burial place of the Southern Song dynasty general famed for his loyalty to his country. The well known Chinese song "Man Jiang Hong" was composed by him in captivity. Ironically, it was not the enemy who landed him in prison. Corrupt court officials and emperor Gaozong, whom he served, were responsible for the wicked deed. He died a prisoner, falsely accused of treason, in his own country. Centuries later, people still throng his mausoleum in admiration of a dynasty's hero. Tour guides still tell the story of national governance gone very wrong. But visitors are now discouraged from spitting on the iron statues of his betrayers kneeling across his tomb.

The coach took us around some other tourist spots in Hangzhou, with the predictable mix of commerce with strident promotions of Hangzhou silk and West Lake green tea. It was said that the cheongsams worn by the lady presenters at the Beijing Olympics were Hangzhou silk and Suzhou embroidery. And Hangzhou West Lake Dragon's Well green tea is reputedly one of the very highest grade of tea in China.


We ended a long day with dinner at a local restaurant near the lake. The concept is quite novel. We pay for food tickets first at a counter near the entrance and use these to make food and beverage purchases from different counters inside the restaurant. Any remaining food tickets can be exchanged for cash back at the exit. We tried a local dish, Cat's Ears. No, it was not some exotic meat dish. On the contrary, it was a tame soupy dish with flour bits shaped like tiny cat's ears (well they were small triangles with a dose of imagination) that actually tasted quite good in the cold weather.

After dinner, it was a short trot to the musical fountain at West Lake -- gracefully choreographed water jets with lights and music earned the awws of appreciation from visitors. In that relaxed mood, getting sprayed with water was fun for many standing there.

For us, we were happy to see Friendship Hotel towering beyond the edge of the lake where the musical fountain was. This meant that we were near a warm shower and comfortable bed, all of 20 minutes walk across a few streets. We could have been faster, but my Reeboks gave up (they were eventually left behind in Shanghai). The day's packed schedule was the final straw, I guess. Along the way back, we saw a handicapped man writing very beautiful calligraphy on the sidewalk in chalk. Glad he had some donations. But it is indeed hard for him to earn his keep this way, in the dust of road traffic. We have seen many sides of Hangzhou today.

A Dive Into Hangzhou

Hangzhou of the West Lake fame, we were finally here. This is also the part of the journey that we especially look forward to because of the nice Friendship Hotel with good online reviews. It took some effort dragging ourselves from our hotel room once we checked in, but out we go...

We were two hungry and cold people trawling the streets around our hotel for dinner. We saw some interesting things, like this typical small stall selling hot fried snacks (see pic), which the locals were buying. Interesting because it was Taiwan snacks sold in Hangzhou. Too tired to be adventurous, we settled for MacDonalds and were pleasantly surprised that the fish and beef in Hangzhou taste better than that back home.

A must-do, budget permitting, for visitors to Hangzhou is to catch the Impression: West Lake show which literally takes place over the West Lake. This we faithfully did on our first night, braving the cold. How thoughtful, the show organisers even rented out down jackets for RMB10 each. And even allocate the red ones for ladies and black ones for gentlemen. Coming from Zhang Yimou the critically acclaimed Chinese director (who did the opening and closing ceremonies of the Beijing Olympics 2008), the show is, unsurprisingly, spectacular. It's an understatement, I know. But you just have to be there to see it. The online clips can't give the whole experience of sitting open air at the edge of the West Lake, feeling the breeze, watching the light, sound and water play together on a natural stage as the actors do their thing.


What marred the show, through no fault of the show people, was a significant number of tourists who, seized with an inexplicable fear of being left behind by their tour group, started standing up and walking out in the last 5 minutes of the show. This, of course, blocked the view of the remaining weirdos who actually wanted to finish the show. This fear of being left behind mentality is quite chronic. We saw it in commuters at subway stations too. You know, those who somehow manage to barricade the entire exit for the alighting passengers and believe in different physical laws that if you block people from getting off a crowded train, you can still squeeze yourself into the train?

But back to the main story, we had an enjoyable, albeit freezing, evening at the lake and were very happy to find a cab in those rather remote parts. Looking forward to tomorrow!

A Dip Into Suzhou

We arrived in Suzhou just past 1pm and have less than 24 hours in the city.

The first direct encounter with Suzhou took place at the railway station, where lots of transport touts, map-sellers and beggars did their thing. We were glad that the "authorised" taxi queue moved fast and reached the hotel fairly quickly.

The Humble Administrator's Garden was our main destination this time round, and even the 1 1/2 hours we had before closing time was barely enough for us walk through the expansive grounds properly. The ticket price included an official guide who took us through the main sections of the garden by way of introduction. Thankfully, at least we had the guide's assistance to better appreciate the place, its history, design and interesting tidbits. A pity about the short time we had -- before coming I'd envisaged sitting around at various vantage points in the garden to contemplate the pictures of nature as its previous owners did. We'd need about 3 hours to get into that kind of contemplative mood!


Then it was a quick trishaw ride to Guan Qian Jie, the main pedestrian walking street in Suzhou where Starbucks and Haagen Dazs share the street with 100-year old stores. An evening bonus came in the form of a crepe outlet, from which I got a strawberry and banana crepe. Somehow, all the people buying crepes were girls!? After walking quite a while without getting a cab, we were very happy to board the right bus and stop at the right stop a stone's throw from our hotel.

There, our quick dip into Suzhou, and we're bussing out tomorrow.

First Date with Nanjing

When we arrived on Sunday night, it was cold and rainy. By the time we boarded the train to Suzhou on Wednesday, it was a fond farewell to Nanjing.

Since I've missed a few days, i'll be short on words and put in some pix to tell the tale :-)

First cold rainy night, we cabbed it to the Confucius Temple area, which has come a long (touristy) way from being an educational institution imparting Confucian teachings. The presence of many locals as well as tourist groups led by tour guides with loudhailers at that time of day confirmed that this is a "night" attraction. Interestingly, the cinema there was showing "Confucius" the movie starring Hong Kong star Chow Yun Fatt.


Monday morning was much better weather-wise. We finally saw the sun and made our way to the Purple Mountain. This was the last week of the International Plum Blossom Festival 2010. It's a breath of fresh air getting to highland away from the polluted city. However, a guide said that the plum blossom blooms were not as great this year; it rained the first two weeks of the month-long festival. And I thought the blossoms were wonderful already! At the Purple Mountain, one should also see the Ming Tomb of the first emperor of that dynasty and its Sacred Way (lined with stone statues of civil and warrior officials and various animals). This was the pioneer that influenced the layout of later Ming and Qing tombs found outside Beijing. We spent half a day there and barely visited half the attractions on Purple Mountain; one can imagine why the locals enjoy a leisurely summer day retreat to these environs.

After much exercise on Monday, we sought some muscular reprieve at the Presidential Palace in Nanjing city on Tuesday. The sunny weather bolstered our spirits after the wet welcome to this ancient capital to six dynasties a few days earlier. The Presidential Palace is a place for history lovers. It has been occupied by at least six noteworthy personages in their generation, all the way from Prince Han of the Ming dynasty, through to Sun Yat Sen, through to Chiang Kai Shek. Sun Yat Sen is held in very high esteem here, seeing as he is the "Father of modern China". There was a nice, educational exhibition dedicated to telling his story, with photos, English captions and some artefacts. There was more to see and savour slowly, but we had to rush through the sprawling grounds towards our next destination of the day.


Next after modern China history was a hark to the more distant past -- Zhonghua Gate of the Ming dynasty. This is a huge gate set within the southern city walls, the largest of its kind in China. In fact, during the first Ming emperor's reign, these city walls were the most extensive in the world. There are interesting details on the design and function of the gateways, citadels and portcullises. Were we seriously expecting muscular reprieve with this? I thought the hike up to the Ming Tomb the day before was the most strenuous on this trip. But the climb up the ramp to the top of the wall was another workout. I wonder about the horses who had to carry generals in full armour up the steep incline; they must be very strong animals!

Something New and Something Old in Shanghai

Finally, we are here again. Not before a red eye flight that merits an endurance medal, but we have finally landed in Shanghai. And made it through the metro without losing any of the three pieces of luggage despite jostling with commuters out on a Saturday morning. And reasoned in vain with the hotel reception why we should be charged only what the agent-issued travel voucher said, and not more, for turning up early. But, we are glad.


Amazingly, despite our sleep deprivation and general fatigue on the first day, we managed to sample a taste of the old and new at two unique Shanghai spots. (Well, not so amazingly, we ended the day with cup noodles in the hotel room because we were too tired and cold!)

The first is a restaurant called the Red House at Central HuaiHai Road, in the heart of the French Concession Red House Restaurant. Featured in a travel-cum-food programme on Singapore TV recently, my interest was piqued that the writer Eileen Chang and the opera singer Mei Lan Fang were associated with this historical eatery. It is literally red on the outside, and sits along a what-i-can-imagine-to-be-lovely-leafy-boulevard-once-the-green-returns-and-the-grey-sky-turns-blue. But today, it is cold and windy, and the bare branches look somewhat forlorn. The Red House, too, has seen better days. There seems to be a certain dignity in accepting that it wasn't what it used to be and bravely adapt as best as it can. It banks on nostalgia now. And there is a market for it, so it seems.


There was a steady stream of patrons flowing in all the time we were there. Perhaps they liked the service, as we did. Or the ambience, as we also did. And of course the food, it beat any Western food we had eaten in Singapore in the same price range. If we could drift into satisfied slumber there and then, we would (well, almost did) -- but TaiKang Road beckons...


There is still a working wet market at TaiKang Road in the French Concession. Neighbour to a flourishing art district. There are people buying and selling fresh meat, seasonal vegetables, artsy photographs and curious sculptures in one locality. The art district itself is a maze of alleys, where converted traditional residential houses showcase artistic talent. Some turns actually lead you to the backdoor to real homes, laundry and all. It was quite amazing that a cluster of old, weathered houses has been revived into a thriving and throbbing centre of activity. Tellingly, both locals and tourists descend on this charming spot; friends meet for tea, shop for gifts, shutterbugs point and shoot; tourists get a bite of history and then a drink of beer. Even getting lost in the labyrinth can be delightful.

But then the wind chill bitterly reminded us how underdressed we wear, and it was time to head back to the hotel for shelter. Did I mention that the camera acted up like a cold car engine? Hope the weather gets warmer. Take care!