"""Essential 06 — reusable modular arithmetic and matrix functions."""
from lab04 import primeFactors,eulerTotient,extendedGCD,inverseMod,inverseMatrixMod,hill

def myGCDIter(a,b):
    while b: a,b=b,a%b
    return abs(a)

def myGCDRec(a,b): return myGCDRec(b,a%b) if b else abs(a)

def det(a):
    if len(a)!=2 or any(len(r)!=2 for r in a): raise ValueError('Expected 2x2 matrix')
    return a[0][0]*a[1][1]-a[0][1]*a[1][0]

def matrixMult(a,b):
    if not a or not b or not a[0] or not b[0] or any(len(r)!=len(a[0]) for r in a) or any(len(r)!=len(b[0]) for r in b) or len(a[0])!=len(b):
        raise ValueError('Incompatible matrix dimensions')
    return [[sum(x*y for x,y in zip(row,col)) for col in zip(*b)] for row in a]

def matrixMultMod(a,b,m):
    if m<2: raise ValueError('Modulus must exceed one')
    return [[x%m for x in row] for row in matrixMult(a,b)]

def hillCipherEncrypt(pt,k,alphabet): return hill(pt,k,alphabet)
def hillCipherDecrypt(ct,k,alphabet): return hill(ct,k,alphabet,True)

if __name__=='__main__':
    assert primeFactors(24)==[2,2,2,3] and eulerTotient(24)==8
    assert myGCDRec(121,55)==myGCDIter(121,55)==11
    g,s,t=extendedGCD(9,7); assert 9*s+7*t==g==1
    assert inverseMod(8,27)==17
    assert matrixMult([[1,2,3],[4,5,6]],[[1],[2],[3]])==[[14],[32]]
    k=[[2,0],[2,4]]; assert matrixMultMod(k,inverseMatrixMod(k,27),27)==[[1,0],[0,1]]
    a='ABCDEFGHIJKLMNOPQRSTUVWXYZ '; assert hillCipherDecrypt(hillCipherEncrypt('HILLS',k,a),k,a)=='HILLSX'
    print('All helper and matrix round-trip tests passed')
