Add Prim.

This commit is contained in:
Oleksii Trekhleb
2018-05-07 12:45:10 +03:00
parent 50df3bf717
commit cad8ccd9bb
9 changed files with 194 additions and 2 deletions

View File

@ -110,12 +110,18 @@ export default class Graph {
return null;
}
/**
* @return {number}
*/
getWeight() {
return this.getAllEdges().reduce((weight, graphEdge) => {
return weight + graphEdge.weight;
}, 0);
}
/**
* @return {string}
*/
toString() {
return Object.keys(this.vertices).toString();
}

View File

@ -19,4 +19,11 @@ export default class GraphEdge {
return `${startVertexKey}_${endVertexKey}`;
}
/**
* @return {string}
*/
toString() {
return this.getKey();
}
}

View File

@ -1,6 +1,9 @@
import LinkedList from '../linked-list/LinkedList';
export default class GraphVertex {
/**
* @param {*} value
*/
constructor(value) {
if (value === undefined) {
throw new Error('Graph vertex must have a value');
@ -37,6 +40,13 @@ export default class GraphVertex {
return edges.map(neighborsConverter);
}
/**
* @return {GraphEdge[]}
*/
getEdges() {
return this.edges.toArray().map(linkedListNode => linkedListNode.value);
}
/**
* @param {GraphEdge} requiredEdge
* @returns {boolean}

View File

@ -8,6 +8,7 @@ describe('GraphEdge', () => {
const edge = new GraphEdge(startVertex, endVertex);
expect(edge.getKey()).toBe('A_B');
expect(edge.toString()).toBe('A_B');
expect(edge.startVertex).toEqual(startVertex);
expect(edge.endVertex).toEqual(endVertex);
expect(edge.weight).toEqual(0);

View File

@ -21,17 +21,20 @@ describe('GraphVertex', () => {
expect(vertex.toString()).toBe('A');
expect(vertex.getKey()).toBe('A');
expect(vertex.edges.toString()).toBe('');
expect(vertex.getEdges()).toEqual([]);
});
it('should add edges to vertex and check if it exists', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const edgeAB = new GraphEdge(vertexA, vertexB);
vertexA.addEdge(edgeAB);
expect(vertexA.hasEdge(edgeAB)).toBeTruthy();
expect(vertexB.hasEdge(edgeAB)).toBeFalsy();
expect(vertexA.getEdges().length).toBe(1);
expect(vertexA.getEdges()[0].toString()).toBe('A_B');
});
it('should return vertex neighbors in case if current node is start one', () => {