|
| 1 | +""" |
| 2 | +Project Euler Problem 79: https://projecteuler.net/problem=79 |
| 3 | +
|
| 4 | +Passcode derivation |
| 5 | +
|
| 6 | +A common security method used for online banking is to ask the user for three |
| 7 | +random characters from a passcode. For example, if the passcode was 531278, |
| 8 | +they may ask for the 2nd, 3rd, and 5th characters; the expected reply would |
| 9 | +be: 317. |
| 10 | +
|
| 11 | +The text file, keylog.txt, contains fifty successful login attempts. |
| 12 | +
|
| 13 | +Given that the three characters are always asked for in order, analyse the file |
| 14 | +so as to determine the shortest possible secret passcode of unknown length. |
| 15 | +""" |
| 16 | +import itertools |
| 17 | +from pathlib import Path |
| 18 | + |
| 19 | + |
| 20 | +def find_secret_passcode(logins: list[str]) -> int: |
| 21 | + """ |
| 22 | + Returns the shortest possible secret passcode of unknown length. |
| 23 | +
|
| 24 | + >>> find_secret_passcode(["135", "259", "235", "189", "690", "168", "120", |
| 25 | + ... "136", "289", "589", "160", "165", "580", "369", "250", "280"]) |
| 26 | + 12365890 |
| 27 | +
|
| 28 | + >>> find_secret_passcode(["426", "281", "061", "819" "268", "406", "420", |
| 29 | + ... "428", "209", "689", "019", "421", "469", "261", "681", "201"]) |
| 30 | + 4206819 |
| 31 | + """ |
| 32 | + |
| 33 | + # Split each login by character e.g. '319' -> ('3', '1', '9') |
| 34 | + split_logins = [tuple(login) for login in logins] |
| 35 | + |
| 36 | + unique_chars = {char for login in split_logins for char in login} |
| 37 | + |
| 38 | + for permutation in itertools.permutations(unique_chars): |
| 39 | + satisfied = True |
| 40 | + for login in logins: |
| 41 | + if not ( |
| 42 | + permutation.index(login[0]) |
| 43 | + < permutation.index(login[1]) |
| 44 | + < permutation.index(login[2]) |
| 45 | + ): |
| 46 | + satisfied = False |
| 47 | + break |
| 48 | + |
| 49 | + if satisfied: |
| 50 | + return int("".join(permutation)) |
| 51 | + |
| 52 | + raise Exception("Unable to find the secret passcode") |
| 53 | + |
| 54 | + |
| 55 | +def solution(input_file: str = "keylog.txt") -> int: |
| 56 | + """ |
| 57 | + Returns the shortest possible secret passcode of unknown length |
| 58 | + for successful login attempts given by `input_file` text file. |
| 59 | +
|
| 60 | + >>> solution("keylog_test.txt") |
| 61 | + 6312980 |
| 62 | + """ |
| 63 | + logins = Path(__file__).parent.joinpath(input_file).read_text().splitlines() |
| 64 | + |
| 65 | + return find_secret_passcode(logins) |
| 66 | + |
| 67 | + |
| 68 | +if __name__ == "__main__": |
| 69 | + print(f"{solution() = }") |
0 commit comments