# Arup Guha
# 2/19/2025
# Solution to COP 4516 Final Individual Contest Problem A: Almost Magic Square

# Returns 1 if the values in nums permuted according to perm form a d
# Almost Magic Square, and returns 0 otherwise.
def eval(nums, perm, d):

    # There are eight groups to consider, here I store the indexes of each.
    # These are really indexes into perm.
    GROUPS = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]

    # This is the sum of the first row.
    firstsum = 0
    for i in range(3):
        firstsum += nums[perm[GROUPS[0][i]]]

    # These will get overwritten.
    mymin = 1000000000
    mymax = 0

    # Try each group.
    for i in range(len(GROUPS)):

        # Add the number in this row, col or diag.
        mys = 0
        for j in range(len(GROUPS[i])):
            mys += nums[perm[GROUPS[i][j]]]

        # Update.
        mymin = min(mymin, mys)
        mymax = max(mymax, mys)

    # Return accordingly.
    if mymax - mymin <= d:
        return 1
    return 0

# Updates perm to be the next permutatation.
def nextperm(perm):

    # Second to last index.
    i = len(perm)-2

    # Finds first pair (i, i+1) where perm[i] < perm[i+1] from back.
    while i>=0 and perm[i] > perm[i+1]:
        i -= 1

    # At last perm.
    if i < 0:
        return False

    # We want perm[j] to be smallest value > perm[i].
    j = len(perm)-1
    while perm[j] < perm[i]:
        j -= 1

    # Values in indexes i and j need to be swapped.
    tmp = perm[i]
    perm[i] = perm[j]
    perm[j] = tmp

    # Reverse from i+1 to end.
    left = i+1
    right = len(perm)-1

    # Swap pairs until you meet in the middle.
    while left < right:
        tmp = perm[left]
        perm[left] = perm[right]
        perm[right] = tmp
        left += 1
        right -= 1

    # We got to the next permutation.
    return True

# Solves the problem for this set of numbers and tolerance d.
def go(nums, d):

    # Set up my default permutation.
    res = 0
    perm = []
    for i in range(len(nums)):
        perm.append(i)

    # See if this permutation works.
    res += eval(nums, perm, d)

    # Try each other permutation in order and add into result.
    while nextperm(perm):
        res += eval(nums, perm, d)

    # Ta da!
    return res

def main():

    nC = int(input())

    # Process cases.
    for loop in range(nC):

        # Get input.
        d = int(input())
        vals = [int(x) for x in input().split()]

        # Ta da!
        print(go(vals, d))

# Run it!
main()
