diff --git a/src/App.svelte b/src/App.svelte index 8f06687..7bc9c6b 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -1,10 +1,41 @@ + +
-
change(0)} /> -
change(1)} /> -
change(2)} /> -
change(3)} /> -
change(4)} /> -
change(5)} /> -
change(6)} /> -
change(7)} /> -
change(8)} /> -
change(9)} /> -
change(10)} /> -
change(11)} /> -
change(12)} /> -
change(13)} /> -
change(14)} /> + {#each states as _, i} +
change(i)}> + {i} +
+ {/each}
diff --git a/src/Graph.js b/src/Graph.js new file mode 100644 index 0000000..b236d1b --- /dev/null +++ b/src/Graph.js @@ -0,0 +1,42 @@ +// an undirected graph +class Graph { + constructor() { + // Graph has an adjacencyList attribute set as an object + this.adjacencyList = {} + } + + addVertex(vertex) { + // to avoid overwriting the existing vertex, we need if statement + if (!this.adjacencyList[vertex]) this.adjacencyList[vertex] = [] + } + + addEdge(vertex1, vertex2) { + // undirected graph is two way connection + //we push both vertices to each other's array + this.adjacencyList[vertex1].push(vertex2) + this.adjacencyList[vertex2].push(vertex1) + } + + removeEdge(ver1, ver2) { + // two way connection, delete from both arrays + this.adjacencyList[ver1] = this.adjacencyList[ver1].filter( + v => v !== ver2 + ) + this.adjacencyList[ver2] = this.adjacencyList[ver2].filter( + v => v !== ver1 + ) + } + + removeVertex(vertex) { + // first find all the conncetion, and remove all edges from both parties, + // and then delete the vertex from the adjacency list + let edges = this.adjacencyList[vertex] + + for (let edge of edges) { + this.removeEdge(vertex, edge) + } + delete this.adjacencyList[vertex] + } +} + +export default Graph