Skip to content

Commit 92eafba

Browse files
committed
added method to add edge on graph
1 parent a847d3b commit 92eafba

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

data_structure/graph/graph.lua

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,16 @@ function Graph:add_vertex(vertex)
3939
return false
4040
end
4141

42+
function Graph:add_edge(edge)
43+
if type(edge) ~= 'table' then return false end
44+
45+
if self._graph[edge[1]] == nil then
46+
self._graph[edge[1]] = {edge[2]}
47+
else
48+
table.insert(self._graph[edge[1]], edge[2])
49+
end
50+
51+
return true
52+
end
53+
4254
return Graph

data_structure/graph/test.lua

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,3 +62,30 @@ test('should not add vertex', function()
6262
assert_equal(graph:add_vertex('b'), false)
6363
assert_equal(#graph:get_vertices(), 2)
6464
end)
65+
66+
test('should not add edge', function()
67+
local graph = Graph:new({})
68+
69+
assert_equal(graph:add_edge('a'), false)
70+
assert_equal(#graph:get_vertices(), 0)
71+
end)
72+
73+
test('add edge in a new vertex', function()
74+
local graph = Graph:new({})
75+
76+
assert_equal(graph:add_edge({'a', 'b'}), true)
77+
assert_equal(#graph:get_vertices(), 1)
78+
79+
local edge = graph:get_edges()
80+
assert_equal(edge[1][1], 'a')
81+
assert_equal(edge[1][2], 'b')
82+
end)
83+
84+
test('add edge in a old vertex', function()
85+
local graph = Graph:new({
86+
['a'] = {'b'}
87+
})
88+
89+
assert_equal(graph:add_edge({'a', 'c'}), true)
90+
assert_equal(#graph:get_vertices(), 1)
91+
end)

0 commit comments

Comments
 (0)