Bulls and Cows

Interview

Time limit1sMemory limit128 MB

Summary
Given a transcript of Bulls and Cows guesses and replies for codes of length up to 7 with distinct digits, count the codes consistent with all replies and print the smallest one.
Level

Medium4 of 10

Topics
Brute force, Implementation
Solved
No attempts yet

Problem

Bulls and Cows is a game for two players: the codemaker and the codebreaker. The codemaker chooses a secret code — a sequence of KK decimal digits that are all different (a leading zero is allowed). The codebreaker then tries to determine the code by naming numbers of KK digits.

For every guess, the codemaker replies with two counts:

  • Bulls — the number of digits whose value and position are both correct.
  • Cows — the number of digits whose value is correct but whose position is wrong.

For example, if the secret code is 1230 and the codebreaker guesses 1205, the reply is 2 Bulls and 1 Cow.

Given the full transcript of guesses and replies for one game, report how many codes are still possible and, among all of them, the numerically smallest one.

Input

The input contains one or more game descriptions.

Each game description starts with a line containing a single integer KK with 1≤K≤71 \le K \le 7. A value of KK that is not positive marks the end of the input.

Each positive KK is followed by zero or more guess-and-reply lines. Every such line holds K+2K+2 integers separated by one or more spaces: the first KK integers are the digits of a guess, the next integer is the number of Bulls, and the last integer is the number of Cows. The list of guess-and-reply lines ends with a line whose first integer is −1-1 (any remaining integers on that line are ignored).

Output

For each game, print exactly one line of the form

N is one of M possible solutions.

where NN is the numerically smallest code consistent with every guess and reply — written as KK digits with no separators and keeping any leading zeros — and MM is the number of codes consistent with the whole transcript.

Examples1

  1. Example 1

    Input
    6
    0 1 2 8 4 5 5 0
    0 1 2 9 5 4 3 2
    -1 1 2 3 4 5 0 0
    0
    
    Expected output
    012345 is one of 5 possible solutions.