addedge

function addedge( graph, from, to [, undirected] ) --> graph

Description

Adds an edge to a existing graph. If the nodes from or to not existing creates the function the nodes in the graph. The edges are by default direct, with the optional undirected parameter is it possible to define it as undirected edge.

Parameters

graph

The graph that should get the edge.

from

Source node of the edge.

to

Destination node of the edge.

undirected

Optional value that is by default false. Can be true to create undirected edges.

Return Values

graph

The modified graph.

Code

--ZFUNC-addedge-v1
local function addedge( graph, from, to, undirected ) --> graph
   graph[ from ] = graph[ from ] or {}
   graph[ to ] = graph[ to ] or {}
   graph[ from ][ to ] = true
   if undirected then
      graph[ to ][ from ] = true
   end

   return graph
end

return addedge

Examples

local t = require( "taptest" )
local addedge = require( "addedge" )
local adjmatrix = require( "adjmatrix" )
local buildgraph = require( "buildgraph" )
local matrixtostrlst = require( "matrixtostrlst" )

local function tostr( graph, order )
   local m = adjmatrix( graph, order )
   return table.concat( matrixtostrlst( m, "%d", "" ), " " )
end

local nodes = { "a", "b", "c" }
local g = buildgraph( nodes, {} )
-- [ a ] [ b ] [ c ]
t( tostr( g, nodes ), "000 000 000" )

g = addedge( g, "a", "b" )
-- a --> b
-- [ c ]
t( tostr( g, nodes ), "010 000 000" )

g = addedge( g, "b", "d" )
table.insert( nodes, "d" )
-- a --> b --> d
-- [ c ]
t( tostr( g, nodes ), "0100 0001 0000 0000" )

g = addedge( g, "d", "b", false )
-- a --> b <--> d
-- [ c ]
t( tostr( g, nodes ), "0100 0001 0000 0100" )

g = addedge( g, "a", "c", true )
-- c <--> a --> b <--> d
t( tostr( g, nodes ), "0110 0001 1000 0100" )

t()

See also