Lua用一维数组存储一个n阶方阵,输出这个方阵的正对角线上的数的和与反对角线上的数的和的差的绝对值。

arr = {11, 2, 4,
        4, 5, 6,
        10, 8, -12}
function diagonalDifference(arr)
dimesion = math.sqrt(#arr)

    arr1 = {}
    sum1 = 0
    arr2 = {}
    sum2 = 0

    for i=1,dimesion do
        for j=1,dimesion do
            if(i == j)then
                arr1[j] = arr[1 + (j - 1) * (dimesion + 1)]
                sum1 = sum1 + arr1[j]
                --print(arr1[j])
            end
        end
    end


    for i=1,dimesion do
        for j=1,dimesion do
            if((i + j) == (dimesion + 1))then
                arr1[j] = arr[dimesion + (j - 1) * (dimesion - 1)]
                sum2 = sum2 + arr1[j]
                --print(arr1[j])
            end
        end
    end
    return math.abs(sum2 - sum1)

end
print(diagonalDifference(arr))

 

posted @ 2018-12-27 16:37  _清风明月  阅读(344)  评论(0编辑  收藏  举报