buildgraph

function buildgraph( nodes, edges [, undirected] ) --> graph

Description

Creates a graph data structure with the defined nodes and edges. If the nodes from the edges are 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

nodes

The nodes for the graph.

edges

The edges that should be created.

undirected

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

Return Values

graph

The created graph.

Code

--ZFUNC-buildgraph-v1
local function buildgraph( nodes, edges, undirected ) --> graph
   local graph = {}

   for _, node in ipairs( nodes ) do
      graph[ node ] = {}
   end

   for i, edge in ipairs( edges ) do
      local x = edge[ 1 ]
      graph[ x ] = graph[ x ] or {}
      local y = edge[ 2 ]
      graph[ y ] = graph[ y ] or {}
      graph[ x ][ y ] = true
      if undirected then
         graph[ y ][ x ] = true
      end
   end

   return graph
end

return buildgraph

Examples

local t = require( "tapered" )
local buildgraph = require( "buildgraph" )
-- util functions
local keys = require( "keys" )
local like = require( "like" )

local nodes = { "a", "b", "c", "d" }

local edges = {
   { "a", "b" },
   { "b", "c" },
   { "b", "d" },
   { "c", "e" }
}

local g = buildgraph( nodes, edges )
t.ok( like( keys( g ), { "a", "b", "c", "d", "e" } ) )
t.ok( like( keys( g[ "a" ] ), { "b" } ) )
t.ok( like( keys( g[ "b" ] ), { "c", "d" } ) )
t.ok( like( keys( g[ "c" ] ), { "e" } ) )
t.ok( like( keys( g[ "d" ] ), {} ) )
t.ok( like( keys( g[ "e" ] ), {} ) )

g = buildgraph( nodes, edges, false )
t.ok( like( keys( g ), { "a", "b", "c", "d", "e" } ) )
t.ok( like( keys( g[ "a" ] ), { "b" } ) )
t.ok( like( keys( g[ "b" ] ), { "c", "d" } ) )
t.ok( like( keys( g[ "c" ] ), { "e" } ) )
t.ok( like( keys( g[ "d" ] ), {} ) )
t.ok( like( keys( g[ "e" ] ), {} ) )

g = buildgraph( nodes, edges, true )
t.ok( like( keys( g ), { "a", "b", "c", "d", "e" } ) )
t.ok( like( keys( g[ "a" ] ), { "b" } ) )
t.ok( like( keys( g[ "b" ] ), { "a", "c", "d" } ) )
t.ok( like( keys( g[ "c" ] ), { "b", "e" } ) )
t.ok( like( keys( g[ "d" ] ), { "b" } ) )
t.ok( like( keys( g[ "e" ] ), { "c" } ) )

t.done()