from random import randint
import numpy as np

def random_ternary_matrix(nbrows, nbcols):
    """
    Returns a random nbrows-by-nbcols matrix with three types
    of elements: -Inf, 0, and 1.
    """
    result = np.zeros((nbrows, nbcols));
    for i in range(nbrows):
        for j in range(nbcols):
            nbr = randint(0, 2)
            if nbr < 2:
                result[i, j] = nbr
            else:
                result[i, j] = -np.inf
    return result

def tropical_matrix_multiply(A, B):
    """
    Returns the result of the tropical matrix multiplication of A with B.
    """
    nbrowsA, nbcolsA = A.shape
    nbrowsB, nbcolsB = B.shape
    result = np.zeros((nbrowsA, nbcolsB))
    for i in range(nbrowsA):
        for j in range(nbcolsB):
            result[i, j] = -np.inf
            for k in range(nbcolsA):
                result[i, j] = max(result[i, j], A[i, k] + B[k, j])
    return result

def main():
    """
    Generates two random matrices and shows the result
    of the tropical matrix multiplication.
    """
    A = random_ternary_matrix(3, 5)
    print('The matrix A :\n', A)
    B = random_ternary_matrix(5, 4)
    print('The matrix B :\n', B)
    C = tropical_matrix_multiply(A, B)
    print('The matrix A*B :\n', C)

main()
