Friday, April 30, 2010

Reverse a string

Question

Write code to reverse a string in its place.

Answer

[ This basically means, that we cannot allocate extra memory for the reversed string and have to return it back in the same memory ]

To reverse a string in its place, we'll have to swap the 1st character with the nth character, then the 2nd character with the (n - 1)th character and so on ...


Corollary Question

Reverse the string in its place, without using a temporary variable.

Answer

The logic for this comes from the simple swapping technique that does not use a temporary variable.


Using the above logic we can re-write our function to reverse the string as below

Thursday, April 29, 2010

Find the box containing 9 grams gold coin

Puzzle : 


Update : This puzzle is solved now

There are 5 boxes. Each box contains 10 gold coins. 
4 of the boxes contain gold coins weighing 10 grams each. 
One of the box contains gold coins that weigh 9 grams each. 
You are allowed to open the boxes if needed. 
But, the gold coins are completely identical and the difference in their weight cannot be identified by the naked eye. 
You are given a digital weighing machine.

Find out the box that contains the 9 grams gold coins by using the weigh only once.

Solution : 


Lets label the 5 boxes as A,B,C,D and E


Now pick 1 gold coin from box A, 2 from box B, 3 from box C, 4 from box D and 5 from box E
Keep them on the weighing machine and find out the total weight.
If all the boxes contained gold coins that weighed 10 grams each, then the weight would be :

10 + 20 + 30 + 40 + 50 = 150 grams.

But, since one box contains all the gold coins weighing 9 grams, based on the box that contains this defective gold coin the measured weight would vary.

If box A contained the 9 gram gold coins, the measured weight would be :

9 + 20 + 30 + 40 + 50 = 149 grams.

Following the same logic, based on the single measured weight we can identify the box that contains 9 grams gold coin as below :

If measured weight is 149 grams, then the 9 gram gold coin is in box A.
If measured weight is 148 grams, then the 9 gram gold coin is in box B.
If measured weight is 147 grams, then the 9 gram gold coin is in box C.
If measured weight is 146 grams, then the 9 gram gold coin is in box D.
If measured weight is 145 grams, then the 9 gram gold coin is in box E.

Thursday, April 15, 2010

Introduction

Have been thinking of trying out the new Blogger templates since quite a while now. Got some time now and thought of creating this new blog, where I would be posting all the interesting FAQs and various questions, some with answers, some seeking answers :)

Lets see how far I can go with posts on this new blog of mine.