Sunday, October 11, 2009

Objective C - Towers of Hanoi

So I was playing around with Objective-C. Got an idea of the basic syntax of the language, setup the GNUStep environment to compile objective-c code without a MAC and wrote the following tutorial. Still not close to IPhone development yet, the problem is though that it is difficult to do without a MacOS. Or, maybe I'll use the toolchain with iphone 2 sdk, but then, that will be outdated.

This is a short tutorial on implementation of Towers of Hanoi in Objective-C. Of course, there is not much to implement in the algorithm itself, the code is useful to give some nitty-gritty of objective-c syntax and coding methodoloy.

The code is available for free download. Please link back and use as desired.

Problem Description:

Read more about the "Towers of Hanoi" problem on wikipedia here. Short description (borrowed from wikipedia for completeness of tutorial):
http://upload.wikimedia.org/wikipedia/commons/6/60/Tower_of_Hanoi_4.gif
The puzzle starts with the disks neatly stacked in order of size on one rod, the smallest at the top, thus making a conical shape.

The objective of the puzzle is to move the entire stack to another rod, obeying the following rules:

  • Only one disk may be moved at a time.
  • Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod.
  • No disk may be placed on top of a smaller disk.
Algorithm Solution:

The solution to the problem involves recursion. Let's say there are n disks and three pegs numbered 1, 2, 3. Further, assume that initially all the disks are stacked on Peg #1 and the goal is to move all the disks on Peg #3. This can be achieved by moving n-1 disks to Peg #2 and then moving the last disk to Peg #3. After this n-1 disks can be moved from Peg #2 to Peg #3. We have to use the same algorithm for (n-1) disks until we reach n=1 (disk) for which the solution is simply to move from Peg #1 to Peg #3.

Here is the pseudo-code for solving the problem:
def Hanoi(PegFrom, PegTo, PegVia, numDisks):
if numDisks == 1:
print 'Move the disk from', PegFrom, 'to', PegTo
else:
Hanoi(PegFrom, PegVia, PegTo, numDisks - 1)
Hanoi(PegFrom, PegTo, PegVia, 1)
Hanoi(PegVia, PegTo, PegFrom, numDisks - 1)

where
numDisk = number of disks,
PegFrom = labeled Peg from which the disks will be moved,
PegTo = label Peg to which the disks will be moved,
PegVia = the third peg which is used to help the transition.

Objective-C Implementation:

This code has been tested on GNUStep but should work on XCode/Cocoa framework too.

For a short tutorial to Objective-C read here.

Lets get started. First you'll need GNUStep installed or XCode (for Mac users).

On Ubuntu linux, this is straight forward by the following command: sudo apt-get install gnustep gnustep-devel gnustep-games

To check whether GNUStep is successfully installed, execute the following command: gnustep-config --variable=GNUSTEP_MAKEFILES,
the output should give you the location of GNUstep/Makefiles directory e.g. /usr/share/GNUstep/Makefiles.

At this point you are ready to write code. Please create all the following files mentioned below in the same directory or ensure proper path linkages if that is not going to be the case. The entire source code package can be downloaded here.

The Interface:

Create a file named TowersOfHanoi.h and put the following code in it:

//Filename: TowersOfHanoi.h
//Author: Vinod Shukla

#import


@interface TowersOfHanoi: NSObject {
int pegFrom;
int pegTo;
int pegVia;
int numDisks;
}

-(void) setPegFrom: (int) from andSetPegTo: (int) to andSetPegVia: (int) via andSetNumDisks: (int) disks;
-(void) movePegFrom: (int) from andMovePegTo: (int) to andMovePegVia: (int) via andWithNumDisks: (int) disks;
@end

Explanation of the code:
  • Create of TowersOfHanoi object which extends the NSObject.
  • Define the instance variables.
  • Create setters.
  • Create the move peg function.

The Implementation:

Create a file named TowersOfHanoi.m and put the following code in it:

//FileName: TowersOfHanoi.m
//Author: Vinod Shukla
#import "TowersOfHanoi.h"
@implementation TowersOfHanoi

-(void) setPegFrom: (int) from andSetPegTo: (int) to andSetPegVia: (int) via andSetNumDisks: (int) disks {
pegFrom = from;
pegTo = to;
pegVia = via;
numDisks = disks;
}

-(void) movePegFrom: (int) from andMovePegTo: (int) to andMovePegVia: (int) via andWithNumDisks: (int) disks {
if (disks == 1) {
printf("Move disk from pole %i to pole %i", from, to);
printf("\n");
} else {
[self movePegFrom: from andMovePegTo: via andMovePegVia: to andWithNumDisks: disks-1];
[self movePegFrom: from andMovePegTo: to andMovePegVia: via andWithNumDisks: 1];
[self movePegFrom: via andMovePegTo: to andMovePegVia: from andWithNumDisks: disks-1];
}
}
@end

Explanation of the code:
  • Implement the setter function.
  • Implement the recursive algorithm for moving the disks. Notice the self keyword which is akin to this in Java and C++. We are calling the function recursively with n-1 disks.
Thus we have successfully written the code to solve Towers of Hanoi in Objective-C.

A Test Harness:

Let's create a main method to test our implemenation above. Create a file named TowersTest.m and put the following code in it.

//FileName: TowersTest.m
//Author: Vinod Shukla
#import
#import "TowersOfHanoi.h"

int main( int argc, const char *argv[] ) {
TowersOfHanoi *tower = [[TowersOfHanoi alloc] init];

int from = 1;
int to = 3;
int via = 2;
int disks = 3;

[tower setPegFrom: from andSetPegTo: to andSetPegVia: via andSetNumDisks: disks];

[tower movePegFrom: from andMovePegTo: to andMovePegVia: via andWithNumDisks: disks];

return 0;
}

The code above solves the case of three disks to be moved from Peg 1 to Peg 3. You can increases disks = any positive number n to tests for n disks.

Makefile:

A simple makefile to compile and run the above code. Create a file called GNUmakefile and put the following snippet:

#FileName: GNUmakefile
#Borrowed from: http://www.gnustep.it/nicola/Tutorials/WritingMakefiles/node2.html
include $(GNUSTEP_MAKEFILES)/common.make

TOOL_NAME = TowersTest
TowersTest_OBJC_FILES = TowersOfHanoi.m TowersTest.m

include $(GNUSTEP_MAKEFILES)/tool.make

Install Script:

A one line utility script to generate the executables. You can also use the command line instead. Create a file called install.sh and copy the following:

#FileName: install.sh
make GNUSTEP_MAKEFILES=`gnustep-config --variable=GNUSTEP_MAKEFILES` install

Clean Script:

A one line utility script to clean up the executables directory. Command line can be used too. Create a file called install.sh and copy the following:

#FileName: clean.sh
make GNUSTEP_MAKEFILES=`gnustep-config --variable=GNUSTEP_MAKEFILES` clean

Additional Instructions:
  • Assuming your GNUstep is correctly setup, extract the attached TowersOfHanoi.tar.gz to any directory.
  • Make the install.sh and clean.sh scripts executable using chmod.
  • To compile the code, run ./install.sh from the TowersOfHanoi directory. This will generate a TowersOfHanoi/obj directory containing an executable TowersTest.
  • The output of the program is obtained by executing ./obj/TowersTest.

Links:

Wednesday, July 19, 2006

Government banning blog websites

A recent news curious enough to make it to BBC headlines has me shocked.
India is blocking some blog websites ... what kind of watchdog policy is that.. reminds me of Iran blocking orkut.. and some other countries like who use Internet filtering.
Don't know what to say... looks like an infringement on the fundamental rights!!!

Tuesday, July 04, 2006

World cup continued...

I am tempted to write again... in again a dramatic and unexpected turn... Germany (which I was at one point thinking would win the world cup ;) ) .. have lost to Italy... I was watching the game on my laptop.. but it didnt strike me to record the goals scored by Italy and post it on google video .. i guess i would do it for the next two games... however the first goal scored by Italy was really magnificent.. also the defence of the winners was commendable.

On a different and orthogonal note, this article A guide to Banaras published in The Hindu is worth reading and brought back some memories of Banaras to me :-).

P.S. If anybody gets the links to World cup semifinals and quarterfinals highlights videos, post it in the comments.

Sunday, July 02, 2006

World Cup Fever

I know I haven't updated my blog in like ages.. and all the while I havent been doing anything marvelous.. a bit busy on acads ;) (sounds good.. no details extended).. but havent cracked anything significant anyways. I guess the situation will continue to be like that for more than a month .. until I change my mind.. or may comment on the world cup :-).
Sometimes, I simply get lost about whats going on in the world nowadays.. and rely on my friends and roommates to update me.. other than that.. yes the world cup is going on interesting now... with a few surprises.. England and BRAZIL out of the game .. it was simply impressive how France outplayed Brazil. In my opinion Germany and France should reach the finals.. and we can expect an interesting finish to the world cup.. somehow I feel that Germany will clinch the world cup.. but i'm always up for surprises :P .. not as momentous a thing to keep my fingers crossed though.. all i can say is wait n watch.
Those who want to watch the world cup online and are not already aware of the TVUPlayer can download it and watch online streaming for free... otherwise TV is always there.

P.S. Best wishes to everyone for Canada day (July 1) and American Independence Day (July 4).

Friday, May 26, 2006

Don't aid spam...beware of the hoaxes!!!

Hello friends,

Some of you might have received my personal emails... informing u about the orkut hoax.. or some related hoaxes. Here I am putting up some common hoaxes / spam chain mails floating on the web, so if you get any such kind of emails.. plz. delete and ignore them instead of sending them to everbody or atleast 12 people or some related kind of crap. Below are listed some common hoaxes that I frequently see. Plz. dont believe these mails.. be rest assured that nothing untoward will happen just because u didnt forward some god's photo to 12 person.. a girl with some rare heart disease who is 5 years for the last 5 years will not be saved if you forward the mail .. u will get no free cellphone or dollars from microsoft.. ur orkut or yahoo account will not be deleted.. the list goes on.. I've tried to list below the format of common ones... readers are also encouraged to visit http://www.hoax-slayer.com/ for the latest scams and hoaxes.. thanks!!!

1. Orkut Deleting your account

------------------------------------------------
Important

Dear user because of sudden rush of people signing upto orkut is come

to an attention that we are vastly running out of resources so with in

a week any one who does not receive this scrap will be deleted of our

server . We know that you are still using this account We

want to find out which users are actually using their orkut accounts so

if you are using your then please send this scrap to every orkut user

that you can if u do not pass this scrap to anyone then we will delete

your account

Just follow these simple steps.
1. Click on the "Messages Tab" in your account.
2. Click on the "compose mail" option which is the last
one of the four icons you see together.
3. Select "all friends"
4. Cut and Paste this mail
5. Send it........

--------------------------------------------------
2. Rohypnol drug and permanent female infertility
--------------------------------------------------
A woman at a Gas nightclub (Mumbai) on Saturday night
was taken by 5 men,Who according to hospital and
police reports, gang raped her before

Dumping her at Bandstand Mumbai. Unable to remember
the events of the evening, tests later confirmed the
repeat rapes along with traces of rohypnol
http://www.4woman.gov/faq/rohypnol.htm in her
blood.

Rohypnol, date rape drug is an essentially a small
sterilization pill.

The drug is now being used by rapists at parties to
rape AND sterilize their victims. All they have to do
is drop it into the girl's drink. The girl can't
remember a thing the next morning, of all that had
Taken place the night before. Rohypnol, which
dissolves in drinks just as easily, is such that the
victim doesn't conceive from the rape and the rapist
needn't worry about having a paternity test
identifying him months later.

The Drug's affects ARE NOT TEMPORARY - they are
PERMANENT. Any female that takes it WILL NEVER BE
ABLE TO CONCEIVE. The weasels can get this drug from
anyone who is in the vet school or any university.
it's that easy, and Rohypnol is about to break out big

on campuses everywhere.

Believe it or not, there are even sites on the
Internet telling people how to use it. Please forward
this to everyone you know, especially girls.

Girls, becareful when you're out and don't leave your
drink unattended.

(added - Buy your own drinks, ensure bottles or cans

received are Unopened or sealed; don't even taste
someone else's drink)

There was already been a report in Singapore of girls
drink been Spiked by Rohypnol.

Please make the effort to forward this to everyone you

know.

For guys - Pls inform all your female friends and
relatives.

"Your life is God's gift to you. What you do for
others is your gift to God" I had been forwarded this
mail you SHOULD do the same
--------------------------------------------------
3. Some rare mail / file with rare virus.. which will completely destroy ur C drive
--------------------------------------------------
Please be extremely careful especially if using internet mail such as Yahoo, Hotmail, AOL and so on. This information arrived this morning from Microsoft and Norton. Please send it to everybody you know who accesses the Internet. You may receive an apparently harmless email with a Power Point presentation " Life is beautiful. pps ". If you receive it DO NOT OPEN THE FILE UNDER ANY CIRCUMSTANCES , and delete it immediately. if you open this file, a message will appear on your screen saying: " It is too late now, your life is no longer beautiful ", subsequently you will LOSE EVERYTHING IN YOUR PC and the person who sent it to you gain access to your name, e-mail and password. This is a new virus ! which started to circulate on Saturday afternoon WE NEED TO DO EVERYTHING POSSIBLE TO STOP THIS VIRUS. AOL has already confirmed the severity, and the antivirus Software's are not capable of destroying it. The virus has been created by a hacker who calls himself " life owner ". PLEASE MAKE A COPY OF THIS EMAIL TO ALL YOUR FRIENDS and PASS IT ON IMMEDIATELY.
--------------------------------------------------


4. A Rare God photo u need to send to atleast 12 people
--------------------------------------------------
I forgot the exact structure. .but its something like u will see a rare pic and are requested to send it to atleast 12 or some other number of people.. else something bad will happen to you.
--------------------------------------------------

5. Money from Microsoft
--------------------------------------------------
From: Sankhala, Suresh Singh
Sent: Monday, July 18, 2005 12:48 PM
Subject:
UK Requirement

Dear Friends,
Please do not take this for a junk letter. Bill Gates is sharing his fortune. If you ignore this you will repent later. Microsoft and AOL are now the largest Internet companies and in an effort to make sure that Internet Explorer remains the most widely used program, Microsoft and AOL are running an e-mail beta test.

When you forward this e-mail to friends, Microsoft can and will track it (if you are a Microsoft Windows user) for a two week time period.

For every person that you forward this e-mail to, Microsoft will pay you $245.00, for every person that you sent it to that forwards it on, Microsoft will pay you $243.00 and for every third person that receives it, you will be paid $241.00. Within two week! s, Microsoft will contact you for your address and then send you a cheque.

Regards.
Charles S. Bailey
General Manager Field Operations
1-800-842-2332 Ext. 1085 or 904-245-1085 or RNX 292-1085

Charles_Bailey@csx.com
--------------------------------------------------
Well the list could go on... but i think its intuitive as well.. so I'd request the readers to think a little before intentionally or unintentionally spamming ur friends.

thanks a lot!
-Vinod

Monday, May 08, 2006

Memoirs of a vaishya... (oops Geisha!)

This is a post long due... and might have lost its significance with a significant passage of time since the release of the movie... anyways, guess I'll give it a try and vent out some of my feelings and reactions!!!
Needless to say... the movie was well picturized and typecasted... had beautiful and artistic cinematography.. a bit different from the tastes of characterisitic bollywood cinema but still good. Of course, those who have seen might agree and the critiques might differ!
The definition of 'geisha' as stated in Merriam Webster online dictionary says "a Japanese girl or woman who is trained to provide entertaining and lighthearted company especially for a man or a group of men".. however those who have seen the movie know that this was not the case .. and this prompted me to write this piece.
We can draw similar parallel in the Indian society .. where there were women were supposed to entertain men in a gathering... (particularly, "tawaif" who were supposed to earn patronage and support by practise their art and not by prostituting themselves) .. however, whats supposed to be and whats true are different!
Interestingly, strikingly similar is the case with 'Geishas' who though supposed to practice art.. but occasionally are forced to do prostitution to eke out a living.
Now, a few doubts arise in my mind... one how is the situation in the two cases (there may be more in other societies which i am not aware of) similar.. is it because of a traditional male dominant society with the women being dependent for their needs and livelihood .. and being treated as material entities by the society? Secondly, parallels need to be cited in other societies .. otherwise it could mean a negative portrayal of Asian / mid-east / oriental cultures :-) .. and finally how come the names "vaishya" and "geisha" sound similar .. any more connection than a figure of speech?

P.S. Comments invited... and the movie is worth seeing!

Wednesday, May 03, 2006

A pillar collapsed...

Shocking as was the news of Pramod Mahajan being shot by his brother... it is distressing to know that Pramod Mahajan has unfortunately succumbed to bullet injuries... and India has lost a prominent politician.
Prominent figures and personalities may be granted a high grade security but who would suspect the evil snakes amongst the family?
Enraged!
-Vinod