1

Hi I got the following question:

We have a safe with 4 digits (each digit is between 0-9) password. The safe will be open if you give to it a string that contains a sub string with the correct 4 digit password. For example: safe with the code 2345 will be open if you give for example the string '123456'. the safe will be open in this case after the digit 5. you need to give the shortest string that necessarily will open the safe.

I tried many ways but couldn't find a better way than the naive string that contains: 0000000100020003...

GroundIns
  • 541
  • 1
  • 5
  • 11

1 Answers1

1

Your answer is using the De Bruin sequence. In Python (from wikipedia):

def de_bruijn(k, n):
    """
    De Bruijn sequence for alphabet k
    and subsequences of length n.
    """
    try:
        # let's see if k can be cast to an integer;
        # if so, make our alphabet a list
        _ = int(k)
        alphabet = list(map(str, range(k)))

    except (ValueError, TypeError):
        alphabet = k
        k = len(k)

    a = [0] * k * n
    sequence = []

    def db(t, p):
        if t > n:
            if n % p == 0:
                sequence.extend(a[1:p + 1])
        else:
            a[t] = a[t - p]
            db(t + 1, p)
            for j in range(a[t - p] + 1, k):
                a[t] = j
                db(t + 1, t)
    db(1, 1)
    return "".join(alphabet[i] for i in sequence)

And in your case it is:

print(de_bruijn("0123456789", 4))

Outputs a huge number which I won't copy-paste here.

Idos
  • 15,053
  • 14
  • 60
  • 75