Day 4: Perilous Pier

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

FAQ

  • Pyro@programming.dev
    link
    fedilink
    arrow-up
    1
    ·
    10 hours ago

    Python

    Simply try every code length successively until we find a match

    click to view code
    def min_code_length(s: str):
        n = len(s)
    
        # try every code length successively
        for i in range(1, n+1):
            # extract code
            code = list(s[:i])
    
            # iterate over barcode to see if valid
            j = 0
            for ch in s:
                if ch == code[j]:
                    # we match the code
                    pass
                elif ch == '?':
                    # the barcode has a '?' which can be skipped
                    pass
                elif code[j] == '?':
                    # our code has a '?' which can be collapsed to the char we need
                    code[j] = ch
                else:
                    # code does not match barcode
                    break
                j = (j+1) % i
            else:
                # no-break: we matched the entire barcode successfully
                return i
    
    assert min_code_length("rgbrgbrgbr") == 3
    assert min_code_length("?rv") == 2
    assert min_code_length("o??v???y") == 5
    assert min_code_length("??bg?v??") == 4
    assert min_code_length("??b?????") == 1
    assert min_code_length("??b?????") == 1
    
    # part1: try each barcode separately
    def part1(data: str):
        total = 0
        for barcode in data.splitlines():
            total += min_code_length(barcode)
        return total
    
    assert part1("""rgbrgbrgbr
    ?rv
    o??v???y
    ??bg?v??
    ??b?????
    ???""") == 16
    
    # part2: combine entire barcode
    def part2(data: str):
        return min_code_length(data.replace('\n',''))
    
    assert part2("""rro??
    ?g
    ?g???
    ??r?????
    ??g?
    ??
    yy?v?o
    ???v
    b?g??
    ?y??v?or
    ????r?o
    ??
    ?????
    ?r??v?r""") == 16