Created
December 19, 2016 15:56
-
-
Save heatherbooker/6c7f42ef16bebd754327315bbb1083c7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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