Day 21: Scrambled Letters and Hash

author: Harshvardhan Pandit

license: MIT

link to problem statement

The computer system you're breaking into uses a weird scrambling function to store its passwords. It shouldn't be much trouble to create your own scrambled password so you can add it to the system; you just have to implement the scrambler.

The scrambling function is a series of operations (the exact list is provided in your puzzle input). Starting with the password to be scrambled, apply each operation in succession to the string. The individual operations behave as follows:

  • swap position X with position Y means that the letters at indexes X and Y (counting from 0) should be swapped.
  • swap letter X with letter Y means that the letters X and Y should be swapped (regardless of where they appear in the string).
  • rotate left/right X steps means that the whole string should be rotated; for example, one right rotation would turn abcd into dabc.
  • rotate based on position of letter X means that the whole string should be rotated to the right based on the index of letter X (counting from 0) as determined before this instruction does any rotations. Once the index is determined, rotate the string to the right one time, plus a number of times equal to that index, plus one additional time if the index was at least 4.
  • reverse positions X through Y means that the span of letters at indexes X through Y (including the letters at X and Y) should be reversed in order.
  • move position X to position Y means that the letter which is at index X should be removed from the string, then inserted such that it ends up at index Y.

For example, suppose you start with abcde and perform the following operations:

  • swap position 4 with position 0 swaps the first and last letters, producing the input for the next step, ebcda.
  • swap letter d with letter b swaps the positions of d and b: edcba.
  • reverse positions 0 through 4 causes the entire string to be reversed, producing abcde.
  • rotate left 1 step shifts all letters left one position, causing the first letter to wrap to the end of the string: bcdea.
  • move position 1 to position 4 removes the letter at position 1 (c), then inserts it at position 4 (the end of the string): bdeac.
  • move position 3 to position 0 removes the letter at position 3 (a), then inserts it at position 0 (the front of the string): abdec.
  • rotate based on position of letter b finds the index of letter b (1), then rotates the string right once plus a number of times equal to that index (2): ecabd.
  • rotate based on position of letter d finds the index of letter d (4), then rotates the string right once, plus a number of times equal to that index, plus an additional time because the index was at least 4, for a total of 6 right rotations: decab.

After these steps, the resulting scrambled password is decab.

Now, you just need to generate a new scrambled password and you can access the system. Given the list of scrambling operations in your puzzle input, what is the result of scrambling abcdefgh?

Solution logic

Since this is a rule-based approach, we only need to code the rules and then follow them as per the input specification.

One thing to note regarding all the rules that we are creating functions for - the input comes directly from the parsed file, so we need to convert or parse integers as required.

Swap positions

We get two positions (x, y) which we need to swap. In python, this is as simple as:

list[x], list[y] = list[y], list[x]

In [1]:
def swap_position(password, x, y):
    x = int(x)
    y = int(y)
    password[x], password[y] = password[y], password[x]
    return password

Swap letters

We can either replace the letter x with a temporary letter $ and then replace y with x followed by $ with y (the temp variable approach to swap), or simply iterate over the list and replace the occurences as they appear. For me, the iteration approach seems more logical (to read).


In [2]:
def swap_letter(password, x, y):
    _password = []
    for char in password:
        if char == x:
            _password.append(y)
        elif char == y:
            _password.append(x)
        else:
            _password.append(char)
    return _password

Rotate right and left

We split the string based on the position of x from the front or back based on left/right and then attach it back to the other end.

right --> remove from end, attach to front
left  --> remove from front, attach to end

In [3]:
def rotate_right(password, x):
    x = int(x)
    return password[-x:] + password[:-x]

def rotate_left(password, x):
    x = int(x)
    return password[x:] + password[:x]

Rotate based on position

First we need to find the first index where x occurs. Then we need to calculate the number of rotations to make. This is based on the following rules:

1 rotation by default
Add index of characters
If index is equal or greater than four, add 1

To keep the rotations within the list, we take the modulus of the rotations with the length of the password. Finally, we call rotate_right with the implied number of rotations.


In [4]:
def rotate_letter(password, x):
    for index in range(0, len(password)):
        if password[index] == x:
            break
    else:
        # print('wrong input')
        return password
    rotations = 1 + index
    if index >= 4:
        rotations += 1
    rotations = rotations % len(password)
    return rotate_right(password, rotations)

Reverse

Only the indexes x and y need to be reversed, everything else should be copied or kept as is. We use python's excellent list splicing and inbuilt reverse ([::-1]) to do all the work for us.


In [5]:
def reverse(password, x, y):
    x = int(x)
    y = int(y) + 1  # to include character at `y`
    
#     EXPLICIT
#     _password = []
#     for i in range(0, x):
#         _password.append(password[i])
#     # step in decreasing order
#     for i in range(y, x - 1, -1):
#         _password.append(password[i])
#     for i in range(y + 1, len(password)):
#         _password.append(password[i])
#     return _password

    return password[:x] + password[x:y][::-1] + password[y:]

Move

This is trivial due to the way python handles lists for us. We pop the element at index x and then insert it at index y.


In [6]:
def move(password, x, y):
    x = int(x)
    y = int(y)
    char = password.pop(x)
    password.insert(y, char)
    return password

Defining rules and actions


In [7]:
import re
rules = {
    'swap-position': re.compile(r'^swap position (\d+) with position (\d+)'),
    'swap-letter': re.compile(r'^swap letter (\w+) with letter (\w+)'),
    'rotate-letter': re.compile(r'^rotate based on position of letter (\w)+'),
    'rorate-right': re.compile(r'^rotate right (\d+) step'),
    'rotate-left': re.compile(r'^rotate left (\d+) step'),
    'move': re.compile(r'^move position (\d+) to position (\d+)'),
    'reverse': re.compile(r'^reverse positions (\d+) through (\d+)')
}
actions = {
    'swap-position': swap_position,
    'swap-letter': swap_letter,
    'rotate-letter': rotate_letter,
    'rorate-right': rotate_right,
    'rotate-left': rotate_left,
    'move': move,
    'reverse': reverse
}

Getting input


In [8]:
with open('../inputs/day21.txt', 'r') as f:
        input_data = f.readlines()

Parsing input and simulating rules


In [9]:
def parse_input(password):
    password = list(password)
    for line in input_data:
        for name, rule in rules.items():
            match = rule.match(line)
            if rule.match(line):
                action = actions[name]
                password = action(password, *match.groups())
                break
    return ''.join(password)

print('answer', parse_input('abcdefgh'))


answer gbhcefad

Part Two

You scrambled the password correctly, but you discover that you can't actually modify the password file on the system. You'll need to un-scramble one of the existing passwords by reversing the scrambling process.

What is the un-scrambled version of the scrambled password fbgdceah?

Solution logic

Rather than going through the effort of writing the reverse operations for every instruction, we simply iterate through all the permutations of the letters a, b, c, d, e, g, h and see which one of them generates the given string.


In [10]:
from itertools import permutations
string = 'fbgdceah'
choices = list(permutations('abcdefgh', len(string)))
for password in choices:
    hashed = parse_input(password)
    if hashed == string:
        print('answer', ''.join(password))
        break


answer gahedfcb

== END ==