# Arup Guha
# 12/4/2024
# Code to verify COT 3100H Final Exam Question 6

# I am treating mask as a 9 digit number in base 3. This returns true iff
# the number has three 0s, 1s and 2s, leading 0s permitted of course.
def valid(mask):

    # Counters for each "trit"
    f = [0,0,0]
    for i in range(9):
        f[mask%3] += 1
        mask = mask//3

    # These are the only ones I want to consider.
    return f[0] == 3 and f[1] == 3 and f[2] == 3

# Returns 1 if the number represented by mask in base 3 doesn't have three
# of the same trit in a row.
def countit(mask):

    # Peel of the trits in reverse order.
    mylist = []
    for i in range(9):
        mylist.append(mask%3)
        mask = mask//3

    # If any consecutive run of 3 are the same, we don't count it.
    for i in range(7):
        if mylist[i] == mylist[i+1] and mylist[i+1] == mylist[i+2]:
            return 0

    # If we get here, we count it.
    return 1

# Accumulator.
res = 0

# Go through all 9 trit numbers.
for mask in range(3**9):

    # This isn't one we want to consider.
    if not valid(mask):
        continue

    # Just add the contribution of this one (it's 0 or 1)
    res += countit(mask)

# Ta da!
print(res)
