adjmatrix

function adjmatrix( graph, order ) --> matrix

Description

Return the adjacency matrix of graph. The row/column order es defined by order.

Parameters

graph

A graph structure.

order

An array of nodes from graph that defines the row/column of the matrix. Can also be used the select just a part of the nodes,

Return Values

matrix

The adjacency matrix representation of graph.

Code

--ZFUNC-adjmatrix-v1
local function adjmatrix( graph, order ) --> matrix
   local matrix = {}

   for x, v in ipairs( order ) do
      matrix[ x ] = {}
      for y, e in ipairs( order ) do
         if graph[ v ][ e ] then
            matrix[ x ][ y ] = 1
         else
            matrix[ x ][ y ] = 0
         end
      end
   end

   return matrix
end

return adjmatrix

Examples

local t = require( "tapered" )
local adjmatrix = require( "adjmatrix" )
-- util functions
local buildgraph = require( "buildgraph" )
local matrixtostrlst = require( "matrixtostrlst" )

local function tostr( matrix )
   return table.concat( matrixtostrlst( matrix, "%d", "" ), " " )
end

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

local g = buildgraph( nodes, edges )
-- a --> b ---------> c
--        \         /
--         --> d -->
local m = adjmatrix( g, nodes )
t.same( tostr( m ), "0100 0011 0000 0010" )

m = adjmatrix( g, { "a", "b", "c" } )
t.same( tostr( m ), "010 001 000" )

t.done()