如何测试关系在 Lua 中是否传递?

How can I test whether a relation is transitive in Lua?

我需要编写一个程序来测试给定关系是否可传递。

我想为此使用链表,但我不知道如何实现。我看过类似问题的答案,但其中 none 是针对 Lua 的,由于我只是在学习编码,所以我不知道如何让这些答案对我有用。

这是我目前的尝试:

relation={{1,1}, {1,2}, {2,1}}
n=3
for i=1,n do
if relation[i][1] == relation[i][2] then
print("transitive")
else if relation[i][1] ~= relation[i][2] then
print("checking")
for q=1,n do
_G["x"..i]=relation[q][1]
_G["y"..i]=relation[q][2]
end
if _G["x"..i] == nil then
print("transitive")
end
for w=1,3 do
if
_G["y"..i] == relation[w][1] then
relation[w][2] = z
for e=1,3 do
if 
z == relation[e][2] and e ~= w then
if relation[e][2] == _G["x"..i] then
print("transitive")
end
else print("not transitive")
end
end
end
end
end
end
end
print("end loop 1")
for i=n,1,-1 do
if relation[i][1] == relation[i][2] then
print("transitive")
else if relation[i][1] ~= relation[i][2] then
print("checking")
for q=n,1,-1 do
_G["x"..i]=relation[q][1]
_G["y"..i]=relation[q][2]
end
if _G["x"..i] == nil then
print("transitive")
end
for w=n,1,-1 do
if
_G["y"..i] == relation[w][1] then
relation[w][2] = z
for e=n,1,-1 do
if 
z == relation[e][2] and e ~= w then
if relation[e][2] == _G["x"..i] then
print("transitive")
end
else print("not transitive")
end
end
end
end
end
end
end

我以某种方式让它工作了!我不知道怎么做,但它有效,这很重要!

relation={{1,2}, {2,1}, {2,2}}
n=3
for i=1,n do
if relation[i][1] == relation[i][2] then
print("transitive")
else if relation[i][1] ~= relation[i][2] then
print("checking")
for q=1,n do
_G["x"..i]=relation[i][1]
_G["y"..i]=relation[i][2]
end
if _G["x"..i] == nil then
print("transitive")
end
for w=1,3 do
if
_G["y"..i] == relation[w][1] and w ~= i then
relation[w][2] = z
for e=1,3 do
if 
z == relation[e][2] and e ~= w then
if relation[e][2] == _G["x"..i] then
print("transitive")
end
else print("not transitive")
end
end
end
end
end
end
end
print("end loop 1")
for i=n,1,-1 do
if relation[i][1] == relation[i][2] then
print("transitive")
else if relation[i][1] ~= relation[i][2] then
print("checking")
for q=n,1,-1 do
_G["x"..i]=relation[i][1]
_G["y"..i]=relation[i][2]
end
if _G["x"..i] == nil then
print("transitive")
end
for w=n,1,-1 do
if
_G["y"..i] == relation[w][1] and w ~= i then
relation[w][2] = z
for e=n,1,-1 do
if 
z == relation[e][2] and e ~= w then
if relation[e][2] == _G["x"..i] then
print("transitive")
end
else print("not transitive")
end
end
end
end
end
end
end