Problem 004

Problem

Description

Door lock

Like most high security research facilities, many of the rooms in the engineering building require a secret number code to enter. Usually, a single passcode is given to all the users of a particular room. In an effort to thwart passcode snoopers, the building security team has implemented a new passcode mechanism: instead of entering the whole passcode, the user must enter in three random numbers from the original door code. For instance, if the passcode was 2468135, the user may be asked to enter in the 2nd, 4th, and 5th numbers: 481. This shorter sequence (2nd, 4th, 5th) changes each time, so just watching the someone enter in the door code will not guarantee entry to the snooper. Moreover, it helps prevent divulging the complete passcode.

Being the black hat that you are, however, you decide that this security arrangement is weak and plan on cracking the code to the instructor's office [1]. To do so, you have carefully monitored a series of successful entries and recorded them in a text file. Knowing that the three random numbers are always asked for in order and that the digits in the passcode are unique (due to limitations to the security software), your next step is to analyze these entries and produce the original passcode.

Input

The following is an example of a log of successful entries:

352
154
542
315
152

Output

The passcode for the above input is:

31542

Note

This is based on Problem 79 from Project Euler.

[1]No real need to do this. Just knock.

Solution

Approach

Read in all of the entries. Scan the entries and keep track of which digits appear; this will tell you the length of the passcode and which digits are in it. For each digit, create a set that contains the numbers that appear after it. Scan through these sets; if a digit's set is empty, then it is the last digit. Save this digit and remove it from all the other sets, repeat this process until all digits are processed. The final passcode will be in reverse order, so print out the code in reverse.

Input/Output

Source Code