• + 0 comments

    python3

    def aOrB(k, a, b, c):  
        # Convert a, b, c to (0-left-padded) binary arrays
        bin_len = 4*max(map(len, [a, b, c]))
        a_bin, b_bin, c_bin = map(lambda x: [*map(int, f'{int(x, 16):0>{bin_len}b}')], [a, b, c])
        
        # First pass: perform minimal bit changes to satisfy a'|b'==c
        a_new, b_new = [], []
        for x, y, z in zip(a_bin, b_bin, c_bin):
            if (x | y) ^ z == 1:
                if (x | y) == 0:
                    y = 1  # only change bit in b, to keep a' minimal
                    k -= 1
                else:
                    k -= x+y
                    x, y = 0, 0
            a_new.append(x)
            b_new.append(y)
        
        # If after initial pass k<0, then no solution
        if k < 0:
            print(-1)
        else:
            # If k>0, can look for further minimizations
            for i in range(bin_len):
                if k == 0:
                    break
                elif (a_new[i], b_new[i]) == (1, 1):
                    a_new[i] = 0
                    k -= 1
                elif ((a_new[i], b_new[i]) == (1, 0)) and (k > 1):
                    a_new[i], b_new[i] = 0, 1
                    k -= 2
            
            a_new_hex, b_new_hex = map(lambda x: hex(int(''.join(map(str, x)), 2))[2:].upper(), [a_new, b_new])
            print('\n'.join([a_new_hex, b_new_hex]))