Your mistake has to do with the definition of the problem.  The man does not stop taking matches as soon as one of the boxes is empty (as in your code).  He stops taking matches after he *picks a box and finds it empty*.  This means that when Box A is empty, he doesn't immediately stop -- he continues until he picks Box A again (or until he empties Box B as well).