Repository navigation
Expand file tree
/
Copy pathmatrix_sum.lua
More file actions
79 lines (71 loc) · 1.6 KB
/
Copy pathmatrix_sum.lua
File metadata and controls
79 lines (71 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
local function sameShape(a, b)
if type(a) ~= "table" or type(b) ~= "table" or #a == 0 then
return false
end
if type(a[1]) ~= "table" or #a[1] == 0 then
return false
end
if #a ~= #b then
return false
end
local cols = #a[1]
for i = 1, #a do
if type(a[i]) ~= "table" or type(b[i]) ~= "table" then
return false
end
if #a[i] ~= cols or #b[i] ~= cols then
return false
end
end
return true
end
local function sumMatrices(a, b)
if not sameShape(a, b) then
error("matrices must be non-empty and the same size", 2)
end
local rows = #a
local cols = #a[1]
local result = {}
for i = 1, rows do
result[i] = {}
for j = 1, cols do
result[i][j] = a[i][j] + b[i][j]
end
end
return result
end
local function printMatrix(m)
for i = 1, #m do
local row = {}
for j = 1, #m[i] do
row[#row + 1] = string.format("%6.2f", m[i][j])
end
print(table.concat(row, " "))
end
end
local M = {
sameShape = sameShape,
sumMatrices = sumMatrices,
}
if arg and arg[0] and tostring(arg[0]):find("matrix_sum", 1, true) then
local matrixA = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
}
local matrixB = {
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
}
local matrixC = sumMatrices(matrixA, matrixB)
print("Matrix A")
printMatrix(matrixA)
print("")
print("Matrix B")
printMatrix(matrixB)
print("")
print("A + B")
printMatrix(matrixC)
end
return M