I don’t know. I know that. Now I know. I know too!

August 24th, 2006 admin

Question

Anant asked me this question. He had heard it in a talk by an executive at Cisco Systems.

There are 2 numbers X and Y (integers).
2<= X < Y <= 100
Person 1, P1, knows X * Y (product).
Person 2, P2, knows X + Y (sum).
P1 knows that P2 knows the sum, P2 knows that P1 knows the product.
They have this conversation:
P1: I do not know what X and Y are.
P2: I knew you would not know.
P1: Now I know what X and Y are.
P2: Now I too know what X and Y are.
What are X and Y?

Solution

This is not an easy one. At least not as easy as the previous puzzle Anant had asked. I will provide a brief commentary on the approach and then present a C program that solves the problem. The comments in the program may also be of some help, although there is probably no alternative to going through the process yourself.

Lets take the statements one by one, and see how they reveal more and more detail, thereby narrowing our choice of potential answers until we are left with one. Of course we were lucky to be left with exactly one. We could, with a larger range for X and Y, end up with more than one pair for answers. Before evaluating the statements I think there are some key things to realize. The problem is easier to solve if you were either P1 or P2. But you are not. You are relying on reducing a set of candidates such that what P1 and P2 could do at a given step and no earlier, makes sense. So other than P1’s and P2’s deductions YOUR deductions play a role. The second realization is that you might have to use a computer to help you out, for the set of possible pairs is quite big to start with. Without loss of generality I choose both P1 and P2 to be male and use “he”,”his” or “him” to refer to them.

P1 says: I do not know what X and Y are.
P2’s deduction: NOTHING, as his next statement shall reveal.
YOUR deduction: Aha! X and Y are not prime, else X and Y would be the only non-trivial factors in a factorization of X*Y.

P2 says: I knew you would not know.
P1’s deduction: I see. So P2 knew that X and Y are not both prime. This is only possible if X+Y is a sum that two prime numbers in the range from 2 to 100 cannot ever add up to.
YOUR deduction: Exactly same as P1’s deduction.

P1 says: Now I know what X and Y are.
P2’s deduction: I see. So P1 has a product X*Y such that he could calculate the correct factors, i.e. X and Y, out of all possible factors of X*Y. That means there is only one factorization of X*Y, such that the two factors X and Y satisfy the condition that X+Y is a sum that cannot be reached by adding two primes.
YOUR deduction: Exactly same as P2’s deduction.

P2 says: Now I too know what X and Y are.
P1’s deduction: NOTHING, he has solved the problem already, and has stopped listening to P2.
YOUR deduction: Aha! P2 has been able to solve the problem. P2 knew what X+Y was. P2 also knew that P1, who knew X*Y, figured it out. So P2 knew that X*Y is such that there is only factorization that when added leads to a sum that cannot be reached by adding two primes. So P2 now looks at X+Y that he knows and figures out all possible pairs that add up the sum X+Y. These are pairs such as (2,(X+Y-2)), (3,(X+Y-3)) etc.. The fact that P2 was able to pick the correct one from these possible pairs implies that there is only one pair that satisfies the property that if multiplied, the product has only one factorization (say X*Y) such that the two factors satisfy the condition that X+Y is a sum that cannot be reached by adding two primes. But we do not know X+Y. So we will have to choose all possible candidates for X+Y. Of course, we need to restrict the search to summations that cannot be reached by adding any primes (to honour P2’s first observation). So we will try to find the pair that P2 could have identified had that sum been what he was handed.

Luckily, we find only one sum that satisfies the property that P2 could have solved the problem. So we have the solution that way. If there were two such pairs, as indeed there could be with a larger set of choices for X and Y, P2 might have been able to solve it but not us.

Upon researching further on the net, I found this link to how the famous computer scientist and mathematician Edsgar W. Dijkstra’s solved it without the help of a computer and with hardly any help from paper and pencil. A couple of more interesting observations are revealed than I did above. He makes a note, in his own handwriting, at the end of the paper that he learnt that his nearly-blind sister had solved the very same problem in the sixties.

C Program to solve the same problem (specific to this range, but could be generalized and optimized to save space)


    #include <stdlib.h>
    #include <stdio.h>
    const unsigned int primes[] = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97};
    unsigned int numOfPrimes =sizeof(primes)/sizeof(primes[0]);
    main(int argc, char** argv)
    {
      unsigned int i,j;
      /*=============================================
      * P1 does not know what X & Y  are from XY
      * X, Y are not both prime
      ==============================================*/

      /*=============================================
      * P2 already knows the above fact.
      * => X+Y cannot be a sum that can ever be
        gotten by adding two primes in the given range
      * histSumOfPrimes[200] is an indicator of which
        X+Y sums could not be gotten by adding primes
      * if histSumOfPrimes[i] == 0, that implies that
        i is a sum of two numbers, that could not be
        both prime. In other words i is a candidate
        for what P2 has been given
      ==============================================*/
      unsigned int histSumOfPrimes[200];
      for(i=0;i<200;i++)
        histSumOfPrimes[i]=0;

      for(i=0;i<numOfPrimes;i++)
        for(j=0;j<numOfPrimes;j++)
            histSumOfPrimes[primes[i]+primes[j]]++;

      /*=============================================
      * P1 is now able to figure out X and Y from XY
      * So of all the ways to factorize XY into a*b,
        there is exactly one such that
        histSumOfPrimes[a+b]==0
      * We as the third person also know that we only
        need to consider as the potential product P1
        has, only those XY products for which
        histSumOfPrimes[X+Y]==0
      * histValidProds[10000] is a histogram that
        keeps track of how many ways there are to
        get a product XY from X and Y that satisfy
        histSumOfPrimes[X+Y]==0
      ==============================================*/

      unsigned int histValidProds[10000];
      for(i=0;i<10000;i++)
        histValidProds[i]=0;

      for(i=2;i<=100;i++)
        for(j=2;j<=100;j++)
          if(i<=j)                  //to avoid double counting
            if(histSumOfPrimes[i+j]==0)
              histValidProds[i*j]++;

      /*=============================================
      * P2 is now also able to figure out X and Y from
        X + Y.
      * There are several potential break-ups P2 must
        consider. Starting from 2+(X+Y-2), 3+(X+Y-3)
        etc.
      * From these, for him to be sure he knows which
        is the pair a,b such that a+b = X+Y, he needs
        to be sure that a,b are such that
        histValidProds[a*b]==1, that is, there is
        only one way to get a factorization of a*b
        such that histSumOfPrimes[a'+b']==0 (where
        a'*b' = a*b)
      * Since we as the third person do not know which
        X+Y P2 is starting from, we consider all
        potential sums, i.e sums such that
        histSumOfPrimes[X+Y]==0
      ==============================================*/
      unsigned int histValidSums[200], X[200], Y[200];
      for(i=0;i<200;i++){
        histValidSums[i]=0;
        X[i]=0;
        Y[i]=0;
      }

      for(i=4;i<=200;i++){
        for(j=2;j<=(i>>1);j++){     //to avoid double counting
          if(histSumOfPrimes[i]==0 && histValidProds[j*(i-j)]==1)
           if(histValidSums[i]==0){
             histValidSums[i]=1;
             X[i]=i-j;
             Y[i]=j;
           }
           else
             histValidSums[i]=2;    //some invalid count
        }
      }

      /*=============================================
      * All potential X,Y values are now printed
      * There is no reason to expect there to be only
        1 pair. If it is 1 pair, we as the third
        person, should consider ourselves lucky.
      ==============================================*/
      for(i=0;i<200;i++)
        if(histValidSums[i]==1)
          printf("%d,%d\n",X[i],Y[i]);
    }

Posted in Tidbits | No Comments »

A diagonal through a rectangular grid of squares

August 20th, 2006 admin

Question

Anant asked me this question. He had heard it in a talk by an executive at Cisco Systems.

“There is a rectangular grid composed of 1×1 squares (i.e unit squares). The grid measures m squares by n squares. How many squares will a diagonal pass through?”

There are potentially many ways to compute a solution to this one. A deep dive into discrete mathematics is one way to tackle the problem, but the fact that an executive asked the question made be believe that there had to be a more elegant approach to solving it. The lesson the executive wanted to share with his colleagues was, probably, that a problem may have only one solution, but there may be a more elegant way to get to it and a less elegant way. Elegance of a solution is probably as important an aspect as correctness. Elegance not only saves time, but it also makes the solution easy to implement, understand and sell. I believe elegance should be a criterion to further qualify a solution beyond it’s correctness.

Getting back to the question, here is a figure showing an example scenario where mxn is 5×9.

Each square in the grid is 1×1.Draw a diagonal through the grid, as shown in the next figure.

The diagonal goes through some number of the 1×1 squares. These squares are highlighted in the next figure.

In this example it is easy to count that there are 13 squares that the diagonal goes through. What is the general solution in terms of m and n?

Solution

Read this solution only after you have either solved the problem in your way or have at least given it a good think. Keep an eye on how you approached the problem. The first step in the solution is to realize that the answer is not a trivial answer such as max(m,n), i.e. the bigger of m and n, or a non-integeral sqrt(m*n), or some variation there of. To prove it to youself, draw a 2×3 grid, and see that in this case the diagonal passes through 4 squares. Now draw a 2×4 grid and notice that the diagonal again passes through 4 squares! So the solution, though increasing in general as m and n grow, might sometimes give the same answer for two different mxn values.

I will dive straight into my solution without going into other approaches. I feel that my solution is relatively straightforward, quite thorough and yet, not too hard to explain. The main observation that gets us started is to notice that m and n can have two kinds of relationships. In one case, they might be relatively prime. That means there is no common factor between the two larger than 1. Highest Common Factor of m and n = HCF(m,n) = 1. The other case is that there is a common factor larger than 1. Taking examples, if mxn is 2×3, there is no common factor other than 1. If mxn is 2×4, then 2 is a common factor. The reason this is important is that the diagonal, in its journey from one corner of the rectangular grid to the other, only passes through a grid-point (i.e the corner where 4 1×1 squares meet) if m and n are not relatively prime! Several questions arise here. First is “Why?” and the second is “So what?”. To prove this, let us use a contradiction approach. Say m and n are relatively prime. There is no common factor between m and n other than the obvious 1. Say the diagonal passes through a grid-point. Let’s pick the first grid point it passes through and call it GP. Let C1 be the corner the diagonal “starts” at, and C2 be the corner the diagonal “ends” at. Since the diagonal is a single line and has a constant slope, the slope from C1 to GP is the same as the slope from GP to C2. This implies that, treating GP as C1, the diagonal will meet another grid-point in relatively the same position from GP as GP was from the original C1. Eventually since the diagonal must hit the ending corner C2, C2’s co-ordinates (m,n), must be a multiple of the co-ordinates of the first grid-point GP, say (m’, n’). m is k*m’ and n is k*n’, for some k, which therefore is a factor. This implies that m and n cannot be relatively prime. Putting it another way, if m and n are relatively prime the diagonal cannot pass through grid-points.

Once the effect of relative primality between m and n is established, it is a very easy problem to solve. Say m and n are relatively prime. Then the diagonal never goes through any of the intermediate corners of the 1×1 squares. Only corners it touches are those of the square the diagonal starts from and the square the diagonal ends at. Only way the diagonal enters a new square is from the top or side of a 1×1 square, never from a corner. Another way to say this is, each time the diagonal cuts either a horizontal or vertical grid line it enters a new square. That means to calculate the number of squares the diagonal passes through, the only thing we need to calculate is the number of vertical and horizontal grid lines the diagonal cuts. And that is easy to calculate. Imagine for a second that the horizontal grid lines vanished. The number of vertical lines the diagonal has to cut across to reach the other corner is … well, all the vertical lines there are, which is n – 1. This is shown in the figure. Now, for a second imagine that the horizontal lines are back, but the vertical lines have vanished. The diagonal must cut through the m – 1 horizontal lines.


The diagonal, even before it starts cutting any of the horizontal or vertical lines, must start from the first square, so it touched that one square without cutting any grid lines. So we add 1 to the total count of grid lines cut by the diagonal. This gives us,

The number of squares the diagonal passes through when m and n are relatively prime is
= (n-1) + (m-1) + 1
= m+n-1 : let’s call this Equation 1

So that brings us back to the case where m and n have a common factor. The largest common factor is HCF(m,n). If you look at the mxn grid, it is basically a replication of the problem k times where k is the HCF(m,n). This is shown in the figure. Therefore the answer is to solve the problem for the smallest relatively prime grid of size m/k x n/k and just multiply that answer by k, since the problem repeats k times across the length of the diagonal, as shown in the next figure.

This gives us the final solution to this problem.
Solution for the m/k x n/k grid
= m/k + n/k – 1 (from Equation 1)

Solution for the m x n grid
= k*(m/k + n/k -1)
= m + n – k
= m + n – HCF(m,n) : let us call this Equation 2

Equation 2 is the final answer.

Posted in Tidbits | 2 Comments »

Poisoned Wine

June 4th, 2006 admin

You are the Monarch of an Island and are about to have a festival tomorrow. The festival is the most important one you have ever had. You’ve got 1000 bottles of wine you were planning to open for the fiesta, but you find out that one of them is poisoned by some evil scoundrel. The actual poison exhibits no symptoms until somewhere around the 23rd hour, then results in sudden death. You have thousands of prisoners at your disposal.

1. What is the smallest number of prisoners you must have to drink from the bottles to find the poisoned bottle?
2. What is the smallest number of prisoners that you must sacrifice?
3. For the strong minded, what is the smallest number of prisoners if more than one bottle (say 2) is poisoned?

Read More – poisonedWine.pdf

Posted in Tidbits | No Comments »

Send More Money

October 19th, 2005 admin

My father asked me this question over the phone this weekend.

“A college going kid’s father, tired of his sons repeated requests for money throws him a challenge. He asks the son to solve a math puzzle, before expecting any more money from the dad. SEND + MORE = MONEY is a mathematical equality, where each letter is a unique numeral. What is the equality in numbers?”.

It turned out to be an immensely interesting puzzle. It has a unique solutions, the solution can be logically deduced, and it makes a sensible English phrase! That third point is something I am still not sure whether to be amazed by or not.

Here is a sequence of steps I followed in my deduction of the solution

  S E N D
+ M O R E
---------
M O N E Y

The M has to be a 1, since the carry from adding S of SEND and M of MORE can be either a 0 or a 1, and in this case it is a 1 since we have M in MONEY to represent it. Another way to say the same thing is adding two numbers in the thousands can not give you twenty thousand or more. even 9999 + 9999 falls short of 20000 by 2.

  S E N D
+ 1 O R E
---------
1 O N E Y

S in SEND and 1 from 1ORE have to add to result in a carry since the whole existance of the 1 in 1ONEY depends on it. That is possible only if S is 9, there is no carry from the hundreds’ place (and therefore the O in MONEY is 0) or S is 8 and there is a carry of 1 from the hundreds’ place (in which case the O in MONEY is 0 again) or indeed the case that S is 9, and there is a carry of 1 from the hundreds’ place (and here the O in MONEY is 1). Since O can’t be 1, as M has wrested that privilege, the only two plausible choice is that S in SEND is 8 with a carry from the hundreds’ place or the S is 9 with no carry from the hundreds’ place. So, are we stuck? Which of these two to choose? Well, time to look a little into the future, by which I mean the hundreds place. One thing is certain, whether S is 9 with no carry or 8 with carry, the O in MONEY is 0. Therefore the O in MORE is 0 too! So looking at the hundreds’ place, E + 0 = N. That can’t be. There must be a carry from the tens’ place! So the hundreds’ place equation now reads, 1 + E + 0 = N. The question we are after is does 1+E give rise to a carry or not. Only way it can give rise to a carry is if E = 9. But then 1+E =10 and that means N = 0. That can’t be. O has gotten that privilege. So we do not know what E is but is certainly is not 9 (and not 0 or 1). So that means, since there is no carry over from the hundreds place S is 9.

  0 1
  9 E N D
+ 1 0 R E
---------
1 0 N E Y

N is one more than E. At first glance the values E can take are 2,3,4,5,6,7,8. Of these, 8 has to be ignored since then N would be 9. But 9 has already been assigned to another letter. Still the choices for E are too many. Looking at the tens’ place, N + R = E + 10 or 1 + N + R = E + 10 (if there is a carry from the ones’ place). The 10 in the above equation comes in because there is a carry from the tens’ to the hundres’ place for sure. Substituting E+1 for N, we get either E + 1 + R = E + 10, which implies R = 9 which is not possible, or that, 1 + E + 1 + R = E + 10, which leaves us with the information that R = 8 and equally importantly, that there is a carry from the ones’ to the tens’ place.

  0 1 1
  9 E N D
+ 1 0 8 E
---------
1 0 N E Y

Now we look at the ones’ place. D, E and Y have to be three amongst 2,3,4,5,6,7 since the others have been taken. The information that the ones’ place lends a carry to the tens’ place means D + E = Y + 10. Note than the ones’ place cannot have a carry from the tenths’ place. This implies that D and E have to add up to at least 12, since Y is, at a minimum, 2. The only ways of adding a pair from the remaining numbers to get 12 or more are 5+7 or 6+7. E is either 5,6 or 7. Now we fall back upon the hundreds’ place to bail us out of the dilemma. The hundreds’ place tells us that E + 1 = N. Therefore E cannot be 7, since then N would be 8. N cannot be 8 since 8 is taken by R. Since E cannot be 7, E is either 5 or 6. Either way, D is 7. Now, if E were 6, N, which is E + 1, would be 7. That is not possible since we just allocated 7 to D. So E is 5 and N is 6.

  0 1 1
  9 5 6 7
+ 1 0 8 5
---------
1 0 6 5 Y

Y is therefore 2. And the final solution is 9567 + 1085 = 10652

Posted in Tidbits | No Comments »

Crossword Clues

August 28th, 2005 admin

Kavita and I sometimes play this game over the phone, where I give Kavita a clue and she has to figure out the word. The clue is usually simpler than a cryptic clue in a crossword puzzle, bit I would still categorize it as a cryptic clue because there are two parts to the clue. Either both buttress the reason for the clue’s solution being what it is, or one provides the solution while the other part of the clue confirms it. In general I prefer cryptic clue crossword puzzles over easy clues, because with cryptic clues, each clue is a puzzle in its own right, and the crossword puzzle fills itself once you get the answer.

Syhamala and Srini also enjoy participating in this kind of a cryptic clue session. Lot of times, since the clues are created on the fly and are not “solidified” yet, they are twisted and mangled as the game proceeds leading to strange guesses and a hearty laugh. Shyamala suggested that I should atleast keep track of these, and therefore I am putting them together here.

Hereditary Clothing
Aim to shop at this store
Mated domesticated
Spherical dance
Direction I threw the stew in
India grows teas in this direction
Direction of old “you”s
Direction prickly things go
Mites multiplication factor
He levitated like this flower
Sue it’s for blowing your nose

Posted in Family, Tidbits | No Comments »

Binary vs ASCII Files

July 17th, 2005 admin

How are they generated?

The difference in how a file is written into memory is crucial in knowing how to read it. If a file is written using fprintf, then the data in the file is stored as a sequnce of ASCII characters. This creates a file in the ASCII format. If the was written using fwrite, then the data would be stored as one of many data types depending on what the fwrite is writing. For example, if the fwrite is writing an int (32 bit quantity), then the 32 bits are written to the memory as is. This creates a binary format file.

Example

If you write 12345678 to a file using fprintf, the file will actually have the ASCII codes for the symbols ‘1′, ‘2′, ‘3′ and so on, a total of 8 bytes. If you write 12345678 to a file using fwrite and the pointer to the source is an int*, then the 32 bit (4 byte int) binary corresponding to 12345678 will be directly written to 32 bits in memory.

How does it matter?

ASCII, being a byte by byte storage format, is not affected by big-endian/little-endian storage issues. Since the bits in a byte are not affected by little or big endian storage scheme, only problem arises if the datum being stored as a single-entity crosses the byte boundary. And that happens with something like storing a 32 bit quantity as is (in binary). Therefore, when reading an int from a binary file using fread, one should be careful to flip the bytes in case the machine that is reading the binary file uses a different endian scheme than the machine that had written the file. I faced a problme recently where a trace file feeding one of our performance models was in big-endian binary format in memory. I had to read one instruction (32 bits) at a time and flip the bytes, before I could use the trace when the model was running on a little endian machine.

Posted in Tidbits | No Comments »

A puzzling weekend

April 3rd, 2005 admin

The puzzler went something like this “There is a famous person in history, with 5 lettered first name and 4 lettered last name. Rearrange the first name to make a term used in a certain game and rearrange the lastname to make the name of that game!”

I thought about it for a few seconds and realized that finding the names of games that are only 4 letters long might be worth it. Golf and polo came to mind. But I could not think of many 5 lettered terms used in those games. I was listening to the National Public Radio’s Weekend Edition Sunday on the radio, brushing my teeth. Soon I went down to the kitchen to preparing my usual weekend morning tea. I started heating water on the range when I called Kavita. She woke up sleepy eyed and after a few initial words I threw at her this problem. Upon hearing that I was thinking about polo as an option, she just said “Marco Polo”. She said it as a joke, almost as a rebuttal that if I thought of Polo, she actually though of a famous person with that for a last name. Maybe she did not realize that the problem had the added twist of rearranging the letters. Almost immediately a light bulb went off in my head. That could be it. “Pool is also a game and is a rearrangement of Polo!” AND more importantly, Carom, is a term used in pool! I was amazed at how she got the answer almost without realizing she had! It was a good start to the day. I sent in the solution to puzzle@npr.org today.

Yesterday I was at Srini’s place and Shyamala and I were playing wordgames like taboo (Shyamala had sometime ago written up with the word being guessed and the tabooed words that should not be used while trying to describe the word), twenty questions etc. One of the games was about thinking of something or somebody and giving indirect clues about it. She asked me a question, “I am thinking about something which cries when used, makes our lives brighter and comes in many colours. What is it?” I thought for about 5 minutes…while watching the Illinois Fighting Illini and the Louisville Cardinals fight it out in the NCAA mens basketball semifinals…I had no clue. I asked for one more clue. She said “Some of these smell nice”. I continued being clueless. Then after a few more minutes of contemplation, I asked, “Can I see it from where I am sitting?”, and she, after a few moments of thought and with a hint of uncertaininty said, “You should be able to see if from where you are sitting”. I started looking for things not in direct sight, but at the edges of my vision. Shyamala had said I “should” be able to see it. And she had taken a few moments calculating the answer given my position in the room. So it had to be something not in direct sight. Still no clue. Then my phone rang and Kavita was on the other side. After a few initial pleasantaries, I asked her this question. I even told her that I should be able to see it where I was. She might have thought for a total of 5 seconds and said candles in a tone suggestive of “Aaaawbviously”. And then the big bulb went on in my head. Every thing made sense. Every clue. And it was right in front of me all the while…sitting on the mantlepiece of Srini’s woodburning fireplace in his Brook Arbor apartment!

My comeback to Shyamala was a question about somebody famous (or infamous) and went something like – “More like a shrub, less like grass or a tree, donkey among elephants but not a donkey!

And talking of puzzles, there was this one on ThinkGeek.com. If you bought anything over $10 you were supposedly getting this T-shirt which said “Fake Ghostlike Photons”. I was wondering what satirical message could this be. The website, upon closer insoection revealed a clue that this was an anagram of some sort. Unable to solve it and unable to contain my curiosity, I googled for it and found on Slashdot, the message, in accordance with it being April Fools day recently, was, “Fools shop at ThinkGeek!”.

Posted in Tidbits | No Comments »

Small step of logic or a giant leap of math … take your pick!

October 17th, 2004 admin

There are a 100 people trying to get onto the same flight you are. The airplane has a 100 seats. You are all ready to board. You are the last one in the line of passengers at the gate. The first guy walks in to the flight and promptly realizes that he does not have his boarding pass on him and does not remember his seat number. So he picks one at random, hoping his charm will take care of the after effects. Every one else takes their assigned seat if it is available. If someone is already sitting on it they quietly look for an empty one and sit there. By the time you get in there is only 1 seat left. What is the probability that the seat which remains is indeed the one originally assigned to you?
This problem, I heard on National Public Radio’s show called Car Talk a couple of weekends back, and immediately set to solving it. I solved it in about 15 minutes with relatively straight forward mathematics, but had the nagging feeling that the problem did not deserve the insight-less fiddling around with drone mathematics, and instead had a much more elegant and insightful, logical solution. I had to wait for the next show for the answer, which as I suspected was crisp and short. The first thing I tried to do was to get to the answer. Once I got there I would decide if I was satisfied by my method or not. This brute-fore technique meant I started with the probability the first guy got his assigned seat. Denoting that by P1, I concluded,

P1 = P(first guy picks his assigned seat)

= 1/100

P2 = P(second person picks his assigned seat)

= p(first person does not pick the second person’s assigned seat)

= 1 – p(first person picks second person’s seat)

= 1 – 1/100

= 99/100

P3 = p(third person gets his assigned seat)

= p(neither of the first two take his seat)

= 1 – p(either of the first two take his seat)

= 1 – p(first takes third’s seat OR second takes third’s seat)

= 1 – p(first takes third’s seat) – p(second takes third’s seat)

The probability that the first takes third’s seat is 1/100.

The probability that the second takes third’s seat is p(first takes second’s seat and second takes third’s seat), because second would only ever try to sit anywhere other than his assigned seat, if first has already occupied his rightful seat. Therefore this probability becomes p(first takes second’s seat). p(second takes third’s seat). The reason the probabilities get multiplied in the previous line is because the probability of first taking seconds seat is independent of the probability of second taking third’s seat once he decide to choose a random seat. p(first takes second’s seat) = 1/100 and p(second takes third’s seat)= 1/99 since second has 99 seats to choose from when he enters the plane.

continuing our equation from above

= 1 – 1/100 – 1/100.1/99

= 99/100 -1/100.1/99

= (1/100).(99-1/99)

= (1/100).(99.99 – 1)/99

= (1/100). (99 + 1).(99 – 1)/99 using P2-1 = (p+1).(p-1)

= 98/99

If we continue this lengthy procedure and keep our thoughts straight we will see that

P4 = p(fourth person gets his assigned seat) = 97/98

P5 = p(fifth person gets his assigned seat) = 96/97 and so on … till we find out

P100 = p(100th person gets his assigned seat) = 1/2

The answer is deceptively simple and has something about it that makes us wonder if this headlong dive into mathematical woods is necessary. An even stronger whiff of suspicion is leant by the seeming irrelevance of the total number of people trying to board the flight. I would have gotten a similar pattern with 50, 80, 200 or 200 million passengers. I felt sure that there was an easier way to figuring this out. I thought for a while, talked about it to a couple of my accommodating friends over lunch, and decided to wait for the answer on NPR’s “Car Talk” show hosted by Click and Clack the Tappet brothers.

Here is their version of the answer, in my words. If someone chooses the seat assigned to the first person then there will be no more need for any seat exchanges. If someone chooses your seat (you are the last one to get on the plane), your probability to get the seat assigned to you is 0. Lets think about the first assertion. If the first person sits by chance on his assigned seat, passengers 2,3,4 … 100 will not notice any problem and will sit on their assigned seat. Say passenger 1 sits on some other seat say number n. The first passenger to note a problem will be passenger assigned seat n. Up until that point all passengers happily seat themselves into their assigned seats. Say passenger assigned to n sits on a seat numbered m, the a similar logic applies and only passenger assigned to m, will notice a problem. If any of these passengers who choose a seat randomly, choose seat originally assigned to passenger 1, no one after them will notice any problem, since the only person who could have noticed a problem is passenger 1 himself who is already seated. Therefore a subset of the total number of passengers will make a decision to choose a seat at random. If they choose the seat assigned to person 1, you are guaranteed to get your seat. If they choose the seat assigned to you, you are guaranteed to not get your seat. To a person choosing a seat at random, your seat is no different that the first person’s seat. So irrespective of the number of people (both total and one’s who have to choose), it’s just a matter of is your seat chosen first or is the first person’s seat chosen first. Therefore due to the symmetry in the argument the answer is 1/2.

Posted in Tidbits | No Comments »

2’s Complement, and the trick to negate it

October 15th, 2004 admin

“2’s complement” is an often heard phrase in the world of computers. It is a notation used to represent numbers to ease subtraction. The intuitive binary number notation only stays positive, adding higher powers of 2 to the number as you keep adding 1’s to the left of a number. The most intuitive way to denote a negative of a number is to place a “-” symbol to its left. So if in decimal -5 is negative of 5, why can we not live with -101 for negative 101 (101 is binary for decimal 5) in binary? We can, but this “-” symbol is an abstraction useful to think about the number. A computer, which can only identify a 1 or a 0 (a high or a low voltage), needs to represent the “-” symbol using a trick.The easy trick would be to have an understanding that the first bit of any binary-represented number would indicate if the number is positive or negative. So if a number starts with 1, that indicates that treat the rest of the number as a positive binary number and negate it. If the number starts with a 0 that indicates that the number is positive. Unfortunately every sane number starts with a 1. If a number starts with a 0, the 0 is simply ignored (not to mention it looks strange). So to represent decimal 5 as 101 is fine but to represent it as 0101 looks a little odd. So then the way to make this first-bit-1-for-negative scheme work we need to associate a place value for the sign-representing leftmost digit. So say we want our number system to be capable of representing all numbers from -12 to 12, we will need to use 4 bits at least, for 12 is 1100. And then we can say the fifth bit from the right will be used to represent sign. So 12 becomes 01100 and -12 becomes 11100. And one that fact is made understood 5 represented as 00101 does not look as questionable. This scheme has two representations for 0, 00000 and 10000. In this scheme therefore, out of the 32 unique arrangements possible using 5 bits, 15 represent positive numbers, 15 represent negative numbers and there are 2 representations for 0. This scheme is called the sign-magnitude representation.

Yet another way to represent the fact that a number is negative would be to again have an understanding that the number is a represented using a fixed and predetermined number of bits, the left most bit being 1 indicates negative and being 0 indicates positive, and that the way you flip a positive number is to flip each of its individual bits. The positive number starts off with a 0 as its highest order bit, by definition, and therefore the flip of all the bits flips this bit too and makes it negative. The fact that for every pattern of bits there is a unique flipped pattern, guarantees that we have a unique negative number for each positive number, that can be easily identified. So if we say we will use 5 bits to represent a number and 5 is 00101, -5 is 11010. How we recognize 11010 to be -5 is we notice the “-” from the first bit and notice the 5 by flipping the bits back and calculating the resulting value in decimal. Only one small glitch is that this representation provides two equally acceptable versions of 0, namely 00000 and 11111 (since 0 = -0). So at another level of abstraction, this just means that out of the 32 different patterns possible using 5 bits, this scheme has 15 positives, 15 negatives and 2 0’s. This scheme is called 1’s complement representation.

2’s complement is another notation where the first or leftmost bit actually represents a negative offset. The remaining bits work the same way as for normal positive binary numbers. So in the most intuitive notation, 101 means 1*22 + 1*20, or 5, and in the 2’s complement notation 101 means -1*22 + 1*20, or -3. This representation has a unique representation for 0 (00000) and a unique representation for 15 positives, and 16 negatives! That is because 10000 means -16! There is therefore no duplication and the 32 variations of the 5 bits represent 32 unique numbers. Instead of 3 bits say we want to use 4 bits to represent 5. 5 would then be represented as 0101.But what about -3? The leftmost bit needs to be 1 to give the number a negative offset. The offset is -23 and that is -8. So to get the end value to be -3 we need the remaining three bits to value +5. So -3 in 4 bits is 1101. And this indicates the phenomenon called sign bit extension. 101 is -3 and extending the sign bit (the most significant bit) on the left by repeating it makes the number 1101, which still is -2! In 2’s complement notation, in general the sign bit may be extended to the left (i.e. repeated on the left) without changing the value of the number.

The trick to negate a 2s complement number is often taught as “flip all bits and add a 1″. What is happening here? Let’s give it a shot first. 3 is 011 in 3 bit 2’s complement representation. Flip the bits and we get 100. Add a 1 and we get 101, which we saw earlier was 2’s complement representation for -3. Why this works is pretty straightforward once we see what’s going on. When the bits of an n bit positive number N are flipped essentially we end up with a number of value 2n – N. Why?

N = 0 xn-2 xn-3 . . . x0 (where xi is 1 or 0)

-2n-1 2n-2 2n-3 . . . 20 (corresponding power of 2)

= 0.(-2n-1) + xn-2.2n-2 + xn-3.2n-3 . . . + x0.20

= xn-2.2n-2 + xn-3.2n-3 . . . + x0.20

N’ = N flipped

= 1 xn-2‘ xn-3‘ . . . x0

-2n-1 2n-2 2n-3 . . . 20 (corresponding power of 2)

= 1.(-2n-1) + xn-2‘.2n-2 + xn-3‘.2n-3 . . . + x0‘.20

N + N’ = 1.(-2n-1) + (xn-2+xn-2‘).2n-2 + (xn-3+xn-3‘).2n-3 . . . + (x0+x0‘).20

= 1.(-2n-1) + 1.2n-2 + 1.2n-3 + … + 1.20

= 1.(-2n-1) + (2n-1 – 1)

That last reduction essentially is based on the observation that 1112 = 10002 – 1 and so on.

Therefore

N + N’ = -1

Therefore rearranging,

N’ + 1 = -N

Posted in Tidbits | No Comments »

Becoming a rememberer – an aid to remembering annually recurring events, such as, birthdays.

July 17th, 2004 admin

Here is a miraculous solution to the age old problem of forgetting birthdays and anniversaries. A perl script that can send you email every morning about what’s coming up for the next week, so not only do you remember, but you have enough time to set up something special … like a surprise birthday cake!
OK enough of the introduction. Essentially it is a simple perl script that I run on my Unix machine. At it has already proven its worth. So this is for those of you who are looking for a similar tool.

#!/usr/bin/perl
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

#Written by: Anil Krishna

#On: July 10th 2004

#Purpose: This perl script sends an email to a given address, with a listing of events that are going to happen in the nesr future. The “nearness” is described by a variable called $warnZone in the script.

#Dependency: This program needs a dateslist.txt file to contain the dates and corresponding events.
#The dateslist.txt file should contain the dates in the following format for this perl script to work right.
#month_in_digits date_in_digits String Describing the event
#example:
#1 1 New Year’s
#8 15 India’s Independence
#9 1 bright’s Birthday; email address: bright@tubelight.com

#Usage: To use this script, create the dateslist.txt file. You can add to it as appropriate. Set the $from and $to variable to point to appropriate addresses. Set the $warnZone to any other number if you want. Right now it is set to 7, which means the program will warn you about events happening in the next 7 days (including today). And you would likely want to run this program with some regularity. I run this program once a day. The way I automate that is by creating a crontab entry in a Unix machine where I store these files. Crontab is a table where you can specify time periods for autoamtically having the system run executable programs such as this one. The way it typically works is do a “crontab -e” call on your Unix machine. It will open up a file for you to edit (using the system’s default text editor. Type in the following command to have it run the program every morning at 6 AM. “0 6 * * * ~/date.pl”. What this is saying is at 0 minutes, 6 hours, every day of the month, every month, every day of the week, run ~/date.pl. You would have to change the path to this perl script according to where it is located on your Unix machine. You could also choose to run this script only every Thursday midnight, by doing this to the crontab, “0 0 * * 4 path/to/your/foleder/file.pl”. By the way, just as “crontab -e” lets you edit the crontab, “crontab -l” lists the current crontab entries.

#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

#find today’s day of month (mday) and month (mon)
($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime (time);

#day of year = yday+1 (since the count starts from 0 in perl)
$today_doy = $yday+1;

#array defining days in months, and variable defining num days in year
if($year%4 == 0){
@dpm=(31,29,31,30,31,30,31,31,30,31,30,31);
$daysThisYear = 366;
}
else{
@dpm=(31,28,31,30,31,30,31,31,30,31,30,31);
$daysThisYear = 365;
}

#read the entries in the table of dates and see if there is any that is close. Close is defined as being within nearEnough (defualt 7) days.
$warnZone = 7;
open(DATES,”dateslist.txt”) or die “dateslist.txt could not be opened \n”;
while ($line = )
{
($event_month, $event_dateInMonth, @event) = split(” “, $line);
$event_doy=0;
for($i=1;$i<=$event_month;$i++){
if($i<$event_month){
$event_doy += $dpm[$i-1];
}
else{
$event_doy += $event_dateInMonth;
}
}
$proximity = $event_doy-$today_doy;
#if the event is in the same year as today then proximity is positive, and its being withing the warnZone is good enough.
#if the event is in the next year, then proximity return a negative value. daysThisYear + proximity indicate the real proximity of the event, and its being withing the warnZone is good enough.
if( ($proximity >= 0 && $proximity <= $warnZone) || ($proximity < 0 && $daysThisYear + $proximity <= $warnZone ) )
{
$content .= “@event on $event_month/$event_dateInMonth \n”;
}
}

#send email with the above collected content content.
use Net::SMTP;
$from = “sender\@source.com”;
$to = “receiver\@destination.com”;
$subject = “Important Upcoming Dates”;
$relay = “mailrelay.charlotte.servercompany.com”;
$smtp = Net::SMTP->new($relay) || die “Can’t open mail connection: $!”;

$smtp->mail($from);
$smtp->to($to);
$smtp->data();
$smtp->datasend(“To: $to\n”);
$smtp->datasend(“From: $from\n”);
$smtp->datasend(“Subject: $subject\n”);
$smtp->datasend(“\n”);
$smtp->datasend(“$content\n”);
$smtp->dataend();
$smtp->quit();

Posted in Tidbits | No Comments »