Skip to content

Instantly share code, notes, and snippets.

@heatherbooker
Created December 19, 2016 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heatherbooker/6c7f42ef16bebd754327315bbb1083c7 to your computer and use it in GitHub Desktop.
Save heatherbooker/6c7f42ef16bebd754327315bbb1083c7 to your computer and use it in GitHub Desktop.
const vertices = ['james', 'jon', 'joe', 'moe', 'moda'];
const vertices2 = ['jon', 'joe', 'moe'];
const vertices3 = ['james', 'joe', 'moda'];
const edges = [['james', 'jon'], ['james', 'joe'], ['jon', 'joe'], ['joe', 'moe'], ['moe', 'moda'], ['moda', 'james']];
const edges2 = [['jon','joe'], ['joe', 'moe'], ['moe', 'jon']];
const edges3 = [['james', 'joe'], ['moda', 'james']];
function createAdjacencyList(vertices, edges) {
const adjList = {};
vertices.forEach(vertex => {
adjList[vertex] = [];
edges.forEach(edge => {
const vertexIndex = edge.indexOf(vertex);
if (vertexIndex > -1) {
const adjVertex = edge[Number(!vertexIndex)];
adjList[vertex].push(adjVertex);
}
});
});
return adjList;
}
function isNeighbour(adjList, vertex, neighbour) {
return adjList[vertex].includes(neighbour);
}
function isTree(adjList) {
// TODO: make this function correct.
const numVertices = Object.keys(adjList).length;
let numEdges = 0;
for (let key in adjList) {
console.log(adjList[key]);
// numVertices minus 1 because doesn't include reference to self.
if (adjList[key].length === numVertices - 1) {
numEdges++;
}
}
return numEdges !== numVertices;;
}
const adjList = createAdjacencyList(vertices, edges);
const adjList2 = createAdjacencyList(vertices2, edges2);
const adjList3 = createAdjacencyList(vertices3, edges3);
console.log(adjList);
console.log(isTree(adjList));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment