Aaron Andersen

GraphShop Script Examples

The following examples demonstrate how easy it is to write custom graph functions and algorithms using GraphShop's scripting module. To use one of these functions in your own scripts, copy and paste the code into the code editor window. You may then write the remainder of your script below the function definition, or immediately click run to parse and define the function. The function can then be referenced and called from either the code editor or the script editor windows. Once a defined, a function's source may (if desired) be removed from the code editor window.

Complete Graph

// Complete graph on n vertices
function completeGraph(n)
{
	var g = new Graph("K"+n);
	for(var i=0; i<n; i++)
	{
		for(var j=i+1; j<n; j++)
		{
			g.addEdge(i, j);
		}
	}
	
	return g;
}

Random Graph

// Random n-graph with edge probability p
function randomGraph(n, p)
{
	var g = new Graph("R"+n);
	
	for(var i=0; i<n; i++)
	{
		for(j=i+1; j<n; j++)
		{
			if(Math.random() < p)
			{
				g.addEdge(i, j);
			}
		}
	}
	
	return g;
}

Random Tournament

// Random n-tournament
function randomTournament(n)
{
	var g = new Graph("T"+n);
	
	for(var i=0; i<n; i++)
	{
		for(j=i+1; j<n; j++)
		{
			if(Math.random() > 0.5)
			{
				g.addArc(i, j);
			}
			else
			{
				g.addArc(j, i);
			}
		}
	}
	
	return g;
}

Randomize Arc Directions

// Randomize arc directions
function randomizeArcDirections(g)
{
	for(var a=0; a<g.arcCount(); a++)
	{
		if(Math.random() > 0.5)
		{
			g.flipArc(g.getArc(a));
		}
	}
}

Graph Union

// Simple edge-union
function graphUnion(g1, g2)
{
	var n1 = g1.vertexCount();
	var n2 = g2.vertexCount();
	var ng = Math.max(g1, g2);

	var g = new Graph(g1.label() + " union " + g2.label());
	
	for(var i=0; i<ng; i++)
	{
		g.addVertex();
	
		for(j=i+1; j<ng; j++)
		{
			if((n1 >= j && g1.hasEdge(i, j)) || 
			   (n2 >= j && g2.hasEdge(i, j)))
			{
				g.addEdge(i, j);
			}
		}
	}
	
	return g;
}

Graph Intersection

// Simple edge-intersection
function graphIntersection(g1, g2)
{
	var n1 = g1.vertexCount();
	var n2 = g2.vertexCount();
	var ng = Math.min(g1, g2);

	var g = new Graph(g1.label() + " intersect " + g2.label());
	
	for(var i=0; i<ng; i++)
	{
		g.addVertex();
	
		for(j=i+1; j<ng; j++)
		{
			if(g1.hasEdge(i, j) && g2.hasEdge(i, j))
			{
				g.addEdge(i, j);
			}
		}
	}
	
	return g;
}