Tuesday, December 30, 2014

Sum of unit fractions puzzle

A unit fraction is a number of the form $\dfrac{1}{n}$, where $n$ is a positive integer $ \gt 0$.

Show that any positive rational number can be written as a sum of a finite number of distinct unit fractions.

For example 1 can be written as 1/2 + 1/3 + 1/6.


[Solution]

Monday, December 29, 2014

Textbook hand in real life?

This hand had appeared playing on BBO (if I recollect correctly).

Normally, in textbooks you see plays which one might think will be required only rarely at the table: most bread and butter hands require counting and drawing the right inferences, and not some counter-intuitive subtle technique...

Anyway, you are South, and end up in 6C after your RHO preempts 3H. I don't remember the bidding, so you can ignore it.

IMPS
None 
 Dummy
♠ J93
♥ T9876
♦ KQJ
♣ 42

   


 You
♠ AKT
♥ 2
♦ 2
♣ AKQJT976

W N E S
3H6C
allpass


LHO leads a small spade. How will you play?


Solution (posted on Jan 3rd 2015)


Looks like LHO has a heart void. So LHO will have the SQ, and DA.

Seems like we got a free finesse at trick one, but if you win the T in hand, you will not make it! You will lose a diamond and a heart for sure: draw trumps and play a diamond. LHO will win the first round and exit a spade.

You need to throw your heart on the diamonds, and the only way to do that is to make sure LHO helps you by putting you in the dummy.

So win the SA at trick one (playing low from dummy), draw trumps and play diamonds.

LHO who is now left with only spades and diamonds, will have to win either the first or second round (you throw a heart on the second round if LHO ducks the first), and either lead a spade (you put up the J in dummy) or a diamond, allowing you to dispose off your losers.

Saturday, December 27, 2014

Solution to finding the semi-balanced string, algorithm puzzle

This is a solution to finding the semi-balanced string algorithm puzzle.

A brief description:

Given a string S consisting of exactly (n+1) X's and n O's, show that there is exactly one cyclic shift of S which is semi-balanced, and give an O(n) time algorithm to find it.

A string is semi-balanced iff every non-empty prefix contains more X's than O's.

This property can actually be used to show that Catalan numbers are $\dfrac{\binom{2n}{n}}{n+1}$.

Solution

It will be a constructive proof, giving the algorithm with the proof.

Given string S consisting of X's and O's, replace X with a $1$ and O with a $-1$.

For a prefix of length $i$, take the sum $S_i$ of the $1$'s and $-1$'s that form that prefix (basically compute #X's - #O's).

For a semi-balanced string, we must have that $S_i \gt 0$ for all $i, 1 \le i \le 2n+1$.

Note that $S_{2n+1} = 1$ for any string S consisting of $n+1$ X's and $n$ O's.

Now suppose a cyclic shift left by $k$ of S gave a semi-balanced string.

Then we must have that (look at the prefix of the shift from $k+1$ to $j$)

$S_j - S_k \gt 0 \quad \forall j, k \lt j \le 2n+1$

and (look at the prefix from $k+1$ to $2n+1$ and then $1$ to $j$).

$ S_{2n+1} - S_k + S_j \gt 0 \quad \forall j, 1 \le j \le k$

i.e

$S_j \gt S_k \quad \forall j \gt k$

and (note that $S_{2n+1} = 1$)

$S_j + 1 \gt S_k \quad \forall j \le k$

Thus if $ m = \min \{S_1, S_2, \dots, S_{2n+1}\}$ then there is a unique $k$: the largest $k$ such that $S_k = m$.

This easily gives an $O(n)$ time algorithm too.

Friday, December 26, 2014

Solution to area exactly half, geomety puzzle

This is a solution to area always half puzzle.

The problem description:

Show that a triangle whose vertices are integers points (both x and y co-ordinates) and which does not have any integer point inside or on the sides (except the vertices) has area exactly half.

These triangles are sometime called primitive triangles.

Solution

As promised, this is the proof from the book, "Proofs from the book".

This requires some Linear Algebra background.

[Perhaps a simpler proof is to just complete the rectangle (draw horizontal and vertical lines through $p_0$ and $p_2$ in the below figure) and count the number of integer points in the triangles, but the point is to show the book proof.]

The proof in the book goes as follows:



If the points are $p_0, p_1, p_2$, then the parallelogram formed by $p_i$ and $p_1 + p_2 - p_0$ does not contain any integer point, because both $\mathbb{Z}^2$ and the parallelogram are symmetric with respect to the reflection $x \to p_1 + p_2 -x$.

Now we can tile the plane by translating this parallelogram (by integer distances) and thus, $p_1 - p_0$ and $p_2 - p_0$ form a basis for $\mathbb{Z}^2$, which implies that the parallelogram has area $1$, and the triangle has area $\dfrac{1}{2}$.

A basis of $\mathbb{Z}^2$ is linearly independent vectors $e_1, e_2$ such that $\mathbb{Z}^2 = \{ae_1 + be_2 | a, b \in \mathbb{Z}\}$.

Area of the parallelogram spanned by $e_1 = (p,q), e_2 = (r,s)$ is given by the absolute value of the determinant of $A(e_1, e_2) = \begin{bmatrix} p & r \\ q & s \end{bmatrix}$

Given any other basis $f_1, f_2$, there is an invertible matrix $Q$ with integer entries such that $A(e_1, e_2) = A(f_1, f_2)\times Q$.

Since $Q$ is invertible and contains integer entries, we must have $|det(Q)| = 1$, and hence $|det (A(f_1, f_2))| = |det(A(e_1, e_2))|$.

Choosing $f_1, f_2 = (1,0), (0,1)$ gives us the result.

There are other elegant proofs, for instance using Minkowski's theorem. See here.

Another way to prove is to prove that the integer coordinates of primitive triangle (with a $(0,0)$ vertex) form consecutive numbers in the Farey sequence.

The stronger theorem I was referring to in the problem blog post is Pick's theorem.

Friday, December 19, 2014

Finding the semi-balanced string, algorithm puzzle


A string S consisting of exactly n+1 X's and n O's is called semi-balanced, iff every non-empty prefix of S has more X's than O's.

For example:

XXO is semi-balanced while OXX is not.
XXOXO is semi-balanced but XOXOX is not.

This puzzle is in two parts.

a) Show that for any string S consisting of exactly n+1 X's and n O's, there is exactly one cyclic shift of $S$ which is semi-balanced.

For example if S = OXX, its cyclic shifts are OXX, XOX and XXO, the last one being semi-balanced.

b) Given S consisting of exactly n+1 X's and n O's, can you given an algorithm to determine, in O(n) time, which cyclic shift of S is semi-balanced?

[Solution]

Wednesday, December 17, 2014

Area always half, geometry puzzle.


A cute fact about triangles with integer co-ordinates:

Lemma: Suppose $A, B, C$ are points in the 2D plane each with integer co-ordinates, such that no point with integer co-ordinates lies inside, or on the sides (except $A, B, C$) of triangle $ABC$. Then, the area of triangle $ABC$ is exactly $\dfrac{1}{2}$ 

[A point with integer co-ordinates is a point whose x and y co-ordinates are both integers].

For example, $A = (0,0)$, $B = (1,1)$, $C = (2,1)$. The "base" $BC$ and height $AD$ (where $D = (0,1)$) are both of length $1$ and so the area of $\triangle{ABC}$ is exactly $\dfrac{1}{2}$

Can you prove the Lemma?

[Note, using a stronger theorem about lattice points and areas would be circular (unless you prove the stronger theorem without using this Lemma).]

[A neat proof of this appears in Proofs from the Book: Solution]

Tuesday, December 16, 2014

Rabbit Leads a Heart

[I had posted this article on bridgewinners.com. It is based on the characters in "Bridge in the Menagerie" by Victor Mollo, just like an earlier article: Rabbit plays a spade.]


With great reluctance and pressure from the regional bridge authorities, the members of the Griffin club agreed to hold a pre-played Matchpoint tournament. The hands would be ones which were already played at more than a 100 tables previously, and the scores would be compared against the results of those tables, rather than the tables present at the club. The results slip which contained the contracts and the opening leads at those 100+ tables, would be available as soon as the board was played.

The Hog agreed to play with the Rabbit, and on the way to the club, the Hog said, "Raise me with 2 trumps, or a singleton honour. Feel free to double the opponent's contract, no transfers when you open NT". The rabbit replied, "Ok. Lets play 3rd/5th and udca". The Hog, with a generous wave of his hand, said, "Sure". He ignored the Rabbit's defensive signals, anyway.

Meanwhile, Karapet, who was paired with Papa was saying, "Never raise me with just 3. With me they split 5-0. Never double the opponent's contract, they will make it, and never use stayman or transfers which will result in a fatal lead directing double. Why, just last Tuesday..."

He was interrupted by the Hog and Rabbit arriving at their table. Papa and Hog quickly made a side bet about who would make the Rabbit squirm in his seat first, while the Rabbit and Karapet exchanged system information. A few moments later, the tournament began.

Papa was South and was dealt



 Papa opened 2C, Karapet responded 2D, showing 0-4 or 8+ in their system. Papa bid 2S, and Karapet jumped to 4S, denying interest in slam, and showing 0-4.

At this point, Papa, starting his usual monologue with his imaginary kibitzer, thought: "Listen closely. Many players will pass here. Not Papa. You see, Rabbit is on the lead. That is usually worth one, if not two tricks. I am playing the hand, and that is worth an extra trick. I am going to bid 6S. But wait! Not so fast. Where is your imagination? If you are going to bid 6S anyway, why not give opponents a chance to make a lead directing informative double to our advantage?".

Papa bid 4NT, and Karapet showed his 0 Aces with 5D. 6S from Papa closed the bidding. The Rabbit and the Hog had passed through out.

The Rabbit led the H8, and this is what Papa saw:



Papa continued, "See! You can count on the Rabbit! The lead marks the Hog with HKQxxx(x). After winning the HQ with the HA, even the Rabbit can force an entry to dummy by overtaking the HT with the HJ. Draw trumps, unblock clubs, force entry, throw D loser on CJ. 12 easy tricks and a well deserved top!".

Congratulating himself, Papa asked for the H3 from dummy, and was taken aback when the H2 appeared on his right. After getting over the initial shock, he thought, "Hog is a good player, but this is brilliant! With HKQxxx(x) and he can afford to make an entry denying duck. He deserves a good result, but unfortunately for him, I am declaring. I can still make the hand. Wait and see".

So Papa won with the HT, drew trumps, cashed the CAKQ and the HA.

The play so far(click Next):





Papa continued, "We are at the fork in the board, if you will. I can still make the hand if I can tell who has the DK. If the Hog has it, I can exit with a heart, endplaying him. If the Rabbit has it, then I can play DA and DQ. The Rabbit who is out of hearts, must give me the 12th trick. Now who has the DK you ask? Remember the bidding? Imagination? Karapet bid 5D, and Hog did not double! That inference is good enough to place the DK with the Rabbit. Of course, if it was a better player like me, who is capable of making a deceptive double... besides, I will have a chance to make the Rabbit squirm and win the bet".

So Papa played the DA and a D to the Q. It was won by the Rabbit with the DK who now started squirming in his seat.

Papa thought, "Aha! As we inferred. Let him squirm for sometime. I win the bet and a top! I will claim just before he is about the play a card".

After some agony, the Rabbit detached a card, and Papa was about to claim as it hit the table, when he was totally shocked to see that it was the HQ, which took the setting trick.



This was the whole hand:





Papa spluttered, "You.. you... led the H8 from KQ84?".

"Yes, we are playing 3rd/5th", said the Rabbit.

"What were you thinking about when you got in with the DK!?", cried the Hog, handing Papa an IOU for his side winnings.

"I was not sure whether we play the HK or the HQ in this situation. Maybe I should have played the HK. In any case, it did not cost a trick".

Meanwhile Karapet who had opened the pre-played results slip, spoke: "Most were in 4S making 6. Some were in 6S making and some were in 6NT making. One South was passed in 2C making 12 tricks. At all tables, the lead was HK."

"Maybe they weren't playing 3rd/5th", said the Rabbit, as they drew cards for the next board.

Friday, December 12, 2014

Solution to online cake splitting algorithm puzzle.

This is a solution to the cake splitting puzzle posted earlier.

A brief description of the puzzle:

Given a stream of numbers which sum to $1$ and each number being a negative power of $2$, can you give an algorithm to split the numbers in two groups, each of which sum to half when the stream is finished? When you see a number you have to immediately decide which group it goes to. Prove that your algorithm works.

[A more clear description is on the question post].

Solution


The algorithm is actually simple: Keep putting the new pieces in group $A$, unless adding that piece will make the sum go over half. In which case, add it to group $B$!

The interesting part is actually proving that it works.

One such proof (thanks to Eigenray of a forums I used to frequent) goes as follows:

Let $R_A$ and $R_B$ be the volumes remaining in each group.

The key property of the algorithm:

When you look at $R_A$ and $R_B$ in binary, if $R_A \ne R_B$ and $R_A \neq 0$, then the ones (or set bits) in $R_A$ all are to the right of the ones in $R_B$.

Let $b$ be the position of left most bit in $B$.

Now suppose the algorithm is adding a piece $2^{-c}$. Now we have that $2^{-c} \le R_A + R_B \lt 2^{-b} + 2^{-(b+1)} + \dots = 2^{-(b-1)}$.

Thus if we cannot add the piece to $A$, we can add it to $B$, and still maintain the property of the bits of $R_B$ being to the left of $R_A$. This property stops holding when $R_A = 0$.

Wednesday, December 10, 2014

Solution to monochromatic equilateral triangle puzzle

This is a solution to the math puzzle posted earlier.

We will post a solution to the variant (which also solves the main puzzle).

The problem:

Each point of 2D plane is coloured either black or white. Given three positive angles $\alpha + \beta + \gamma = 180^{\circ}$, show that there are there points $A,B,C$ of the same colour such that the triangle formed by those three has the angles $\alpha, \beta, \gamma$.

Solution

The solution is quite similar to the one posted in the comments by 226.

First we show that there are three collinear points $X,Y,Z$ which are coloured the same, and $Y$ is the midpoint of $X$ and $Z$.

Assume that is not true.

Consider two points which are coloured the same (say black, wlog). Say they are $(0,0)$ and $(2a, 0)$.

Now $(a,0)$, $(-2a, 0)$ and $(4a, 0)$ must be coloured white. These three points satisfy the requirement.

Say $X,Y,Z$ are coloured black.

Let $\gamma = \max \{\alpha, \beta, \gamma\}$

Let $P,Q$ be such that $\angle{YXP} = \angle{ZYQ} = \alpha$ and $\angle{XYP} = \angle{YZQ} = \beta$. Both $\triangle{XYP}$ and $\triangle{YZQ}$ have the angles $\alpha, \beta, \gamma$.

Ths $P$ and $Q$ must both be coloured white.

Now consider point $R$ such that $\angle{QPR} = \angle{ZXR} = \alpha$ and $\angle {PQR} = \angle{XZR} = \beta$

Triangle $PQR$ also has the given angles, and so $R$ must be black. But $\triangle{XZR}$ also has the given angles, and all vertices are black.

Basically, $XZR$ is an $\alpha, \beta, \gamma$ triangle, and $P,Q,Y$ are the midpoints of the sides of $\triangle{XZR}$.

Sunday, December 7, 2014

Best play for making 3NT

I don't remember the source of this hand. I had posted this on bridgebase forums a few years back.

Playing Rubber Bridge, you reach 3NT as South. West leads the HQ and you see:

Rubber
None 
 Dummy
♠ AJT9
♥ AK
♦ K32
♣ Q932

   


 You
♠ KQ8
♥ 432
♦ Q54
♣ AJ74

How will you play?

[Please feel free to comment with your line.]

Solution [Added Dec 13th 2014]

You have 6 tricks in the majors and need three from the minors.

If clubs are 3-2 you can get 3 tricks from the clubs. But if they are 4-1 or 5-0, you can get 3 tricks if LHO holds the club length, by playing a club to the J (and later the CA and then club to 9).

The problem occurs when RHO holds the club length: you can only get two tricks from the clubs and would need a trick from diamonds.

You only have a single heart stopper left after the opening lead. If you go out once in clubs, a heart will come back and you cannot go out in diamonds now.

The solution to this is to play the CA, then play a club to the J from dummy!

If clubs are 3-2 or LHO has the length, you make 3 club tricks.

If RHO has the length, he cannot go up with the K (otherwise you have 3 club tricks). Once you win the J, you shift to diamonds for your ninth trick.

A 100% play.


Friday, December 5, 2014

Online splitting a cake, algorithm puzzle

You want to evenly split a cake of volume one between two people, say $A$ and $B$, so that each gets the same volume of cake.

Problem is, there is another person, $C$, who has already split the cake into a finite number of pieces, each piece being of a volume which is a negative power of two: of the form $\dfrac{1}{2^k}$ for some integer $k \gt 0$. The pieces need not have the same volume and you could have multiple pieces with the same volume. For example, one such split could be $\{\frac{1}{8}, \frac{1}{8}, \frac{1}{4}, \frac{1}{2}\}$.

$C$ is also holding the cake hostage, and will only give you one piece at a time (in some random order), on the condition that you immediately make a decision who ($A$ or $B$) to give the piece to. You cannot revisit that piece later.

Can you think of an algorithm which will help split the cake equally between $A$ and $B$ in this scenario? Just an algorithm won't do, you need to prove that it works too.

[For the reason why it is called online, read this]

[Solution]

Wednesday, December 3, 2014

Monochromatic Equilateral Triangle, IMO problem

This problem appeared in the International Math Olympiad (IMO) in the 1970/80s.

Each point of the 2D plane, is coloured either black or white. Show that there are three points $A,B,C$ which are of the same colour, and form the vertices of an equilateral triangle.

In other words, there is a monochromatic equilateral triangle, no matter how you colour each point of the plane, with one of two colours.

A variant:

Given three positive angles $\alpha + \beta + \gamma = 180^{\circ}$, show that there is a monochromatic triangle with those angles.

[Solution]

Monday, December 1, 2014

Solution to find the three missing numbers

The puzzle (posted earlier):

You have an array of $2n+3$ positive integers, such that each element appears exactly twice in the array, except for three of them (say $a,b,c$) which appear exactly once.

Can you give an $O(n)$ time and $O(1)$ space (assuming RAM model) algorithm to find out what the three unique integers $a,b,c$ are?

Solution

If we had just one number missing, this would be the classic puzzle whose solution is to XOR (bitwise exclusive or, denoted $\oplus$) all the numbers. The result will be the unique number.

A similar solution works in the two unique case (missing $a,b$), where you XOR all the number together, and use a set bit position in the result (which is $a \oplus b$) to differentiate between the two unique numbers by making another pass and bucketing based on that bit. [See Collins' comments on the question post for more details.]

When you try to apply that to the three unique case, we compute $S = a \oplus b \oplus c$, but this might well be $0$. Even if some bit of $S$ was set to $1$, the corresponding bits of $a,b,c$ could all be $1$ and we cannot be sure of using that position to distinguish one of them.

But, consider this: If $S$ differed from $a$ at some bit position, then that bit position could be used as a distinguishing bit for $a,b,c$. Because if $a,b,c$ were all the same at that position, then $S$ would be too, and cannot differ from $a$. $S$ will always differ from some bit of $a$ as otherwise we will $S = a$ and thus $b = c$.

But, we don't really know what $a,b,c$ are, to find out a differing bit.

That does not matter though, if we consider the smallest position where they might differ.

If $f(x,y)$ is the smallest bit position (rightmost bit position being $0$) where $x$ and $y$ differ, then we cannot have that $f(S,a) = f(S,b) = f(S,c)$, as otherwise $a,b,c$ would agree at that position and thus would not differ from $S$ at that position. [Note that $f(x,y)$ can be computed in $O(1)$ time and space by using the classic bithack: $x \& (x-1)$.]

Thus the algorithm becomes:

Compute $S = a \oplus b \oplus c$ by doing an XOR of all $a_i$.

Now make another pass through the array and compute the XOR $T$ of all $\displaystyle 2^{f(S, a_i)}$, where $a_i$ are the elements of the array.

Note that $\displaystyle 2^{f(S,a_i)}$ can be computed in $O(1)$ time, and would fit in the underlying register (so $O(1)$ space). We also ignore $a_i$ for which $S = a_i$.

Now, $T$ cannot be $0$ as it is the bitwise XOR of three powers of $2$. Thus, a set bit of $T$ can now be used to distinguish one of $a,b,c$, and we can then fall back to the two unique case to find the other two.

Friday, November 28, 2014

Solution to integer part of fourth root reciprocals

This is a solution to the puzzle posted earlier.

The problem:

What is the integer part of
$$1 + \frac{1}{\sqrt[4]{2}} + \frac{1}{\sqrt[4]{3}} + \dots + \frac{1}{\sqrt[4]{10000}} $$
i.e. the integer part of
$$ \sum_{k=1}^{10000} \frac{1}{\sqrt[4]{k}} $$

Solution

The typical way to approach this problem is to approximate the sum by an integral and find appropriate upper and lower bounds.

We will essentially do the same, but presented differently.

Consider the function $\displaystyle f(x) = \frac{4x^{3/4}}{3}$. The derivative of $f$ is $\displaystyle f'(x) = \frac{1}{\sqrt[4]{x}}$

Now using the mean value theorem, and the fact that $\frac{1}{\sqrt[4]{x}}$ is decreasing, we have the following:
$$\frac{1}{\sqrt[4]{k+1}} \lt f(k+1) - f(k) \lt \frac{1}{\sqrt[4]{k}} \quad \quad (1)$$
Using the left side of the inequality, and adding from $k=1$ to $9999$ we get
$$ \sum_{k=2}^{10000} \frac{1}{\sqrt[4]{k}} \lt f(10000) - f(1) = \frac{4}{3}(10^3 - 1) = 1332$$
Thus adding $1$ to both sides,
$$ \sum_{k=1}^{10000} \frac{1}{\sqrt[4]{k}} \lt 1333$$
Using the right side of $(1)$, and adding from $k=1$ to $9999$ we get

$$ \sum_{k=1}^{9999} \frac{1}{\sqrt[4]{k}} \gt f(10000) - f(1) = 1332$$
Thus adding $\frac{1}{\sqrt[4]{10000}} = \frac{1}{10}$ to both sides,
$$ \sum_{k=1}^{10000} \frac{1}{\sqrt[4]{k}} \gt 1332 + \frac{1}{10}$$
Thus the integer part is $1332$.

Thursday, November 27, 2014

Find the missed line (bridge hand)

This is a hand from the book "Beaten by the Masters", by David Bird.

It seems like the author missed a line which ensures the contract. Can you find it?

[It is possible that the missing of the line was intentional, based on the character that plays it.]

IMPS
N/S 
 Dummy
♠ Q74
♥ A4
♦ AK7
♣ AQ932




 You
♠ AKT962
♥ J98
♦ -
♣ K865

W N E S
1S
4D4NT5D6S
P7Sallpass

West leads the DQ.

[Please feel free to comment with your line.]


Solution [added Dec 3rd 2014]

The spade spots are such that you can always get 6 tricks. Add to that one heart and two diamonds: requiring you to get 4 club tricks.

It is tempting to throw the heart losers on the diamonds, but you will have a problem if clubs are 4-0, and will need a squeeze of some kind. [That is the line taken by the character in the book.]

Note that you need only four club tricks, not five. To cater to the 4-0 break, you win the DA and make the key play: throw a club from hand!

Now you draw trump by playing spade to A, and finessing an opponent for Jack if the other shows out. (Coming back to hand with a diamond ruff if needed).

Now play AKQ of clubs and ruff a club, making the fifth club good, irrespective of the club split. This fifth club is your fourth club trick. This club and the DK will take care of the two heart losers.

Tuesday, November 25, 2014

Find the three missing numbers. Algorithm puzzle.


I will get straight to the puzzle.

You have an array of $2n+3$ positive integers, such that each element appears exactly twice in the array, except for three of them (say $a,b,c$) which appear exactly once.

Can you give an $O(n)$ time and $O(1)$ space (assuming RAM model) algorithm to find out what the three unique integers $a,b,c$ are?


An easier version: Exactly two appear once in array of $2n+2$.
Easier than that: Exactly one appears once in array of $2n+1$.


[Please feel free to comment with your solution to any version of the problem]

[Solution]

Monday, November 24, 2014

Integer part of fourth root reciprocal sums

A quick to state puzzle:

If

$$S = 1 + \frac{1}{\sqrt[4]{2}} + \frac{1}{\sqrt[4]{3}} + \dots + \frac{1}{\sqrt[4]{10000}} $$

what is the integer part of $S$?

i.e. what is the integer part of

$$\sum_{k=1}^{10000} \frac{1}{k^{1/4}} $$


(integer part of $x$ = largest integer $\le x$)

[Solution]

Friday, November 21, 2014

Solution to only the twain shall meet geometry puzzle

This is a solution to the geometry puzzle about lines posted earlier.

A brief description of the problem:

Given a set $S$ of finite number lines in the 2D plane, no two parallel, and not all concurrent, show that there is a point through which only two lines of $S$ pass (hence the title).

Solution

Since no two lines are parallel, and not all are concurrent, there is at least one triple of lines which forms a non-degenerate triangle.

Of all such triplets, consider the lines which form a triangle of the least area. The claim is that one of the vertices of this triangle satisfies the requirement!

[Sorry, no figures yet, so it might help to draw it out]

Suppose not, then if the triangle was $\triangle ABC$, then there are lines passing through $A,B,C$ such that they form a bigger triangle, $\triangle DEF$, with each of $A,B,C$ lying on different sides of $\triangle DEF$ and $\triangle ABC$, say $A$ is on side $DE$ (between $D$ and $E$), B is on side $DF$ (between $D$ and $F$) and $C$ is on side $EF$ (between $E$ and $F$).

We consider two cases:

1) $A$ is closer to $D$ than $E$ (possibly equidistant from both points). $B$ is closer to $D$ than $F$. Then we must have that the area of $\triangle ABC$ lies between areas of $\triangle ABE$ and $\triangle ABF$, say area of $\triangle ABE$ is smaller. This we can see, by drawing lines parallel to $AB$ through $E$ and through $F$, and considering the altitude lengths.

Since $A$ is closer to $D$ than $E$, we must have that area of $\triangle DAB \lt$ area of $\triangle ABE$, and thus contradicting the fact that $\triangle ABC$ has the least area.

2) $A$ is closer to $D$ than $E$ (possibly equidistant) and $B$ is closer to $F$ than $D$, and $C$ is closer to $E$ than $F$.

In this case, we can move $C$ to the midpoint of $EF$ and $B$ to the midpoint of $DF$ and decrease the area of $\triangle ABC$. This we can see by drawing lines parallel to $AB$ through $C$ and the midpoint $M$ of $EF$, and lines parallel to $MA$ through $B$ and $M'$, the midpoint of $DF$ (and considering the altitude lengths).

The resulting area is exactly one-fourth the area of $\triangle{DEF}$, and hence area of $\triangle ABC$ is more than the average of the sum of triangles $ABC, DAB, EBC, FAB$ and thus there must be a triangle of lesser area.

The above two cases cover all the possibilities, so we are done.

Futher reading

The classic problem I was referring to is the Sylvester-Gallai problem, which is the dual of this problem, by considering the polar/pole version.

A different proof of the claim that $\triangle ABC$ is not the least can also be found here (Theorem 3.1.2 on pages 20-22).

More information about the Sylvester-Gallai theorem, including some nice history can be found here and here.

Wednesday, November 19, 2014

Solution to the C programming puzzles

There were the two puzzles (posted earlier).

The first one:

Write a method in C, which will print ";", but does not use any semi-colons anywhere. Assume you have printf available.


We can do a print of a semi-colon, using the ascii value, but it does not end there... C programs use semi-colons as statement separators. If statements don't however, and so the code will look like this:



void print() {
  if (printf("%c", 59)) {}
}




The second one:

Write a C program to print "hello world!" 2014 times. The catch is, it must fit inside an 80x25 page and must not use the characters f,o,w,?,&,| (last three are question mark, ampersand and pipe). Assume you have printf available (and don't need to #include the header).

This one is more difficult. The printing is the easy part (and so we assumed we could use printf etc). The size limits do not allow us to write the print 2014 times (and that is a silly solution, anyway). #define etc macro tricks to do that are clever, but still silly :-)

The difficult part is that not using those characters does not allow us to use if statements (or conditionals), for and while loops. There might still be ways to loop and have conditionals, but that is probably weird C territory [that will still be a valid solution to the puzzle].

One way to do things multiple times without using loops is using recursion. But, since we cannot use if, we need a different way to stop the recursion.

Even though we cannot use if, we are allowed (=), so we can at least tell when we have recursed 2014 times, count == 2014 will be 1 or 0, depending on count.

In order to use that, we use function pointers! If count == 2014 is 0, we recurse, otherwise we return. We do this by calling the appropriate function, using the function pointers stored in an array a. a[0] will be a pointer to the recursive function, a[1] will be a pointer to the function which stops the recursion (basically returns).

The code will look something like this:


int stop(int n){}

int print(int n){
  int (*a[2])(int) = { print, stop };
  printf("hell%c %c%crld!",111,119 ,111);
  n++;
  a[n==2014](n);
}

int main(){
  print(0);
}


The code above can be made better by counting down and checking against 0 (instead of 2014), that way we don't have to hardcode 2014.

One could also use integer division, instead of ==. count/2014 is 0 or 1 depending on whether 0 <= count < 2014 etc.

That will get rid of the use of any conditional, including the equality check.

Tuesday, November 18, 2014

A 100% 7NT hand by Fred Gitelman.

This was a hand posted by Fred Gitelman on the bridgebase forums a couple of years ago.

[Apparently, the source is Micheal Rosenberg's book, Bridge, Zia and me]

You are South, in 7NT, and get a club lead.

IMPS
None 
 North
♠ KQT9
♥ AJT9
♦ KQT9
♣ 2

 


 South
♠ A876
♥ K2
♦ A32
♣ AKQJ


Can you guarantee the contract?

Please feel free to add your solution in the comments.

Solution (added November 22nd 2014).

This is a strange hand, for which only counting is enough. You do need to time it correctly to obtain the count.

The basic idea is to count the heart+diamond+clubs to get information on how to play the spades (you can finesse either opponent for the Jack, or play for the drop).

So one line is to win the club, spade to K, cash Heart A in dummy, three rounds of diamonds ending in hand.

If diamonds are not 3-3 (otherwise you have 13 tricks), you know who has the diamond length.

Now you cash clubs throwing the hearts. You now get a count of the clubs and diamonds.

If the DJ hasn't appeared yet, you cash the HK and throw the diamond from dummy.

At this point, the card played by the opponent with the DJ will tell you exactly how to play the spades! Try it out.

Friday, November 14, 2014

Only the twain shall meet, geometry puzzle.

This is a classic problem, in disguise. That problem was open for 20+ years, so if you solve this problem without using the classic result, pat yourself on the back!

You are given a finite set of lines, $S$ in the 2D plane, no two lines of which are parallel and not all are concurrent.

Show that there are two lines (call them $p$ and $q$) such that no other line in $S$ passes through the intersection point of $p$ and $q$.

i.e. among all the points of intersections formed by the lines in $S$, there is a point through which only two lines of $S$ meet.

[Solution]

Wednesday, November 12, 2014

A couple of C programming puzzles

Two puzzles in one post.

The first one is a quickie.

Write a method in C, which will print ";", but does not use any semi-colons anywhere. Assume you have printf available.


The second one is strange.

Write a C program to print "hello world!" 2014 times. The catch is, it must fit inside an 80x25 page and must not use the characters f,o,w,?,&,| (last three are question mark, ampersand and pipe). Assume you have printf available (and don't need to #include the header).


[Please feel free to comment with your solutions]

[One solution]

Monday, November 10, 2014

Solution to sort each column, algorithm puzzle

[This is a solution to the sort each column, algorithm puzzle posted earlier]

A brief description of the problem:

Given a matrix of integers, by permuting each row separately (with possibly different permutations), can each column of the matrix be sorted (in ascending order, with smallest in row one)? Give a polynomial time algorithm for it.

Solution

Consider the case of a $2\times n$ matrix, which has two rows and $n$ columns.

Suppose it was possible to sort the columns by permuting the rows.

The claim is that, the columns remain sorted, even after we sort the rows!

For example, this is a matrix in which the columns are sorted:

$\begin{bmatrix}4&7&8&6\\5&100&200&10\end{bmatrix}$

Now, if we sort each row individually we get

$\begin{bmatrix}4&6&7&8\\5&10&100&200\end{bmatrix}$

The columns are still sorted!

The proof is actually not difficult:

Suppose $a \le b$ and $c \le d$, then we have that:

$\min\{a,c\} \le \min\{b,d\}$ and $\max\{a,c\} \le \max\{b,d\}$.

Thus
$\begin{bmatrix}\dots&a&\dots&c&\dots\\\dots&b&\dots&d&\dots\end{bmatrix}$

can be replaced by

 $\begin{bmatrix}\dots&\min\{a,c\}&\dots&\max\{a,c\}&\dots\\\dots&\min\{b,d\}&\dots&\max\{b,d\}&\dots\end{bmatrix}$

and still have the columns sorted.

Thus if the columns are sortable, they are sortable by sorting the individual rows (and vice-versa).

So the algorithm is simple: sort each row, and then check if the columns are sorted.

Friday, November 7, 2014

Solution to separating circle puzzle

[This is a solution to the Separating Circle, geometry puzzle posted earlier]

The problem:

Given $2n+3$ points in the general position (no three collinear, no four concyclic) in the 2D plane, show that there are three points among those, such that the circle through those points has exactly $n$ of the remaining $2n$ points inside the circle (and exactly $n$ outside).

Solution

We use the following property of circles:

If $AB$ is a chord of a circle, and $P$ and $Q$ are any two points on the major (or minor) arc of a circle, then $\angle{APB} = \angle{AQB}$, i.e. the arc of the circle is the locus of points $X$ such that the angle subtended by $AB$ at $X$ is constant.

We won't use this other fact, but just mentioning it for clarity: if $R$ is a point on the opposite arc as $P$ and $Q$ then $\angle{ARB} = 180^{\circ} - \angle{APB}$.

We won't prove these facts here, as they are easily available in textbooks/online.

Now, we can show that, if $S$ is a point inside the circle, on the same side of $A,B$ as $P$ and $Q$, then $\angle{ASB} \gt \angle{APB}$.

Proof: Line through $A$ and $S$ cuts the circle at S'. If $S$ is inside, then $\angle{ASB} = \angle{AS'B} + \angle{SBS'} = \angle{APB} + \angle{SBS'}$

Similarly, if $S$ is outside, on the same side of $AB$ as $P$ and $Q$, then $\angle{ASB} \lt \angle{APB}$.

So, if we have a circle through $A,B,C$ which separates the points, and say all the points lie to the same side of $A,B$, then the angles of the other points will be such that exactly $n$ are smaller than $\angle{ACB}$ and exactly $n$ are bigger.

This gives us a constructive proof:

Take the convex hull of all the points. Since they are not all collinear, the convex hull will have at least three sides. Pick one side, say $AB$. Now all the other points lie on the same side as $AB$.

Now, for each of the remaining $2n+1$ points, $P_i$, compute the angle $\angle{AP_{i}B}$. Since no four are concyclic, all these angles will be distinct, and we can sort them in ascending order, say: $\angle{AP_1B} \lt \angle{AP_2B} \lt \dots \lt \angle{AP_nB} \lt \angle{AP_{n+1}B} \lt \dots \lt \angle{AP_{2n+1}B}$.

Pick $C = P_{n+1}$.

The circle through $A,B,C$ will have $P_1, P_2, \dots, P_n$ outside, and $P_{n+2}, \dots, P_{2n+1}$ inside.

This generalizes to any combination of $n\pm k$ and $ n \mp k$ inside/outside.

Wednesday, November 5, 2014

Masterpieces of Declarer Play #67

This is hand #67 from the book, Masterpieces of Declarer Play, by Julian Pottage. This book has some very nice hands.

You are South, and end up in 4H. West leads the club 9 (opponents lead low from xxx).

IMPS
None 
 Dummy
♠ AT
♥ Kx
♦ AKxxxx
♣ Qxx

   


 You
♠ J
♥ AQJTxx
♦ Jx
♣ xxxx

W N E S
P2H
P4Hallpass


RHO overtakes the C9 lead with the T, and returns a spade, J, K from LHO and won in the dummy with the A.

How will you play?

[Please feel free to comment with your solution]



Solution (posted on 12th November 2014)


The intended solution is as follows:

LHO seems to have led from 9(x) of clubs. So RHO has the AKJT(x). RHO also seems to hold the spade Q (weak inference). Since RHO passed initially, it is likely that LHO has the DQ.

Now if we play a club (key play #1) after winning the spade Ace, threatening to ruff the fourth with the HK, RHO will have to play back a heart. So you play a club, and on the expected trump return, draw trumps.

Now for key play #2: advance the DJ.

LHO has to cover this, which you duck!

LHO does not have any more clubs, and if diamonds are 3-2, you can now make 10 tricks.

[See the comments for another nice line by Martin]

Monday, November 3, 2014

Sort each column, algorithm puzzle.

[This algorithm puzzle was inspired by some Russian math contest problem I saw a long time back]

You have an $n \times n$ matrix of integers which you want to sort by columns: each column must be individually sorted in ascending order, the first row containing the smallest elements of each column.

There is a problem though, the only operation you are allowed to perform on the matrix, is to permute the elements of an individual row. That is you can pick one row, then permute the elements within that row. Then pick another row, permute the elements within that row etc. Each row could be permuted differently.

For example:

Say you are given the matrix:

$\begin{bmatrix}4&5&6\\1&3&2\\9&7&8\end{bmatrix}$

No matter how you permute the elements of the rows, the columns cannot be sorted.

If the matrix was

$\begin{bmatrix}3&1&7\\8&6&5\\9&7&8\end{bmatrix}$

Then you could shuffle just the first row (swap $3$ and $7$) so that it now looks like

$\begin{bmatrix}7&1&3\\8&6&5\\9&7&8\end{bmatrix}$

The columns are sorted: $[7,8,9], [1,6,7], [3,5,8]$

The puzzle is to come up with a polynomial time algorithm, which given the $n\times n$ matrix, tells if you could shuffle some rows (individually) so that the columns end up being sorted. The algorithm just has to give a Yes/No answer and not the actual permutations of the rows.

[Solution]

Thursday, October 30, 2014

Separating circle geometry puzzle

[This puzzle was given to me by Arvind Hariharan a long time back]

The puzzle is easy to state:

Given $2n+3$ points in the general position (no three collinear, no four concyclic) in the 2D plane, show that there are three points among those, such that the circle through those points has exactly $n$ of the remaining $2n$ points inside the circle (and exactly $n$ outside).

[Solution]

Tuesday, October 28, 2014

Playing Safe at Matchpoints

[This hand appeared in a local club game a while back. Most of the bidding is lost, but the relevant parts are probably there]

You are South, and end up in a contract of 4S, after RHO had shown 6 clubs.

LHO leads the club Ten and you see the following:

MPS
None 
 North
♠ T9
♥ 7542
♦ 98742
♣ A3

    


 South
♠ AK86432
♥ AK
♦ 5
♣ K72


How will you play?

[Please think about it before reading on]

Since this is MPs, you probably should be thinking of overtricks.

If trumps are 2-2, you can draw trumps, and come to 11 tricks, losing a club and a diamond.

If spades divide 3-1, drawing trumps will only give you ten tricks: you will lose a spade, a diamond and a club.

There is one way to cater to 3-1 spades: play one round of trumps, and then try to ruff a club. If LHO ruffs from 3, he will be ruffing your club loser with a natural trump trick, and you will still come to 11 tricks. This line will also give you 11 tricks if trumps are 2-2.

So win the CA, SA, and try to ruff a club, right?

No! There is still a problem.

Imagine LHO has QJx of spades. Now if you play one round of trump before going for the club ruff, LHO can ruff the third club with the J, play a diamond to RHO, and another club from RHO now promotes the spade Q, holding you to 10 tricks.

The solution to this is the scissors coup: cut opponent's communication. You don't want LHO to be able to put RHO in after the third round of clubs is played.

So after winning the CA on trick one, play a diamond from dummy immediately! RHO can win and return a club/heart.

You now draw one round of trumps, and go for the club ruff, making 11 tricks even when trumps break 3-1.

Not always do you need to make multiple "safety plays" [safety play being used loosely] at Matchpoints.

Friday, October 24, 2014

Stairs, Fibonacci numbers and O(log n) algorithms.

Introduction

You probably have heard of Fibonacci numbers.

They are the numbers in the sequence $1,1,2,3,5,8,13,\dots$ where each number is the sum of previous two numbers. So the next number after $13$ is $8+13=21$, and then $13+21=34$ and so on.

A combinatorial way of looking at them is the following:

Suppose you wanted to go up stairs having n steps, going up 1 or 2 at time. How many ways can you do this?

For instance, if there were 3 steps, you could go up as follows

$1,1,1$
$1,2$
$2,1$

where $1,2$ means go up one step, then go up two steps.

That the total number is a Fibonacci number is easy to see. If the number for $n$ steps was $F_n$, then the first number of steps is either one or two, and thus $F_n = F_{n-1} + F_{n-2}$.

We get $F_0 = 1, F_1 = 1, F_2 = 2, F_3 = 3, F_4 = 5, \dots$.

This combinatorial approach is a useful way [among many other approaches, like the matrix based approach] of looking at Fibonacci numbers. For instance, try proving the following identity combinatorially:

$$ \binom{n}{0}F_0 + \binom{n}{1}F_1 + \dots + \binom{n}{n}F_n = F_{2n} $$

($\binom{n}{k}$ is the binomial coefficient: $n$ choose $k$)

We will use this combinatorial approach to demonstrate an $O(\log n)$ arithmetic operations algorithm to compute the $n^{th}$ Fibonacci number. [The matrix approach also gives an $O(\log n)$ algorithm]

Note, we are talking about $O(\log n)$ arithmetic operations, rather than $O(\log n)$ time. This is because the size of the Fibonacci numbers becomes substantial. Since $F_n \sim \varphi^n$, $\varphi$ being the golden ratio, $F_n$ will be $\Theta(n)$ bits in size.

Adding $F_n$ and $F_n$ will take $\Theta(n)$ time, and multiplying $F_n$ and $F_n$ would typically be slower than that, its run-time depending on the multiplication algorithm used.

[Please stop reading if you want to try coming up with an algorithm yourself]

An $O(\log n)$ algorithm

So, we want to compute $F_n$, the number of ways to climb a stair of $n$ steps, going up one or two at a time. Assume for the moment, that you don't know that $F_n$ is a Fibonacci number.

To get an $O(\log n)$ algorithm, an effective technique is to reduce the problem in half (e.g: binary search).

So, if we could compute $F_n$ in terms of $F_{n/2}$ (or similar) we would have an $O(\log n)$ algorithm.

So let us try to compute $F_{2n}$ in terms of $F_n$.

Of all the ways to go up $2n$ steps, each possibility will have us end up at step $n-1$ or $n$ at some intermediate stage.

So we count the total number by splitting into two: possibilities that go through step $n-1$ but not step $n$, and possibilities that go through step $n$.

We get the following identity:

$$F_{2n} = F_{n-1}^2 + F_{n}^2 $$

And similarly:

$$ F_{2n+1} = F_{n}F_{n-1} + F_{n+1}F_{n}$$

Thus we can compute $F_{2n}$ if we knew $F_{n-1}$ and $F_{n}$, and we could compute $F_{2n+1}$ if we knew $F_{n-1}, F_{n}$ and $F_{n+1}$.

A naive recursive implementation of these identities would give an algorithm which requires $\Omega(n)$ arithmetic operations.

A common way to speed up such recursive algorithms is to use memoization: cache the previously computed values and use those instead of recomputing them.

As is frequently the case, using memoization gives us an exponential speedup, leading to an $O(\log n)$ arithmetic operations algorithm!

To prove that, consider what values we need, to compute the four Fibonacci numbers $F_{2n+1}, F_{2n+2}, F_{2n+3}, F_{2n+4}$:

$$F_{2n+1}, F_{2n+2}, F_{2n+3}, F_{2n+4} \to F_{n-1}, F_{n}, F_{n+1}, F_{n+2}\quad (1)$$

And to compute $F_{2n}, F_{2n+1}, F_{2n+2}, F_{2n+3}$:

$$F_{2n}, F_{2n+1}, F_{2n+2}, F_{2n+3} \to F_{n-1}, F_{n}, F_{n+1}, F_{n+2}\quad(2)$$

Thus starting with $F_{2n}$ (or $F_{2n+1}$) we can see that ultimately, we need to only compute a total of $O(\log n)$ such $F_i$.

For example, starting with $F_{8n+4}$:

$$F_{8n+4} \to F_{4n+1}, F_{4n+2} \to F_{2n-1}, F_{2n}, F_{2n+1} \to F_{n-2}, F_{n-1}, F_{n}, F_{n+1}$$

To compute $F_{8n+4}$, we need to compute two Fibonacci numbers of half the size ($F_{4n+1}, F_{4n+2}$). To compute those two, we need to compute three more of half their size ($F_{2n-1}, F_{2n}, F_{2n+1}$), and then four more. Based on $(1)$ and $(2)$ above, the amount of new numbers added to compute then stays at four, and never increases. At each step we halve the size, and so the total number of numbers is $O(\log n)$.

The number of arithmetic operations associated with computing $F_i$ is $O(1)$, if we use a memoization table, and so the whole algorithm will be using $O(\log n)$ arithmetic operations.

We can get rid of the memoization table by trying to compute the tuple of 4 elements instead: $T_n = (F_{n}, F_{n+1}, F_{n+2}, F_{n+3})$ and noticing that $T_n$ can directly be computed using $T_{\lfloor n/2 \rfloor -1}$.

[If you look at the matrix approach, you can view it as computing a tuple of three elements]

By massaging the identities a bit more, and using $F_{n+2} = F_{n+1} + F_{n}$, we can in fact, reduce the size of the tuple to two.

Further optimizations can be done, to reduce the number of multiplications (as they are slower than additions for large sized integers). See the GNU gmp Fibonacci implementation which actually does that by using similar identities to what we had earlier.

Conclusion

We looked at a combinatorial way of looking at Fibonacci numbers, and used that to give an $O(\log n)$ arithmetic operations algorithm.

This algorithm naturally falls out by applying two basic algorithm techniques: divide and conquer (by halving the input size) and caching (using memoization on the recursive version) and does not require any 'major leaps' (like the matrix approach).

Wednesday, October 22, 2014

Solution to AOSREMPHE

[This is the intended solution to the puzzle-huntish puzzle AOSREMPHE posted earlier]

The puzzle was just this image:


Solution


If you looked at the hint, it stated "AOSREMPHE is an anagram".

One such anagram is SEMAPHORE.

SEMAPHORE is a reference to flag semaphore, commonly used in such puzzles.

Flag Semaphore is used by navies as a way to encode the alphabet to help two ships communicate visually.

For instance, A encodes as



If you look at the first triangle, the angle corresponds to the letter A!

A list of the flag encodings is in the image here:



If you decode the puzzle image, you see that you will get ALTERINGS, which is the same permutation of TRIANGLES, as AOSREMPHE is of SEMAPHORE (ALTERINGS is also an anagram hint a-la cryptic crosswords).

So the intended answer is TRIANGLES.

[The image does contain a bunch of triangles :-)]

Tuesday, October 21, 2014

Solution to Last 1000 digits puzzle

[This is a solution to the last 1000 digits puzzle earlier.]

A brief description of the problem:

What are the last 1000 digits of $$1 + 50 + 50^2 + \dots + 50^{999}$$ when written in base-10? A reasonably easy to compute (by a human) description is enough.

Solution

The solution relies on the following fact:

If $a$ is relatively prime to $49$, then $a^{42}- 1$ is divisible by $49$: by applying Euler's theorem, as $\varphi(49) = 42$.

Now, the last $1000$ digits of $$1 + 50 + 50^2 + \dots + 50^{999}$$ are the same as the last $1000$ digits of $$S  = 1 + 50 + 50^2 + \dots + 50^{1007} = \frac{50^{1008} -1}{49}  = $$ $$\frac{(5^{1008}-1)10^{1008} + (10^{1008}-1)}{49}$$


Since $1008$ is divisible by $42$, $5^{1008}-1$ is divisible by $49$.

Thus

$$ S = K*10^{1008} + \frac{10^{1008}-1}{49}$$

Thus the last $1000$ digits of $S$ are same as the last $1000$ digits of $$\frac{10^{1008}-1}{49}$$ which are the same as the last $1000$ digits of $$\left\lfloor\frac{10^{1008}}{49}\right\rfloor$$.

Since $\dfrac{1}{49}$ is a repeating decimal with period $42$ , the last $1000$ digits can easily be computed:  $204081632653061224489795918367346938775510$ repeated.

Monday, October 20, 2014

Timing for all the chances [bridge hand]

[This is a hand from the 2000 Indian Nationals held in Baroda, and was given to me by Rajendra Gokhale.]

You are South and with no opposing bidding, you reach a small slam in hearts.

West leads the DK.

You see:
IMPS
None 
 North
♠ A73
♥ T73
♦ 7643
♣ Q64

    


 South
♠ KJ2
♥ AKQJ4
♦ J
♣ AKJT

West wins the trick and continues with the DQ.

How will you play?

[Please think about it before reading on.]



You have 2 spades, 5 hearts and 4 clubs. Where is the 12th trick going to come from?

If the hearts are 4-1, you probably have to rely on the spade finesse (a diamond-spade squeeze seems unlikely from the initial two tricks).

One option with hearts 3-2, is to ruff another diamond in hand and try for a diamond-spade squeeze/guess for finesse in the end position.

When hearts are 3-2 one could also think of trying for a dummy reversal: ruff 3 diamonds in hand, giving 6 heart tricks.

Opponents have been kind enough to lead the second round of diamonds, but you are still an entry short to dummy. You need the heart T to draw the last trump, and cannot use that as entry to ruff the diamonds in hand.

So, besides the heart T, SA and CQ, you need another entry.

Is there some situation where you can get an extra entry to do the dummy reversal?

The heart 7 should give you an idea: what if one opponent holds the heart 98 doubleton? Now you can use the heart Ten as an entry and use the H7 to draw the last trump!

With all these options available, you need to time your play correctly:

Ruff the second diamond with heart A. Play the heart K and the heart 4 to the T. Now you know whether heart 98 is doubleton or not, or whether the hearts are 4-1.

If hearts are 4-1, you just draw trumps, play clubs and rely on the spade finesse/unlikely diamond-spade squeeze.

If hearts are 3-2 with 98 doubleton, you can do a dummy reversal.

If hearts are 3-2 without the 98 doubleton, you can ruff a diamond and go for the squeeze/finesse ending.

The exact play to the tricks 2,3,4 is crucial: HA, HK, HT in that order. Deviate from that order, and you might not be able to pick the right play.

On the actual hand, the only chance that let it make was the dummy reversal with the heart 98 doubleton! The finesse and the squeeze don't work.

Friday, October 17, 2014

Solution to Construct the BST algo puzzle.

[This is a solution to the construct the binary search tree algorithm puzzle posted earlier]

A brief description of the puzzle:

If you insert $a_1$, then $a_2$, then $a_3$ and so on till $a_n$ into a binary search tree, with no rebalancing etc, you get a unique tree with $a_1$ as the root, $a_2$ as a child of the root etc.

A naive algorithm to construct the unique tree is $\Omega(n^2)$ in the worst-case.
(e.g: $a_1 \lt a_2 \lt \dots \lt a_n$).

Give an $O(n\log n)$ time algorithm to construct the tree.

We will present three solutions.

Solution 1)

This solution is based on Shyam's idea.

Initially we start with $(-\infty, \infty)$.

When we insert $a_1$ this interval splits into two: $(-\infty, a_1), (a_1, \infty)$. The left interval corresponds to the left sub-tree of $a_1$ and the right interval corresponds to the right sub-tree of $a_1$.

Basically, the binary search tree can be looked at as a collection of disjoint intervals, whose union is $(-\infty, \infty)$ (ignoring the split points).

Each time you insert a new value into a tree, some interval is split into two, around that value.

Now we can maintain the intervals as a red-black tree whose keys are the left end points, and the values are the right endpoints, plus a pointer to a node in the target tree (target tree is the tree which we want to construct). This node in the target tree holds the value which resulted in the creation of that interval.

Given a new value which we need to insert into the target tree, say $a_j$, we look-up the predecessor of $a_j$ in the tree of intervals ($O(\log n)$ time), and can now add the new node at the appropriate place in the target tree, in $O(1)$ time (and update the book-keeping).

Solution 2)

This solution is based on Arvind's idea, and is perhaps essentially the same as Solution 1). It is the simplest, though.

The key observation used in this solution is the following:

When you insert $x$ into a binary search tree, it will either be the right child of it's predecessor among the elements already present in the tree, or will be the left child of it's successor among the elements already present in the tree.

So you maintain a red-black tree along with the target tree. The nodes in the red-black tree maintain pointers to the corresponding node in the target tree, and also the when it was inserted (i.e. for $a_j$ you store $j$).

Now when you are inserting $a_j$, lookup both the successor and predecessor of $a_j$ in the red-black tree.

Say we get $a_p$ and $a_s$ with $a_p \lt a_j \lt a_s$.

Now if $p \lt s$ (predecessor was inserted before), then $a_j$ will be the left left child of $a_s$ in the target tree. If $p \gt s$, then $a_j$ will be the right child of $a_p$ in the target tree.

Solution 3)

This uses a lesser known data-structure called Cartesian Trees.

Given points $$(x_1, y_1), (x_2, y_2), \dots, (x_n, y_n)$$ with $x_1 \lt x_2 \lt \dots \lt x_n$, a cartesian tree of these points is basically a treap (a tree + heap), with the $x_i$ forming the binary search tree values, and $y_i$ from the heap values: i.e. each node of the tree with contain an $(x_i, y_i)$ pair, and when you just look at the $x_i$, the tree will be a binary search tree, and when you just look at the $y_i$, the tree will be a heap.

This tree can be constructed in $O(n)$ time (see the wiki page for details).

Suppose the sorted list of $a_1, \dots, a_n$ is $b_1, \dots, b_n$, with $b_1 \lt b_2 \lt \dots \lt b_n$. Also, suppose $b_k = a_{f(k)}$.

Then we are looking for the Cartesian Tree corresponding to the points $$(b_1, f(1)), (b_2, f(2)), \dots, (b_n, f(n))$$ with the $f(i)$ forming a min-heap.

We can sort $a_i$ in $O(n \log n)$ time, and create the cartesian tree in $O(n)$ time.

Wednesday, October 15, 2014

AOSREMPHE

When I was at Microsoft, I was a part of a team which participated in puzzle hunts held by other Microsofties. The hunt ran over the weekend with people staying up all night solving puzzles!

Only a few teams managed to solve the final meta-puzzle, but it was quite satisfying to solve whatever amount we could solve.

The puzzles were very creative, with the winners of last year usually holding the contest for the current year.

This puzzle is a puzzle in that spirit.

The answer is one word.


[Solution]

Monday, October 13, 2014

Last 1000 digits puzzle

What are the last $1000$ digits of

$$1 + 50 + 50^2 + \dots + 50^{999}$$

when written in base-$10$?

i.e.

What are the last $1000$ digits of

$$ \sum_{k=0}^{999} 50^k$$

Of course, the idea is to find a way to find this manually/mathematically, and only use a calculator/computer if needed.

You don't have to list the $1000$ digits, just some simple, reasonably easy to compute (by a human) description would do too.

[Solution]

Saturday, October 11, 2014

Solution to the two triangles puzzle.

[This is a solution to the two triangles geometry puzzle posted earlier]

The problem, repeated here:

In the figure below (not to scale, forgive the shoddy drawing skills).




$ABC$ is a triangle such that $\angle{BAC} = 60$ and $\angle{ABC} = 25$.

$DEF$ is an isosceles triangle, such that $\angle{EDF} = \angle{EFD}$, and $\angle{DEF} = 10$

(all angles are in degrees).

We also have that $|BC| = |DE|$ ($|XY|$ = length of the segment $XY$)

Show that $2|AC| + |DF| = |AB|$

Solution

Notice that $\angle{FDE} = 85$ and $\angle{ACB} = 95$, and so their sum is $180$.

Since $|BC| = |ED|$, we can position one copy of $\triangle{ABC}$ with $B$ coinciding with $E$ and $C$ coinciding with $D$ to get a bigger triangle.

Another copy of $\triangle{ABC}$, call it $\triangle{A'B'C'}$, can be positioned so that $B'$ coincides with $E$ and $C'$ coincides with $F$.

The result will be an even bigger triangle, $\triangle{EAA'}$ as below (more drawing incompetence):

Placing two copies of ABC along with DEF results in an equilateral triangle.


$\triangle{EAA'}$ is an equilateral triangle, and thus the base of the triangle which is $2|AC| + |DF|$ is same as the other side which is $|AB|$.

Friday, October 10, 2014

A Dream of Genie [bridge hand]

This hand has been stolen from the book Around the world in 80 hands by Zia Mahmood, which itself was stolen from Adventures in Card Play by Ottlik and Kelsey. This hand is so amazing, that I bought the 80 hand book because of this hand! (I already had the Adventures book at that time).

In the book, the chapter is titled "A Dream of Genie".

The story is about 3 bridge players who find a bottle with a genie who claims to be a master bridge player. With the genie making up the fourth, they had enough players to play a few hands of bridge.

This is the very first hand:

IMPS
None 
 North
♠ 83
♥ 963
♦ AKQJ9
♣ Q63
 West
♠ KJ9652
♥ -
♦ 87542
♣ T8

     


 Genie
♠ AQT4
♥ A74
♦ T63
♣ KJ7
 South
♠ 7
♥ KQJT852
♦ -
♣ A9542

W N E S
3S P4S5H
allpass


West leads the spade 2 against the contract of 5H by South, dummy plays the 3 and the genie sitting East, after some considerable thought, plays the 4!, South winning with the 7.

After this trick, the three players stuff the genie back into the bottle and throw him into the sea.

Later they show the hand to Micheal Rosenberg, expecting him to chuckle at the Genie's play, but Micheal Rosenberg calls them idiots and explains:

If East makes the normal plays of winning the spade and returning the suit (any other switch allows declarer access to diamonds), then South can ruff with the heart T, and lead the heart 8 to the dummy's 9. The Genie has to win this, but now any return he makes, declarer gets access to the dummy's winners. Even though East can ruff the 4th diamond, declarer can draw trump (if needed) and play the heart 2 to the heart 3!

If East ducks the first spade, as the Genie did, East avoids the throw-in, as he has a spade exit card when South plays the heart 8 to the heart 9.

Declarer must play the spade 8 at trick one to make it.
 

Wednesday, October 8, 2014

Constructing a Binary Search Tree [algorithm puzzle]

Suppose you are given a sequence of distinct numbers $a_1, a_2, \dots, a_n$.

You can create a unique binary search tree of those numbers by inserting $a_1$, then $a_2$ etc in the order they appear.

$a_1$ becomes the root, if $a_2 \gt a_1$, then it becomes the root of the right sub-tree and so on. Note that the sequence uniquely determines the tree.

For example, if the sequence was $4,5,1,2,3$ the corresponding binary search tree would look like


Tree formed by inserting 4, then 5,1,2,3 in order.

Now suppose you wanted to write a program to create the final binary search tree corresponding to a given insertion order.

A naive solution would be to run the binary search tree insertion algorithm for each element in the sequence to get the final tree. In the worst case, this creation algorithm would be quadratic in the number of elements in the sequence: if the sequence was sorted, for e.g.

This puzzle is about doing the binary search tree construction better.

Can you give an $O(n \log n)$ worst-case time algorithm which will construct the binary search tree of the given insertion sequence of distinct numbers $a_1, a_2, \dots, a_n$? Note that the resulting tree should be the same as the one gotten by the naive algorithm.

(Assume a pointer based tree, with left and right pointers, and if needed, parent pointers)

[Solutions]

Tuesday, October 7, 2014

Solution to Catch the Magical Monkey puzzle

[This is a solution to the catch the magical monkey puzzle posted earlier]

Brief description of the puzzle:

A monkey is moving at constant integer velocity among the integer points.

You can pick a point at any given time and check if the monkey is there. If he is there, you can catch him.

Can you eventually catch the monkey?

Solution

The solution relies on the following fact: $\mathbb{Z}^2$ is countable, and so there is a bijection mapping every ordered pair of integers $(a,b)$ to a natural number $f(a,b)$.

The strategy is to guess that the monkey's position at time $f(a,b)$ is $a + bf(a,b)$, corresponding to a guess of initial position $a$ and velocity $b$.

If the monkey's actual speed is $v$ and initial position was $u$, then we will catch him at time $f(u,v)$

Sunday, October 5, 2014

A property of two triangles, geometry puzzle

[This is a geometry puzzle, solvable by elementary 8th grade geometry, i.e. no trigonometry etc]

In the figure below (not to scale, forgive the shoddy drawing skills).




$ABC$ is a triangle such that $\angle{BAC} = 60$ and $\angle{ABC} = 25$.

$DEF$ is an isosceles triangle, such that $\angle{EDF} = \angle{EFD}$, and $\angle{DEF} = 10$

(all angles are in degrees).

We also have that $|BC| = |DE|$ ($|XY|$ = length of the segment $XY$)

Show that $2|AC| + |DF| = |AB|$

[Solution]

Thursday, October 2, 2014

Be careful at trick one (and two)

[Another hand I had posted to bridgebase forums]

You are South playing teams, and reach a contract of 5D.

West leads the spade 5.

You see:

IMPS
None 
 North
♠ AQ3
♥ Q752
♦ 653
♣ Q72

     


 South
♠ 642
♥ AK
♦ AKQJ98
♣ K3


You have 6 diamonds, 3 hearts, 1 spade and will definitely get a club after knocking out the CA. That is 11 tricks. So what is the problem?

The problem is that your only sure dummy entry is in spades and is in danger of getting knocked out before you can unblock your hearts.

You probably don't want to play the SA at trick one. If you play the Q, East might win the SK and continue spades. If East has both the SK and CA, you will not be able to get to dummy.

Consider what happens when you play low from dummy.

You have the S6 to cover West's card, so East has to win (otherwise you have 11 tricks without needing the HQ).

Now East cannot play spades without giving you a trick.

So play low and relax, right?

Not so fast.

Suppose East wins tricks 1, and returns a club. You have to go up with the K now.

If you play a low club from hand, West will win the CA, and play a spade, knocking out the SA while both hearts and clubs are blocked.

If you go up with the K, you will have the CQ as entry in case West wins. If the CK wins, you have the SA as entry. 

Monday, September 29, 2014

Catch the Magical Monkey puzzle

[This is another one of those puzzles that seem impossible at first]

You live in a one dimensional world, where the unit of time is seconds and everyone is immortal. At time = 0 seconds, a magical monkey appeared at some integer co-ordinate, and is known to be moving at a constant integer speed.

If it was at position x at time $t$ seconds, then it disappears, and then reappears at some position $x + v$ ($v$ could be negative) at time $t+1$ seconds, where it stays for a brief moment, then disappears and reappears at $x+2v$ at $t+2$ seconds and so on.

Both the initial point of appearance, and the speed of the monkey are not known to you, and you have no record of where the monkey has been so far.

You have access to magic too, and can appear at any point of your choosing. If you appear at a certain point the same time as the monkey, you can catch him.

In your world, time progresses linearly, and there is no time travel etc.

Can you catch the monkey in a finite amount of time (assume the current time is some $T \gt 0$)? (i.e. catch him eventually, and not be on a chase forever).

[Solution]

Friday, September 26, 2014

Solution to the "Is the Sum S?" Algorithm Puzzle

[This is a solution to the Is the sum S? algorithm puzzle posted earlier]

A description of the problem:

Given n numbers in the range [-M,M], and a target sum S, also in the range [-M, M], can you figure out in O(n) time, whether those n numbers add up to S, while keeping all your computations within the [-M, M] range? (M is unknown to you). Assume arithmetic operations are O(1).

Solution


Since the numbers are in the range [-M,M], the key observation we use is that adding a positive number to a negative number (or vice versa) will not overflow.

Thus we do the following:

Start with running sum = the negative of the target. Now we try to add the elements of the array to this running sum, hoping to see whether we get a zero in the end.

If the running sum is negative, add a positive number to it. If there are no positive numbers left in the array, then we know we cannot end with a total sum of 0.

If the running sum is positive, add a negative number to it. If there are no negative numbers left in the array, then we know we cannot end with a total sum of 0.

If the running sum is zero, add a positive or negative, does not matter.

Here is what a C++ implementation might look like (untested):

bool has_sum(const std::vector<int>& a, int target) {
  // Technically, the negation is a bug 
  // and overflow is possible here.
  // The range of int in C++ is actually 
  // [-M-1, M], not [-M, M].
  // But, we ignore that...
  int sum = -target;

  std::vector<int> positives;
  std::vector<int> negatives;
  int total = 0;

  // Collect the positive and negative numbers.
  for (auto x : a) {
    if (x > 0) {
      positives.push_back(x);
      total++;
    }
    if (x < 0) {
      negatives.push_back(x);
      total++;
    }
  }

  int positives_seen = 0;
  int negatives_seen = 0;

  // Note: no overflow in the + here :-)
  while (positives_seen + negatives_seen < total) {
    if (sum < 0) {
      // If sum is negative, try to add a positive.
      if (positives_seen >= positives.size()) {
        break;
      }
      sum += positives[positives_seen++];
    } else if (sum > 0) {
      // If sum is positive, try to add a negative.
      if (negatives_seen >= negatives.size()) {
        break;
      }
      sum += negatives[negatives_seen++];
    } else {
      // If sum is zero pick a positive.
      if (positives_seen < positives.size()) {
        sum += positives[positives_seen++];
      } else {
        // There is at least one negative left.
        sum += negatives[negatives_seen++];
      }
    }
  }

  return sum == 0;
} 

Wednesday, September 24, 2014

Try the duck

I had posted this hand on bridgebase forums a few years back, as a play problem for the intermediate players.

This was the hand:

IMPS
None 
 North
♠ KQJ97
♥ 93
♦ 853
♣ AQ4

   


 South
♠ 42
♥ AQJ4
♦ AKQ
♣ 6532

You are South, in a contract of 4NT in a team game (don't ask how you got there, this is a play problem). West leads the heart 2, you play the 9, and East plays the K which you win with the A.

[Please stop reading if you want to try and solve this first]

You have 3 hearts, 3 diamonds and 1 club. You can get 2 spades for sure and have a good chance of a third spade trick (remember, you are in 4NT).

Now if you play spade KQJ, then West with ATxx, can duck twice (or win second round). Now you are one entry short to cash the third spade and will need to rely on the club finesse.

Consider what happens when you play a spade to the 9 after winning the heart Ace. Even if it loses to the T, East cannot attack your dummy entry. This will allow you to lose two spade tricks while keeping the only entry in dummy to cash the third spade. If you play spades from the top, you might have to use up the dummy entry to setup the spades.

This only loses to the playing from the top only when East has a singleton T.

Playing to the K first and then to the 9 loses to Tx with East.

[Apologies to Charles Goren for swiping the title from his BOLS tip]

Monday, September 22, 2014

Iterators part three: A General Binary Tree Iterator

[This is part three in a series about iterators]

Introduction

If you have heard of binary trees, you probably know what in-order, pre-order and post-order traversals are. These traversals are usually defined in a recursive fashion.

For instance, in-order is defined: traverse left sub-tree, visit node, traverse right sub-tree.

These kind of definitions lead to easy recursive implementations.

A common interview question is to convert these recursive method to iterative methods, which can be solved in a general fashion by doing what the compilers do: simulate the recursion using a call stack.

A possible followup to that is to add the ability to do the traversal in a lazy fashion: provide a next interface, which will return the visited nodes one by one (with next being reasonably efficient). [One could use yield, if the language provides it, but we will assume that it is unavailable.]

If you search the web, you will probably see different iteration solutions, custom made for in-order, pre-order etc.

A General Lazy Iterator for Binary Trees

In this article we will discuss a general lazy iterator for binary trees, for traversals defined recursively. This includes not just in-order etc, but also crazy traversals like traverse left node, traverse right node, visit node, visit node, traverse left node.

These general traversals can be represented as a string consisting of the letters "L", "R" and "V".

For instance, in-order traversal is "LVR", L for traverse left sub-tree, V for visit node and R for traverse right sub-tree. Post-order is "LRV" and the crazy traversal defined above is "LRVVL".

So, given a traversal method in the form a traversal string (like "LVR" and which contains at least one V), and the tree, we would like to create a lazy iterator, which will allow us to visit the nodes of the given tree in the given traversal order.

If you were to write a recursive method for the traversal, the code might look something like this (python):

# traversal_method is a string like "LVLR".
def traverse(tree, traversal_method):
    if tree == None:
        return
    for method in traversal_method:
        if method == "L":
            traverse(tree.Left, traversal_method)
        if method == "R":
            traverse(tree.Right, traversal_method)
        if method == "V":
            Visit(tree.Value) 

This recursive method can be converted to an iterative method, by maintaining a stack of (tree,  traversals_left) pairs.

For example, if the traversal required is "LVR", we first push the (root, "LVR") pair. Once the left sub-tree is traversed because of the "L" (started by pushing the left child), we update that to (root, "VR"), we then visit the node, update that node to (root, "R"), then traverse the right sub-tree.

Once a node's traversals_left becomes empty, we pop it off the stack, pick up what is on the top, examine what needs to be done and continue.

This is what the iterative version might look like (python):


# traversal_method is a string like "LVLR".
def traverse(tree, traversal_method):
    if tree == None:
        return
    stack = [(tree, traversal_method)]
    while len(stack) > 0:
        node, traversal_left = stack[-1]
        del stack[-1] # pop
        if node == None:
            continue
        # in python L[-1] is the last element of the list.
        # and L[1:] is the list without the first element.
        if len(traversal_left[1:]) != 0
            # push.
            stack.append((node, traversal_left[1:]))
        if traversal_left[0] == "L":
            stack.append(node.Left, traversal_method)
        if traversal_left[0] == "R":
            stack.append(node.Right, traversal_method)
        if traversal_left[0] == "V":
            visit(node.Value)        

In languages that support yield, an easy way to make this lazy would be to replace visit(node.Value) above with yield node.Value.

Assuming we don't have such a language feature, we want to implement a next interface, which can give us the nodes one at a time, and in a reasonably efficient manner (both worst case and amortized per call).

[We could probably blindly simulate what the C# compiler/python interpreter does behind the scenes for implementing yield, but the result might turn out to be an unreadable mess and we will probably have to spend some effort making it readable, anyway.]

We implement next as two steps.

First step is move, which will do the iteration of pushing/popping nodes into/off the stack, till we get to a node which needs to be visited, resulting in the appropriate node being at the top of the stack.

The second step of next would be to update the top of the stack indicating that a visit was just performed (and returning the tree node to the caller).

We also maintain the invariant that only the move step will change the size of the stack.

A C++ implementation might look like: [Click here to expand/collapse]

And here is a sample usage of this iterator
// Determine if two nodes of a binary search tree
// sum to target.
bool has_sum(Tree *tree, int target) {
  if (tree == NULL) return false;

  Traverser ascending(tree, "LVR");
  Traverser descending(tree, "RVL");

  Tree *left = ascending.next();
  Tree *right = descending.next();

  while (left->Value <= right->Value;) {
    int sum = left->Value + right->Value;
    if (sum == target) {
      return true;
    }
    if (sum > target) {
      right = descending.next();
    } else {
      left = ascending.next();
    }
  }
  return false;
} 

Analysis of next

If the size of the traversal description string is T [O(1) for most useful cases], and the maximum depth of tree is H, then next would run in O(TH) time, and would use O(TH) space.

Even though each call to next is O(TH), it is O(T) amortized per node visited (averaging over the whole traversal), as each node and each edge of the tree is touched only O(T) times.

Conclusion

Even though any recursive implementation which returns a list of elements, can theoretically be modified into a lazy iterative version, explicitly doing it for a binary tree was an interesting exercise.

This approach can also be generalized to general trees, where instead of "L" and "R", we can use child numbers etc.