Showing posts with label Interesting. Show all posts
Showing posts with label Interesting. Show all posts

Tuesday, April 17, 2012

Brilliant 8-phase multi-quine in ruby

Wikipedia defines quine as:
A quine is a computer program which takes no input and produces a copy of its own source code as its only output.
In layman terms, it is a program that when executed outputs itself. Like a C program outputting its own source code. Kleene's Recursion Theorem proves the existence of quines in any Turing Complete Language. Its a good exercise to write one in your favorite language. Its fascinating to see quines.

Today morning my friend Umesh showed me this brilliant piece of ruby code that behaves as a Multi-quine. Link to original post by its author. Here's a listing of the same:



Save it as "test.rb" and run the following shell script:
while true;
do
    clear
    ruby test.rb | tee test2.rb
    mv test2.rb test.rb
    sleep 1
done

You will be able to see the picture changing after every 1 second and returning back to the original after 8 seconds. Note that when you run test.rb, it produces the output which is used for the next iteration. The shell script code lines 4 and 5 runs the code and uses the output of the code to replace the original code.

After being amazed by the beauty of this piece of code, I am not trying to figure out how exactly does it achieve this result. Someday I will post the same code with indentations and explanations in this blog.

Friday, March 02, 2012

Demystifying bulk SMS sender name

With the high penetration of mobile phones, companies have started sending out automated sms. I have always wondered about the cryptic sender names. Careful observations about the sender name reveals:
  • all letters are in capitals
  • name format is **-******
    • the first two letters seem random
    • followed by an hyphen
    • followed by a six letter
  • last six letters seem to identify the sender name
    • for example presently, "SBIINB" represents SBI bank
  • sometimes the same sender can send some sms with different combinations of first two letters
    • SBI sends sms as "BX-SBIINB", "TD-SBIINB" etc.
Some researching in internet points out that my observations about the last six letters are correct. The first two letters before the hyphen represents service provider and the region from which it is sent. For the examples above:
  • "BX" = BSNL from Karnataka
  • "TD" = Tata from Delhi
View the official list of bulk sms codes in the NDNC website.

Tuesday, May 31, 2011

Follow links to land in Philosophy

A couple of days back, the a cartoon was posted on xkcd titled "Extended Mind". In the mouse-over text, Randall Munroe wrote the following:
Wikipedia trivia: if you take any article, click on the first link in the article text not in parentheses or italics, and then repeat, you will eventually end up at "Philosophy".
I decided to test this theory and indeed managed to land to Philosophy every time !! Here is a demo run for the same:

Snickers > Candy Bar > Cocoa Solids > Chocolate > Mexico > Federation > Sovereign State > State (policy) > Social Sciences > List of Academic Disciplines > Academia > Community > Interaction > Causality > Event > Philosophy

I would be very interested in knowing if somebody find some topic that does not eventually lead back to Philosophy.

PS: To verify this theory I wrote a small Python program which starts from a random page and then traverses the first links until it finds loop or reaches Philosophy (or some threshold # of hops, say 1000). It ran for one night and gave me this loop:

Republic of India > Official names of India > Names of the Republic of India in its official languages > Republic of India (loop)


Tuesday, February 15, 2011

Algorithm for finding square-root

It always intrigued me how one could find the square-root of a number. In school I was taught a digit-by-digit method to calculate square-root. I did implement it using BASIC in Std IX, but the solution did not seem elegant enough. By Std XI I had actually figured out the Bisection method by myself and used it to find any root of a number. This again was implemented in C++ (... and I still have the code !).

Then in my B.Sc. I was formally introduced to the Newton-Raphson method and I have been using that ever since. At about this time only a classmate told me of the logarithm based method, which (if Wikipedia is to be believed) is the method of choice for most implementation of sqrt().

Recently I have been going through the MIT open course, Structure and Interpretation of Computer Programs. While watching the original 1981 videos, I came across this brilliant algorithm which was supposedly invented by the Babylonians around 2000 years back. It is also often attributed to Heron of Alexandria, who was also a great inventor (the link to his biography in Wikipedia has a section on his inventions ... looks impressive to me).

Heron's Algorithm can be derived from the Newton-Raphson method and can be considered to be a special case of that. The brilliance however lies in the fact that it precedes Newton-Raphson by 1600+ years. The algorithm is very simple:
  1. Guess a solution for sqrt(x), say g
  2. Check whether the current value of guess is "good enough" (square roots can be irrational, so exact value is often not achievable)
  3. If the guess is not "good enough", compute the new guess by updating  g=(g+x/g)/2
  4. Go back to step 2
You know from my last post that I have recently been learning Python. So here is a python implementation of the above algorithm.

Once again, please let me know if you find any bugs in the implementation. I am a Python newbie and your suggestions can help me improve.

Saturday, February 12, 2011

My first Python program

I heard of Python in my final year of B.Tech. at CU. Since then I have tried many times to pick up the language. Unfortunately most of the efforts have not gone far mostly due to lack of a particular problem to attack.

This time however it went differently. First I came across this brilliant and simple way (Monte Carlo technique for computing Pi) to compute the value of Pi from some CS magazine that I ran across in Dept of CSA [1]. Then I wanted to implement it. Matlab and C would have been the perfect choice for writing this simple code, but I just had enough time for trying it out in Python.

Here is the result of that (after 50mins involving mostly Google and the Python website):


Maybe I could have improved the code a lot had I been an "evolved Python programmer". But I am pretty happy with the initial results that I got. The great thing is that with iteration count 100K or so the program almost always computes upto 3.14 correctly.

[1] Maybe Communications of the ACM, some issue of 2010, however the link given before also explains the same technique

Saturday, October 09, 2010

Bash Auto-Completion Trick

Most of us who use the bash shell in *nix environments, often find the Tab-key auto-completion to be a very helpful timesaver. But one of the main problems is that he feature is not adaptive, i.e. it does nothing to learn from my previous commands. For example in my home directory I have two folders: “picture” and “programming”. Usually there is no reason for me to traverse the “picture” folder using bash, I’d rather use nautilus for that. So when I type something like “cd p” and press Tab, I would ideally like to get “programming” rather than “picture”. What if we could somehow use the history of commands to help this auto-complete feature?

Here is a cool bash trick that I have been using for quite sometime. It helps me search the history of typed commands that begin with what I have typed so far. Here is the way to enable it in your system.

Edit the “~/.inputrc” file by appending the following lines to it and save it:

"\e[5~": history-search-backward
"\e[6~": history-search-forward

Note that the file “~/.inputrc” might not be present in your system, so in that case you will have to create it.

Now to use this feature, open a new instance of the shell and type something like “cd p” and press the PageUp and PageDown keys to search the history of commands that begin with “cd p” backwards or forwards and cycle through them.

Personally I find this quite a time saver. However note that the completion feature is not directory aware, so like in the previous example it might just give you the name of a directory that does not exist in your current path.

Wednesday, September 08, 2010

How to use Skydrive folders in Windows Explorer

I am a big fan of free online storage for my backups. So far Microsoft Skydrive seems to be the best one in terms of space. But the one thing which I hate about Skydrive is its incompatibility with any application. Ideally I would have liked to use the online folders as easily as my local folders. For example had the folder been openable in Explorer, then we could have used the “copy-paste” and “save in” features available for any local directory. Surely the latency would be higher, but at least there would be no need to do thing separately.

Anyways, here is a hack (not yet perfected but works so far) devised from various sources which allows anybody to mount his/her Skydrive folders in a local directory. This is formally called network mounting. The trick is simple enough for novice users too. Just follow the simple steps:

  1. Log-in to your sky-drive account from http://skydrive.live.com/
  2. Look into the address bar, you should see something like “https://cid-xxxxxxxxxxxxxxxx.skydrive.live.com/”, where the ‘x’s would be replaced by your unique customer-id. Copy the 16 characters of customer-id.
  3. Now open Notepad and do the following very carefully:
    1. and paste this 16 characters
    2. Note down the name of the folder that you would like to mount, say “MyOwn”
    3. In notepad create this URL (without quotes): “\\docs.live.net@SSL\xxxxxxxxxxxxxxxx\MyOwn”, replace the ‘x’s by your unique 16 character customer-id and replace “MyOwn” by the folder name (as it appears in Skydrive) that you want to mount.
    4. If you are trying to mount the default folders “Public” or “Documents”, then you have to use “^2Public” and “^2 Documents” in place of “MyOwn”.
    5. Now copy the final URL that you made.
  4. Open Explorer
  5. On the left side-bar, right click on “Network”, and select “Map network drive”
  6. Paste the URL you copied from Notepad.
  7. Select a drive letter, preferably something at the end of the English alphabet like “Z”, and hit the “Finish” button.
  8. You would be asked for your Windows Live-ID and password, which you must provide.
  9. Voila, you can now see the contents of that drive inside explorer by going to the drive you selected.
  10. Now you can use this folder just like any other local hard-drive folders. Open files from this drive by double clicking, save files, cut-copy-paste files to and from this directory.

Try it out, I’m sure you will stop using the online version after using this trick.

Now, a word of caution. This is NOT an official method, so Microsoft does not give you any guarantees of any kind for this method to work. So one fine morning this method might just give a lot of errors and rendered ineffective. But till then (and I believe chances of that happening is quite slim), utilize this feature.

Lastly the file size restriction still applies (50Mb per file). So unless you are felling adventurous, do not try this out with files lager than 50Mb. Sadly this thing does not work for non-Microsoft OS (Linux, to be specific). If I get something working on Linux, I will post it here.

If you have any questions/recommendations please post it here. I usually reply within a day.

Saturday, June 05, 2010

Why India is still a Developing Country ... a short story

An Old Story:

The Ant works hard in the withering heat all summer building its house and laying up supplies for the winter. The Grasshopper thinks the Ant is a fool and laughs and dances and plays the summer away.

Come winter, the Ant is warm and well fed. The Grasshopper has no food or shelter so he dies out in the cold.

Indian Version:

The Ant works hard in the withering heat all summer building its house and laying up supplies for the winter. The Grasshopper thinks the Ant's a fool and laughs and dances and plays the summer away.

Come winter, the shivering Grasshopper calls a press conference and demands to know why the Ant should be allowed to be warm and well fed while others are cold and starving. NDTV, BBC, CNN show up to provide pictures of the shivering Grasshopper next to a video of the Ant in his comfortable home with a table filled with food.

The World is stunned by the sharp contrast. How can this be that this poor Grasshopper is allowed to suffer so?

Arundhati Roy stages a demonstration in front of the Ant's house.

Medha Patkar goes on a fast along with other Grasshoppers demanding that Grasshoppers be relocated to warmer climates during winter .

Mayawati states this as 'injustice' done on Minorities.

Amnesty International and Koffi Annan criticize the Indian Government for not upholding the fundamental rights of the Grasshopper.

The Internet is flooded with online petitions seeking support to the Grasshopper (many promising Heaven and Everlasting Peace for prompt support as against the wrath of God for non-compliance) .

Opposition MPs stage a walkout. Left parties call for ' Bengal Bandh' in West Bengal and Kerala demanding a Judicial Enquiry.

CPM in Kerala immediately passes a law preventing Ants from working hard in the heat so as to bring about equality of poverty among Ants and Grasshoppers.

Mamta Bannerji allocates one free coach to Grasshoppers on all Indian Railway Trains, aptly named as the 'Grasshopper Rath'.

Finally, the Judicial Committee drafts the ' Prevention of Terrorism Against Grasshoppers Act' [POTAGA], with effect from the beginning of the winter.

Kapil Sibbal makes 'Special Reservation ' for Grasshoppers in Educational Institutions & in Government Services.

The Ant is fined for failing to comply with POTAGA and having nothing left to pay his retroactive taxes, it’s home is confiscated by the Government and handed over to the Grasshopper in a ceremony covered by NDTV.

Arundhati Roy calls it ' A Triumph of Justice'.

Mamta calls it 'Socialistic Justice '.

CPM calls it the ' Revolutionary Resurgence of the Downtrodden '

Koffi Annan invites the Grasshopper to address the UN General Assembly.

Many years later ...

The Ant has since migrated to the US and set up a multi-billion dollar company in Silicon Valle. 100s of Grasshoppers still die of starvation despite reservation somewhere in India.

AND

As a result of loosing lot of hard working Ants and feeding the grasshoppers, India is still a developing country !

Last Words

Usually I stay away from publishing other people's contents on this blog. However, this post actually breaks the rule. The above is an email forward sent to me by my my uncle Dr. Tamal Deb. I do not know the original author, but the story made a lot of sense to me.


Saturday, March 13, 2010

Equations of words

I came across this blog recently. The author has managed to generate equations of words:
http://www.xamuel.com/inverse-graphing-calculator.php

Basically it generates equations which when plotted will generate the word that someone has typed. Unfortunately there is no way to verify it. The equation is by default in image format. On checking the "Raw Text" check-box, one can get the actual equation in text format that can be copy-pasted.  Unfortunately I could not copy-paste it to some plotter to plot it directly. Maybe I will try it out in Matlab someday and post the results here.

Here are some other articles that caught my attention in that blog:
Look up the website. The author is a Math teacher. His ideas seem to be quite interesting. Some of them matched with me quite a lot and created some sort of a resonance and made me like this person. Some other ideas got me thinking. The self-teacher piece is something that I find similarity with a lot. The swapping of signs was an interesting idea, it kind of reflects the consequence of standardization and protocols.

The computer simulation article was like straight out of Matrix trilogy. I have thought about this a lot, and its kind of weird. The mind says its impossible, but logically this could be a possibility. In 2001 Prof. Nick Bostrom published a paper with same title. You could read the paper and look into the website that the Prof has created.


Wednesday, March 03, 2010

SI Prefixes

Here is a list of SI Prefixes that I jotted down from the web today:
10^x Prefix
1 deca
2 hecto
3 kilo
6 mega
9 giga
12 tera
15 peta
18 exa
21 zetta
24 yotta
I was looking for the name of 10^15 and stumbled upon this list.

Wednesday, June 10, 2009

Leap Year checking

What is Leap Year?

The standard Gregorian Calendar that we follow in our daily life, has a leap year every four years. In such a year the month of February contains one extra day in order to keep the calendar year synchronized with the Astronomical Year. So the number of days in the month of February becomes 29 and the number of days in the leap year becomes 366.

The Rule

The full rule for checking a leap year is not very well known, and I often find many of my juniors and fellow pupils lacking the exact knowledge of the full rule. What most people know is that if the year is divisible by 4 then it is a leap year. But although this rule is good for nearly all practical purposes, it is not the full rule. The exact rule for finding out whether a year is leap year or not, is best described by a flowchart:

leap2

It was of course designed keeping the programmers in mind. But non programmers too, should not have much of a problem to understand the logic. Just to aid them, a%b denotes a mod b, which in simple terms mean the remainder obtained when a is divided by b. The numbers a and b are positive numbers only. The above diagram is technically called a flowchart.

Programming Language Construct

We can of course translate this to a programming language with the use of three if-then-else constructs. But there is an easier way of doing this as I will demonstrate:

Let us denote the three condition checks by three boolean variables, A, B and C (as shown beside flowchart). So the condition for leap year is:

AB’ + ABC
= A ( B’ + BC )
= A ( B’ + C )

The reduced boolean expression when expressed in C-like constructs become:

year%4==0 && (year%100!=0 || year%400==0)

Conclusion

What prompted me to write the article was the popular misconception to the rule and the ability to demonstrate the boolean reduction technique. The article took shape while I was trying to explain the rule to my brother Bikkhan for the the n-th time and decided to draw the flowchart to make matters easy for him. Lastly, I also figured out that this could be an excellent way of showing him the practical usage of boolean reductions that he has learnt in his Std XI curriculum, but never grasped the true significance of.

References

  1. To know more about Leap Year, Gregorian Calendar and Astronomical Year, just follow the links. You will also get an insight on the exact scientific reasons behind the rule.

  2. For a similar discussion and actual program in C language, consult the book “The C Programming Language”, 2nd Ed., by Brian Kernighan and Dennis Ritchie. They have given a similar construct along with a full program on date computation.

  3. For non-programmers reading this blog, here are some links on Boolean Algebra and Flowcharts.

Sunday, May 24, 2009

Trisecting an Angle

In mathematics the problem of trisecting an angle is a very interesting one. Perhaps more so, due to its seemingly impossible nature when compared to the similar problem of bisection of an angle which is easily achieved using compass and straightedge. Several literature have shown the problem to be impossible to solve using Euclidian geometric construction tools. However the problem is not impossible in nature. I have got a brilliant way of doing this using a very old technique originally attributed to Archimedes, the famous Greek mathematician.

The construction does not follow the Euclidean rules of construction which were used to prove its impossibility. However there is a bit out confusion about the rules themselves, as they are nowhere clearly mentioned in the writings of Euclid. However, most of the scholars agree on a set of rules apparent from the constructions described by Euclid. The following construction circumvents the rules, but does manage to trisect an angle accurately.

Archimedes’s method of Trisection of Angle

Let the angle to be trisected be AOB as shown in the figure. The trisected angle is PRA where 3xPRA = AOB (will be proved).

trisection_arch

The steps of construction:

  1. Using compass draw a circle with O as center. The intersection of the circle with OB is marked as P.

  2. Draw like PR intersecting the circle at Q, such that QR = OP, where the point R is collinear with O and A. This is achieved by marking the distance OP on the straightedge and aligning the markings with the like OA extended backwards. Although it may seem a difficult procedure, it is actually quite easy to do.

  3. Angle PRO is the trisected angle of AOB

Proof of Correctness

The proof is quite easy. I have put it down in a step by step way:

  1. OP = OQ, as P and Q are points on circumference and O is the center of the circle.

  2. triangle_POQ is isosceles, so angle_PQO = angle_QPO

  3. angle_QOP + angle_PQO + angle_QPO = 180
    => angle_QOP = 180 – 2*angle_QPO

  4. angle_RQO = 180 – angle_PQO = 180 – angle_QPO

  5. triangle_RQO is also isosceles as QR = OP = QO, so angle_QOR = angle_QRO

  6. angle_RQO + angle_QRO + angle_QOR = 180
    => 180 – angle_QPO + angle_QRO + angle_QOR = 180
    => angle_QRO + angle_QOR = angle_QPO
    => angle_QPO = 2*angle_QRO

  7. angle_AOB + angle_POR = 180
    => angle_AOB + angle_QOP + angle_QOR = 180
    => angle_AOB + (180 – 2*angle_QPO) + angle_QRO = 180
    => angle_AOB – 2*angle_QPO + angle_QRO = 0
    => angle_AOB – 2*(2*angle_QRO) + angle_QRO = 0
    => 3*angle_QRO = angle_AOB
    => angle_QRO = (1/3) * angle_AOB

  8. Hence we conclude that angle_QRO is the trisection of angle_AOB

So what is the catch?

There is no catch, the proof is indeed correct. In the beginning I have mentioned that the problem is impossible in nature, yet the proof that we showed is correct. The problem lies with the point 2 of the construction. The step required us to do a marking on the straightedge, which is not permissible in Euclidean constructions.

Bending the Rules !!

So you can actually intersect an angle after all, using the standard set of tools only. But the construction is not Euclidian. The interesting part is that this construction is quite old, but somehow this did not receive much publicity as the problem itself. Sometimes to solve a problem you have to bend the rules a bit.

Wednesday, March 11, 2009

Poems on IT Recession

The recent global economic meltdown has caused the IT Industry in India to suffer a setback. The effect has cascaded to the students who were seeking job opportunities in the Information Technology related domains. Here are a few poems that our friends at IT industry have written along the lines of a few famous poets’ creations. The poems are in Bengali, and in JPG format.

Sukanto Bhattacharya

IT_recession_Sukanto

Rabindranath Tagore

IT_recession_Rabindranath

Nazrul Islam

IT_recession_Nazrul

Jibonando Das

IT_recession_Jibonando

Its good to see that even in these tough times, people have not lost their sense of humor.

Tuesday, February 24, 2009

Weighing puzzle

This is one gem, that I got from a friend of mine. The puzzle in its simplest form goes like this:

There are a set of 8 balls. Out of which 7 are of same mass, and the remaining one is heavier than the rest. What is the minimum number of weighings required to find out the heavier ball? i.e. How many times do you require to use the balance?

My Method

I do not know what you would do, but what I did was to divide the balls first into groups of two groups of 4 balls, then take the heavier set, and divide it into two parts and so on. This yields an answer of 3. More precisely, the answer is:

log2nwhere n is the number of balls.

 

Actual Answer

However the actual answer is two weighings. The technique is to split the balls into three approximately equal groups, here we have 3,3,2. Then weigh the 3,3 groups against each other, if they are the same, then weigh the two remaining balls against one another. If one of the two 3,3 groups are heavier, then select that group and weigh any of the two balls against one another, if one is heavy, then you got the ball, if both are equal, then the third one of the group is the heavier.

So the correct expression is

log3nfor n balls.

 

Decision Tree

Here is a schematic diagram:

Decision Tree

Monday, February 09, 2009

GATE 2009 CS Solutions

There seems to be a lot of arguments over the GATE CS 2009 solutions. Here is my version of it. I have provided explanations and diagrams wherever I felt them necessary.

  1. A Follows directly from the definition of a Group.
  2. A A look at this figure should clear your doubts: Q2
  3. B I did this in the lame way, by drawing graphs. I am quite sure that it can be proved mathematically too. Something along the lines of "let all the vertices have dissimilar degrees", and then proof by contradiction.
  4. D Not symmetric as (x,y) is present but (y,x) is absent. Not anti-symmetric as (x,z) and (z,x) are both present.
  5. B This one was quite simple, just use base convert function of your calculator. Alternatively use the age old method of grouping the binary digits in groups of 3.
  6. B Draw the K-Map and group 0s taking 2 0s per group. You should get 2 such groups. Each group requires one NOR gate. Then these 2 groups, together will require another NOR gate. Formally it looks like: AB+C = (A+C)(B+C) = ( (A+C) (B+C) )'' = ( (A+C)' + (B+C)' )'
  7. C We need 256 Kbytes = 256 x 1024 x 8 bits. We have RAM chips of capacity 32 Kbits = 32 x 1024 bits. Dive the former by latter, and you arrive at 64 chips.
  8. C I do not remember where I read it from, but I guess its either in 8085 book by Gaonkar or in the Architecture book by Hayes. you can also try Mano's book.
  9. A Belady's anomaly is a typical (and very odd) feature of FIFO. Its explained nicely in Galvin.
  10. B Page frame numbers are most important. Virtual page numbers may not be stored entirely in the page table.
  11. A In each pass, there can be at most 1 swap. There are n such passes.
  12. B This is evident from the grammar itself. Just try generating some strings, if you feel otherwise.
  13. C* I am sure about the Q part. Q is true. But I have some confusion over the P part. P can be shown to be false for certain directed graphs. But from the general definition of Graph, directed is not to be assumed. So I hope P & Q both are true. personally I did not answer this question.
  14. C This is best explained by the set diagram (original diagram in the book of Algorithms by Horowitz & Sahani. Q14
  15. C This is again evident from the RE given. The string must have at least two 0s.
  16. D Some CFLs cannot be accepted by Deterministic PDAs. I got this from the book of Automata book of Hopcroft, Motwani and Ullman.
  17. B Check out the Dragon book (Compilers by Aho, Sethi, Ullman)
  18. B Just dry run the GATE_09_18.c program. Giving the steps would be laborious for me. In case you want to just see how it works, try running the program.
  19. C I do not know from which book this was given. Thankfully it was there in my SW Engg paper that I appeared for in 2008.
  20. B This was quite simple, you can apply Bayes Theorem, or just use the basic probability theorems.
  21. D Gold and Silver does not literally translate to "G(x) AND S(x)". it means that "All ornaments which are made of Gold or Silver are precious".
  22. B The function given the the table is P+Q'
  23. D
  24. B See the corresponding chapter on the book of Discrete Mathematics by Rosen.
  25. A Look at the transition diagram: Q27 State 00 means A=0 and B=0. State 11 has not been drawn as it cannot be reached from any other state. The smallest input satisfying the criterion is 101.
  26. B Q28_min Click to view the enlarged image.
  27. D 4 way set associative cache with 16 blocks imply that each set has 4 blocks numbered 0,1,2,3. We take each memory block and use the last 2 bits to place it into proper cache following LRU replacement scheme. 216 would not be in cache as it is followed by 8, 48, 32 and 92.
  28. B Initial position of head = 50. Nearest request is 34. The sequence of access would be: 50, 34, 20, 19, 15, 10, 7, 4, 2, 73
  29. C Consult the OS book by Deitel.
  30. A I is true. II is false, as it does not ensure fairness. III is false as there is no queue of sleeping processes.
  31. B This is the one and only reason for using multilevel paging. All other benefits are direct or indirect effects of this reason.
  32. B The equation is of the form: T(n) = T(n/3) + cn On solving this recurrence relation we get T(n) = Big_Theta (n log n) Without going into the details of the proof, let me give you something that wil explain it much more naturally. Just download GATE_09_CS_Q35.pdf, where I have shown the data plotted against various values of c {5,10,15,20,25} and n {1,3,9, ... 3^11}. Then I have plotted n*log(n,b_up) and n*log(n,b_dn) as the two lines that give the upper and lower bound for the series for some values of bases b_up and b_dn. Most importantly the nature of the curves are similar to that of type n*log(n).
  33. C Open addressing and linear probing results in table C. Just try it out in pencil and paper.
  34. B The minimum number of nodes required for an AVL tree of height h is given by, F(h) = F(h-1) + F(h-2) + 1, where F(0) = 1 and F(1) = 2. For the deduction of this expressions, look into the book by Kruse.
  35. D (a,c) cannot follow (b,c) as (a,c) < (b,c)
  36. B
  37. C This follows directly from the property of CFGs, where we see that CFGs are not closed under intersection, but produces CFGs when intersected with RLs. Even if you are not aware of this, just examine the languages L1 and L2. The intersection is given by (a^m)(b^m)c. This is obviously a CFG.
  38. C Try generating a few strings.
  39. B I is true for simple languages like assembly language of 8085. II is false, dynamic allocation is a must for implementing recursion. III is true as written in the Dragon book. IV is true.
  40. B Draw the dependency graph. S2 and S3 will have no cycles.
  41. A Maximum packet lifetime is 64s and the number of packets can range from 0 to 2^32-1 and the counter increments by 1 per millisecond. Thus the minimum permissible rate is 0.0149.
  42. C Look into any discussion on CRC. I read this from Forouzan.
  43. C I is true II is false, it is to be defined only in level 0 and 1 III is true IV is false, data stores cannot be connected between each other
  44. D All of the options are true. For I, look into the book of Jalote. others are true from the definition of Cyclomatic Complexity.
  45. C 400x2x10x63 + 16x63 + 29 = 505037
  46. C 16x63 + 31 = 1039
  47. C This is the Longest Common Subsequence problem.
  48. B Look into the above link.
  49. D B and C are clearly wrong. Amongst A and D, D is chosen as it also returns suppliers who have not supplied any part.
  50. B Follows from the dependencies and definitions of 3NF.
  51. D Let n be the number of frames. Then, 25e-3 = 100n / 1e6, which gives the value of n = 25. Thus we need ceiling (log 25 / log 2) = 5 bits.
  52. B Time taken to send 2^5 frames = 32. Time taken for the first fram to be acknowledged = 25x2. Thus waiting time = 50-32 = 18
  53. C Try constructing the max heap.
  54. D In case of the 1st deletion there is no problem. In case of the 2nd deletion, the tree loses its almost complete nature, thus we have to replace 8 in a proper place in order to retain this property.

The * mark indicates that I am not sure about the answer to that question. Please keep in mind that the answers may not be correct. These are what I believe to be correct. Most of them were computed by me, and some of them are from fellow GATE aspirants (mostly Sukanto).

If you believe that any of the answers are wrong, or cannot seem to follow the explanation that I have provided, please leave a comment here. I'll try to reply to all the questions.

Tuesday, December 30, 2008

Top 10 of 2008

As the year 2008 is set to end in a few days, various top 10 lists of 2008 are cropping up in the web around me. Here's a small list of the ones that I liked:

So long ... and thanks for all the fish !!

Saturday, November 01, 2008

Square Root of 3

I have never imagined that a poem could have the name "Square root of 3". So when a friend of mine forwarded me this gem, I was quite surprised. Moreover, this is a poem expressing love ! Have a read, and leave your comments. If you know the source of the work, please post it here.

Square Root of 3

I fear that I will always be
A lonely number like root three
A three is all that's good and right
Why must my three keep out of sight
Beneath a vicious square-root sign?
I wish instead I were a nine
For nine could thwart this evil trick
With just some quick arithmetic
I know I'll never see the sun
As 1.7321
Such is my reality
A sad irrationality
When, hark, just what is this I see?
Another square root of a three
Has quietly come waltzing by
Together now we multiply
To form a number we prefer
Rejoicing as an integer
We break free from our mortal bonds
And with a wave of magic wands
Our square-root signs become unglued
And love for me has been renewed

Monday, October 06, 2008

KND's game of 15

Kashi Nath Dey (KND) is a professor of University of Calcutta in the Department of Computer Science and Engineering. He teaches Artificial Intelligence (AI) to us. In his last class before the Puja Vacations, he showed us the following interesting game that he has invented. The game has no formal name, so I took the liberty of calling it "KND's game of 15".

The Game

This is a 2 person finite game with the following simple rules:

  1. 2 players take alternate turns in selecting a number from the set 1 to 9
  2. A number once selected, is not available for further selection
  3. If any 3 numbers from each player's selected number sets have a summation of 15 then that player is declared as winner
  4. Play continues, till any one of the player wins OR the number set is exhausted, in which case the game is declared to be a draw

As with any new game, we tried our hands at it in no time. Here are a few games that we played:

KND 2 6 8 1 W
Class 9 7 5    

 

 

 

KND won the game as 6+8+1 = 15. If you notice carefully, its very easy to see a pattern in KND's game. He started with 2 and then for every move made by class, he just put 15 minus the number. However, this is just a coincidence as we will see in the next game:

KND 8 2 4 9 W
Class 6 5 3    

 

 

 

This time too, KND won the game as 2+9+4 = 15. What is more important to note is that our last strategy was not what he had followed in this game. By this time our class mate Sumeet was convinced that whoever plays first would win, so in the next game, KND took the second move:

Class 5 8 7 9 D
KND 6 2 3 1 D

 

 

 

The game was a draw. So the player playing first does not always win. Somehow, I was feeling that there might be a strategy that allows the first player to win every time he plays.

My Analysis

The game is no doubt, very interesting. A careful study of it would soon reveal many facts which would help a lot in the gameplay. The first task in analyzing would be to jot down all such 3 number combinations which total in 15:

1 6 8
1 5 9
2 4 9
2 6 7
2 5 8
3 4 8
3 5 7
4 5 6

 

 

 

 

 

 

 

 

 

Next we do a simple frequency analysis and get the following result:

Number Frequency
1 2
2 3
3 2
4 3
5 4
6 3
7 2
8 3
9 2

 

 

 

 

 

 

 

 

 

 



I did both of these steps in class and arrived at the conclusion that 5 is the most frequently occurring number, so the player who chooses it first has a distinct advantage over the other. Next in priority were the set {2,4,6,8,} all of which have frequency of 3. Last comes the set {1,3,7,9}, all of which have the frequency of 2.

My Strategy

So I deduced a strategy that try and capture the numbers in that order, and then from the 2nd number onwards try to block your opponent's chance of winning by capturing the number that would get him a total of 15, and simultaneously look out for numbers that would get me a total of 15.

KND's Explanation

I used my newly formulated strategy to get a draw in the last match and was feeling quite happy with myself. Then, KND offered an alternate and much simpler explanation of the game. He first drew a 3x3 magic square:

8 1 6
3 5 7
4 9 2

 

 

 

 

As with any magic square this one also has a constant summation over rows, columns and major diagonals. In this case, the summation happens to be 15. Now what KND has done in this game is to merge it with popular children's game of Tic-Tac-Toe. So selecting a number implies putting a 0 or X in that position in this 3x3 board. What follows is a simple game of Tic-Tac-Toe.

Conclusion

The explanation is very elegant and simple. I liked it very much, both the game and the explanation behind it. It just shows how some apparently very different problems can be mapped in to one another. Interestingly, I knew all of the things that he required to explain the logic behind the game:

  • Magic Squares, and how to generate them. I even knew the 3x3 square by heart and managed to remembered that the constant was 15 !!
  • Tic-Tac-Toe

The key to arriving at the correct explanation is to think harder for simpler explanation. In fact looking back, it was easy to guess that there was some simple strategy as KND did not take much time to make his moves, which he would require if he followed my type of complicated strategy.

For the last few days I have showed this to some of my friends. With the same result, all of them tried to think of a complicated strategy. Sometimes I introduced a minor variation of showing the same thing with 9 playing cards, which makes it a card game.

Thursday, October 02, 2008

Primality of a Number is NP problem

Primality testing of a number is the method of finding out whether a number is prime or not. I have known this is a non-polynomial problem. In fact most of the recent cryptographic techniques rely on this and the factoring problem of numbers to create secure systems.

But it was never clear to me why. So when this question was put forward to me by Sukanta, I kept thinking. Of course I knew the answer, but did not know the reason for this problem to be NP. Sukanta explained that:

For a number N, the usual prime number testing strategies, iterate for N/2 times, which can be further optimized to N^0.5. So the number of division operations required was a polynomial function of N. At this point, it is very easy to say that this is polynomial solvable.

But the thing that I missed here, is that N was the number itself, not the size of the input set on which the complexity of a program is computed. So if we take the input size as the number of digits of N, then the size of input set is log N. So the complexity of the program is exponential, and not polynomial, as I mistook in last step.

Well, there is never any shortage of new things to learn. I thank Sukanta, who explained it in such a nice way. However, what astonished me was that I had believed the result without even asking for the explanation of the same. So I made a mental note to watch out for similar pitfalls in future.

MS Ads with Jerry Seinfeld

Here are two Microsoft Advertisements that featured American comedian Jerry Seinfeld, whom Microsoft hired and caused a lot of speculation. However, he has been recently axed from the campaign, leaving everybody wondering, what the Microsoft Advertisements guys are really upto.

 

 

I personally both of them, specially the way that they are showing Gates.