Facebook Hacker Cup – 1A – Wine Tasting

Problem Description

A group of Facebook employees just had a very successful product launch. To celebrate, they have decided to go wine tasting. At the vineyard, they decide to play a game. One person is given some glasses of wine, each containing a different wine. Every glass of wine is labelled to indicate the kind of wine the glass contains. After tasting each of the wines, the labelled glasses are removed and the same person is given glasses containing the same wines, but unlabelled. The person then needs to determine which of the unlabelled glasses contains which wine. Sadly, nobody in the group can tell wines apart, so they just guess randomly. They will always guess a different type of wine for each glass. If they get enough right, they win the game. You must find the number of ways that the person can win, modulo 1051962371.


The first line of the input is the number of test cases, N. The next N lines each contain a test case, which consists of two integers, G and C, separated by a single space. G is the total number of glasses of wine and C is the minimum number that the person must correctly identify to win.


  • N = 20
  • 1 ≤ G ≤ 100
  • 1 ≤ CG


For each test case, output a line containing a single integer, the number of ways that the person can win the game modulo 1051962371.

Example input

1 1
4 2
5 5
13 10
14 1

Example output


Dynamic Programming Approach

During the contest, I chose to tackle this using a dynamic programming (DP) approach which will be described in this entry.  As usual, the DP approach will need us to formulate the recurrence relation for this problem.  The recurrence I used was based on the following:

Let f(n, pc, t) be the number of ways to guess arrangement of n glasses with pc of them still have a chance to be named correctly (pc stands for potentially correct), and at least t glasses will be named correctly.  When looking at the state (n, pc, t), let our focus be on the very first glass position which can be named correctly.  On that position, there’s a possibility to put the correct glass on it, or a wrong glass.  Let’s explore the function:

def f(n, pc, t):
  if n == 0: return 1 if t == 0 else 0
  ways = 0
  if pc > 0: ways += f(n-1, pc-1, max([0, t-1]))
  if pc > 1: ways += (pc-1) * f(n-1, pc-2, t)
  ways += (n-pc) * f(n-1, max([0, pc-1]), t)
  return ways

Line 2 contains the terminal condition of this recurrence, … it is clear that if there’s no glass left to worry, … we only have one success possibility if there is no target to achieve, t is zero.

Then comes the accumulation of number of ways based on possibilities of actions in this state, … remember the step always focuses in putting a glass (either correct or incorrect) into a position which can still have a proper glass for it.

Line 4 is also straightforward, one of the possibility is to put the correct glass into its position (there’s only one glass here) … the next state after putting this glass is obviously (n-1, pc-1, max(0, t-1)).

Line 5 is basically a possibility of putting wrong glass into the position, but this wrong glass actually has its own proper position somewhere. This means we’re actually wasting 2 glasses and their positions without gaining any correct target. Note that we can choose one out of pc-1 glasses for this possibility, thus the multiplication with pc-1.

Line 6 is basically a possibility of putting wrong glass into the position, and this wrong glass never has a chance to be properly placed (i.e.: its proper position has been occupied by another glass). We can choose out of (n-pc) glasses for this, thus the multiplication by (n-pc). The next state is: (n-1, max(0, pc-1), t).

That’s it, … finally, to tackle an input of (G, C) … call the above function f(G, G, C)

The above logic doesn’t take care of the modulo for clarity, … the following C++ code has the proper solution for this puzzle.

Sweet Florida-trip Sweep

The Utah Jazz just pulled off two improbable wins against the Heat and Magic.  The Jazz-Heat game itself can easily go down as one of the greatest regular season games ever played.  Just too many dramas involved: Jazz being down by 22 away from home, against the heavily favored (and hyped) Heat superstars, Millsap broke loose for a career-high 46 points, including 11 points within the last 30 seconds of regulation to force overtime.  Millsap my man suddenly looked like T-Mac in this clip … I still feel sorry for the Houston fans who left the building early, heheheh.  I’m not a fan of the Rockets, but this is just so amazing,  probably the only meaningful highlight of T-Mac as a Rocket.

Well, this might not be as fiery, but eerily similar, … the Jazz was down by 8 points with 37.3 seconds left in regulation.  From that point, the Jazz scored 14 points to force overtime, 11 by Millsap alone … 3/3 from 3-pt range and a putback to force OT.  What a game!!  Jazz went on (without Deron Williams who fouled out) in OT and won it 116-114.

The next day, the flew to Orlando to face the Magic team who was unbeaten at home.  I thought the Jazz came out pretty well in the 1st quarter, but the 2nd quarter was a disaster … Magic ended up holding a 10-pt lead at half-time.  They continued to torched the Jazz in the 3rd, until about 1:36 left in the period, leading by 18 points.  That was when the Jazz employed a perfectly executed zone defense … This match-up zone defense, along with the Magic bad plays, was responsible of a 24-2 Jazz run to get back in the game.  Jazz ended up with a win by 10 points: 104-94, whoa … how did that happen?  Check this great article out … it breaks down the defense employed by the Jazz during the game.

I’m usually looking forward for the next Jazz game, but don’t feel like it this time … still want to cherish the past two amazing games, the sweet Florida-trip sweep, baby 🙂 … not a lot of teams will get out of it unscathed.

Go Jazz!

Colored Stamps Puzzle (revisited)

Here’s a simplified version of a similar colored stamps puzzle (it was once a question thrown at me during an interview).  The approach can be the same to the one indicated by Felix in the previous post, but if you haven’t seen it, it might still be interesting:

In a game show, the host placed one colored stamp on each of the three contestants’ forehead.  It could either be a red or a blue stamp.  Each contestant can only see the other guys’ stamps, but not his own.  The host gives an important clue: at least one of the stamps is red.  The host then asks each contestant to shout the color of the stamp on the contestant’s forehead.  Here are the responses, in order:

A: “I don’t know”

B: “I don’t know”

C: “I know!”

What is the color of C’s stamp and what is his thought process leading to a confident answer?

Colored Stamps Puzzle

I recently came across another interesting puzzle that goes like this:

During a game show, the host who has 4 red stamps and 4 blue stamps has placed three contestants (A, B, C) in a closed room.  The host places 2 stamps on each of the contestant’s forehead in such a way that each contestant can only see the other stamps, but not his own.  The remaining unused 2 stamps are thrown away and the colors are unknown to the contestants.  It is known that all three contestants are superb and honest logician.  The host then asks each contestant to see if he figures out the colors of the stamps on his forehead.  The host continues asking the same question to each contestant until one of them knows the correct colors of stamps on his forehead:

A: “I don’t know”

B: “I don’t know”

C: “I don’t know”

A: “I don’t know”

B: “I know!”

What are the colors of B’s stamps?

P.S.: You guys know the drill, we need to deduce the answer based solely on the known facts and the above conversations.  No smart moves like using hands to grab the stamps or something of that sort.


What is geocaching?  Well, it happens to be my new hobby.  It is a form of outdoor activity using a GPS device.  It’s a form of a treasure hunt which in short goes like this:

1) A geocache owner hides a container (we’ll call it a cache).

2) That owner posts the GPS coordinates on a site www.geocaching.com (this one is the most popular of such sites and has free and premium membership available).

3) Other cachers, like me, then try to find that hidden cache.  When we find it, we log our names into the cache, and sometimes exchange items.

There are types of geocaches that we play with.  For me, I’m always interested in puzzle cache or unknown cache.  This is a type of cache where you’ll have to work your way first to obtain the correct cache coordinates.  Then the second part is to embark and find the actual cache.

Like many others, I’m starting to also hide some caches (with puzzles, of course) around the area where I live.  Check them out even if  you are not a geocacher yet, but a puzzle lover.  You can mail me if you think you got the right answer, or just use that validator link posted on the cache page.

Geometric Series Puzzle

Someone recently posted a puzzle involving geometric series.  It goes like this:

From the set of integers in range [1..4000,000,000], in how many ways that we can pick 6 different integers from the set, and those 6 numbers form a geometric progression?

From the big range of the set, we can see that brute force won’t cut it.  However, after some analysis, a smarter approach can be applied here.  The following is the step-by-step approach I took when I pondered this puzzle.

Consider the following facts:

* In a geometric series, the 6th term of a series which starts with a as its 1st term is: a r^5 where r is obviously the constant ratio between successive terms.

* We can visualize r as a fraction n / d, where both n and d are integers.  We can safely consider only n and d pairs with n > d (which means we’ll just get the strictly ascending series).  So, visualizing ratios as n / d, we see the 6th term as a n^5 / d^5.

Then I started thinking about the simplest series with ratio 2 / 1.  The smallest valid progression is:

1 2 4 8 16 32

We immediately see that an integer multiple k of the above progression is also valid as long as 32 x k does not exceed 4,000,000,000 which is the maximum integer in the set.  We can see that the largest possible k is floor(4,000,000,000 / 32) = 125,000,000.  More generally, the number of valid integer multiples can be obtained by doing an integer division of the maximum number in the set by the highest term of the 6 numbers in the smallest valid progression of this ratio.

Let’s move on with another example with ratio 4 / 1.  The smallest valid progression is:

1 4 16 64 256 1024

And we’ll have floor(4,000,000,000 / 1024) = 3,906,250 valid progressions from the set.

Now it is obvious that we’ll start with the integer ratios like 2 or 4.  However, the trick to this puzzle is also to see that the ratio might not be an integer as the puzzle only seeks to pick 6 integers which forms geometric progression.

To find out more about this, I started looking at n / d and for each n, I walked up the d part from 1 up to n-1, as those will be the ratios to look at.  I skipped 4 / 2 (same as 2 / 1) because this is not a simple fraction, and thus would already be taken care of when dealing with ratios with n = 2.

Next value of d is 3, which is interesting to look at.  We can see that for a ratio of 4 / 3, the first term of the series has to be a multiple of 3^5.  Otherwise, we won’t be having integer terms because to get each successive term, we’d have to divide by 3.  So, the smallest valid progression for ratio 4 / 3 is:

243 324 432 576 768 1024

The a-ha moment came when I saw that the smallest progressions of both ratio 4 / 1 and 4 / 3 shares the same high number (6th term), which is 1024, or 4^5, or even more generally n^5.  This would mean that it would also have the same number of valid integer multiples, which is 3,906,250.  That is, for a particular simple fraction ratio n / d, the number of valid progressions is floor(MAX / n^5).

I got excited.  We can then ponder how many valid d‘s, each of which is less than n, and the pair n, d is relatively prime to each other to avoid non-simple fractions.  This is none other than the well-known Euler’s Totient function. Combine this with the number of valid integer multiples of a progression, we know that for a particular numerator n, the number of ways to pick 6 integers which forms a geometric progression is:

f(n) = phi(n) x floor(MAX / (n^5)),

where phi is the Euler’s Totient function, and MAX is the maximum integer value in the set (in this case, 4,000,000,000).

Now, we just need to find the sum of all f(n) for n values of 2, 3, 4, … all the way until f(n) yields 0.

Take a look at the Python code for this puzzle.

Programming Interviews

From time to time, I am often tasked to interview some candidates for a software development position.  I usually focus on assessing C/C++ skills of the candidates.  To be honest, so far, I’m still struggling to find a good way to efficiently conduct the interview sessions to better probe the level of competency of the candidates.

That is why I’m so glad to see this article from Joel Spolsky.  It’s a must read for interviewers like me, especially for programming related positions.

Here’s an interesting excerpt from the article which I truly like:

A lot of programmers that you might interview these days are apt to consider recursion, pointers, and even data structures to be a silly implementation detail which has been abstracted away by today’s many happy programming languages. “When was the last time you had to write a sorting algorithm?” they snicker.

Still, I don’t really care. I want my ER doctor to understand anatomy, even if all she has to do is put the computerized defibrillator nodes on my chest and push the big red button, and I want programmers to know programming down to the CPU level, even if Ruby on Rails does read your mind and build a complete Web 2.0 social collaborative networking site for you with three clicks of the mouse.

Happy interviewing!