Tuesday, May 11, 2010

Probability

Probability question: Persons A and B go shopping together. Say person A spent X amount of money and B Y. What is the probability that the sum total of their purchases [i.e. X+Y] has 0 cents [i.e. is a whole number]. ?

Answer : The person A can have cents in the range of 0 to 99, and same with the case B. Thus they have 100 cases each, and total number of cases is 100x100. Out of them the cases of our interest is (0, 0) (1,99), (2, 98), (3, 97) ... (99. 1) is 100. So the probability is 100/10000 = 1/100.

Count 45 minutes using rope

Given 2 non-uniform ropes (each burns down in 1hr, but not uniformly), how to measure 45 mins?

Answer : Take one rope connect both ends. Ignite the connection point and one end of the other rope at the same time. When the looped rope burns out, it is 30 mins. Then ignite the unburned end of the remaining rope. When the remaining rope burns out, it is another 15 mins. So it is 45 mins.

Three Orange Boxes

Three boxes, one with apples, one with oranges, one with a mix of apples and oranges, all the boxes are labeled incorrectly, you can pick up just one fruit. How do you tell which box has what fruit?

Answer : All the labels are incorrect, so pick a fruit from the box labeled mixed box. That will tell you if its the apple or orange box, because its not mixed. The other labels are also incorrect, so the box labeled with the fruit you picked will be the box containing just the other type of fruit. The remaining one will be the mixed box.The second box cant be mixed fruit box because then the third box will be labelled correct which is not the case 

Monday, May 10, 2010

where is volatile variables stored in memory layout ?

The storage of a variable is not decided based on if it is volatile or not. It can be anywhere as is the case with normal variable. So the variable may be on stack,heap or in the data section of executable, depending on how it gets defined. The volatile qualifier just tells the compiler that this variable may change in ways that are not apparent to you, it can be changed at any point of time, for example is hardware registers (variables mapped to h/w registers). So compiler disables any optimizations such as caching on this variable.

Volatile is type qualifier not a storage class specifier.

Find binary of a Number

Write a function to print the binary value of the number passed to it, and function should not use any variables other than the parameter passed to it.

Answer : We need to use recursion for this, and here is my version of the C code for the same
#include <stdio.h>

void printBinary(int k)
{
if(k != 0)
{
printBinary(k/2);
}
printf("%d", k%2);
}
void main(void)
{
int k = 4561;
printBinary(k);
}