Friday, September 13, 2024

ZigZag Matrix

I was reviewing the implementations of ZigZag on RosettaCode and I couldn't find any that showed how to construct just the coefficient itself, so I made one!

def zz(j, k, n):
    return \
        ((2*int(k//2) + 3)*int(k//2) \
         if 0 == k % 2 else \
         (zz(0, k - 1, n) + 1)) \
         if j == 0 else \
        ((n**2-1-zz(n-1-j, n-1-k, n)) \
         if n <= j + k else \
         (zz(0, j + k, n) - (-1)**(j + k)*j))


if __name__ == '__main__':
    from numpy import matrix
    for n in [6, 8, 10]:
        print(repr(matrix([[zz(j, k, n)
                            for k in range(n)]
                           for j in range(n)])))