What Ivan said, and also if you add them in a "canonical" order (any order that is well defined will do, for example lexicographical order of an,bn and xn,yn) rather than arbitrary, you can later just look for duplicates and remove them.
To insert the edges in lexicographical order, you can do for example:
Code: Select all
function addEdge(a, b, x, y)
if a > x or a == x and b > y then
a, b, x, y = x, y, a, b
end
edges[#edges+1] = {{a, b}, {x, y}}
end
With Ivan's method:
Code: Select all
function addEdge(pointA, pointB)
if pointA[1] > pointB[1] or pointA[1] == pointB[1] and pointA[2] > pointB[2] then
pointA, pointB = pointB, pointA
end
edges[#edges+1] = {pointA, pointB}
end
For using Ivan's trick this way, you must have no duplicate points to start with, otherwise you can have points that compare different but have the same values.
You can use mr_happy's suggestion above too, and check if an edge is already in the list before inserting it. That would spare you from having to remove duplicates. But if you absolutely need to remove duplicates later, it can be done easily in O(n²) steps with two nested loops:
Code: Select all
-- this code assumes Ivan's trick, and that the edges are in some
-- canonical order, to spare us from having to compare A,B and B,A
function removeDupes()
for i = #edges - 1, 1, -1 do
local edge_i_1, edge_i_2 = edges[i][1], edges[i][2]
for j = #edges, i + 1, -1 do
if edge_i_1 == edges[j][1] and edge_i_2 == edges[j][2] then
table.remove(edges, j)
end
end
end
end