Skip to content

implemented methods each, each_with_index for edges array #39

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions lib/visual_graphs/graph.rb
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,27 @@ def dump_to_json(path)
File.open(path, 'w') { |f| f.write(@adjacency_list.to_json) }
end


def each(&block)
if block_given?
@edges.each { |e| yield e}
self
else
@edges.to_enum
end
end

def each_with_index(&block)
if block_given?
@edges.each_with_index { |e, i| yield(e, i) }
self
else
@edges.to_enum
end
end



# convert adjacency list based graph to adjacency matrix based graph
# return adjacency matrix based graph
def to_adj_matrix_graph
Expand All @@ -95,4 +116,5 @@ def to_adj_matrix_graph
end

end

end
38 changes: 38 additions & 0 deletions test/adjacency_list_graph_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,42 @@ def test_loop_edge_will_not_add_same_vertex_twice
assert_equal 1, graph.vertices.count(4), 'more than 1 vertex was added during looped-edge inserting'
end

def test_each_for_edges_array
graph = Graph.load_from_json(@filepath)
test_arr=[]
graph.each { |x| test_arr.append(x) }
assert_equal [[1,2], [2, 3], [3, 1]], test_arr
test_arr.clear
graph.insert_edge([1,4])
graph.each { |x| test_arr.append(x) }
assert_equal [[1,2], [2, 3], [3, 1],[1, 4]], test_arr
test_arr.clear
graph.insert_edge([3,2])
graph.each { |x| test_arr.append(x) }
assert_equal [[1,2], [2, 3], [3, 1],[1, 4], [3, 2]],test_arr
end

def test_each_with_index_for_edges_array
graph = Graph.load_from_json(@filepath)
test_arr=[]
graph.each_with_index{ |x, i| test_arr.append(x, i)}
assert_equal [[1, 2], 0, [2, 3], 1, [3, 1], 2],test_arr
test_arr.clear
graph.insert_edge([4, 4])
graph.each_with_index { |x,i| test_arr.append(x, i)}
assert_equal [[1, 2], 0, [2, 3], 1, [3, 1], 2, [4, 4], 3], test_arr
test_arr.clear
graph.insert_edge([1,4])
graph.insert_edge([2,5])
graph.each_with_index { |x, i| test_arr.append(x, i)}
assert_equal [[1, 2], 0, [2, 3], 1, [3, 1], 2, [4, 4], 3, [1, 4], 4, [2, 5], 5], test_arr
test_arr.clear
graph.insert_edge([3,5])
graph.each_with_index { |x, i| test_arr.append(x, i)}
assert_equal [[1, 2], 0, [2, 3], 1, [3, 1], 2, [4, 4], 3, [1, 4], 4, [2, 5], 5, [3, 5], 6], test_arr



end

end