# Jason Zhang
# Bergen County Academies
# Senior

order = ["*1**","***1","*0**","1***","**1*","0***","**0*","***0","*1*0","*1*1",
         "*0*1","*0*0","1*0*","1*1*","0*1*","0*0*","11**","*11*","01**","1**1",
         "**11","0**1","10**","*01*","00**","*10*","**01","*00*","1**0","**10",
         "0**0","**00","11*0","*110","01*0","11*1","*111","01*1","10*1","*011",
         "00*1","10*0","*010","00*0","110*","1*01","100*","111*","1*11","101*",
         "011*","0*11","001*","010*","0*01","000*","*100","*101","*001","*000",
         "1*00","1*10","0*10","0*00","1100","1110","0110","0100","1101","1111",
         "0111","0101","1001","1011","0011","0001","1000","1010","0010","0000"]

grid = ["1100","1110","0110","0100","1101","1111","0111","0101",
        "1001","1011","0011","0001","1000","1010","0010","0000"]


def hex_to_bin(hex) -> int:
    return int(hex, 16)


def match(str1, str2) -> bool:
    for c1, c2 in zip(str1, str2):
        if c2 != "*" and c1 != c2:
            return False
    return True


def bin_from_expr(expr) -> int:
    out = 0
    for pos in grid:
        if match(pos, expr):
            out += 1
        out <<= 1
    return out >> 1


def print_expr(expr) -> str:
    out = ""
    if expr[0] == '1': out += "A"
    if expr[0] == '0': out += "~A"
    if expr[1] == '1': out += "B"
    if expr[1] == '0': out += "~B"
    if expr[2] == '1': out += "C"
    if expr[2] == '0': out += "~C"
    if expr[3] == '1': out += "D"
    if expr[3] == '0': out += "~D"
    return out


with open("3sr_sampledata.txt", "r") as f:
    for line in f:
        binary = hex_to_bin(line)

        for expr in order:
            b = bin_from_expr(expr)
            if binary & b == b:
                print(print_expr(expr), end="")
                binary -= b
                if binary != 0:
                    print("+", end="")
        print()