@@ -300,4 +300,85 @@ describe('Graph', () => {
300300 expect ( graph . getNeighbors ( vertexD ) . length ) . toBe ( 1 ) ;
301301 expect ( graph . getNeighbors ( vertexD ) [ 0 ] . getKey ( ) ) . toBe ( vertexC . getKey ( ) ) ;
302302 } ) ;
303+
304+ it ( 'should return vertices indices' , ( ) => {
305+ const vertexA = new GraphVertex ( 'A' ) ;
306+ const vertexB = new GraphVertex ( 'B' ) ;
307+ const vertexC = new GraphVertex ( 'C' ) ;
308+ const vertexD = new GraphVertex ( 'D' ) ;
309+
310+ const edgeAB = new GraphEdge ( vertexA , vertexB ) ;
311+ const edgeBC = new GraphEdge ( vertexB , vertexC ) ;
312+ const edgeCD = new GraphEdge ( vertexC , vertexD ) ;
313+ const edgeBD = new GraphEdge ( vertexB , vertexD ) ;
314+
315+ const graph = new Graph ( ) ;
316+ graph
317+ . addEdge ( edgeAB )
318+ . addEdge ( edgeBC )
319+ . addEdge ( edgeCD )
320+ . addEdge ( edgeBD ) ;
321+
322+ const verticesIndices = graph . getVerticesIndices ( ) ;
323+ expect ( verticesIndices ) . toEqual ( {
324+ A : 0 ,
325+ B : 1 ,
326+ C : 2 ,
327+ D : 3 ,
328+ } ) ;
329+ } ) ;
330+
331+ it ( 'should generate adjacency matrix for undirected graph' , ( ) => {
332+ const vertexA = new GraphVertex ( 'A' ) ;
333+ const vertexB = new GraphVertex ( 'B' ) ;
334+ const vertexC = new GraphVertex ( 'C' ) ;
335+ const vertexD = new GraphVertex ( 'D' ) ;
336+
337+ const edgeAB = new GraphEdge ( vertexA , vertexB ) ;
338+ const edgeBC = new GraphEdge ( vertexB , vertexC ) ;
339+ const edgeCD = new GraphEdge ( vertexC , vertexD ) ;
340+ const edgeBD = new GraphEdge ( vertexB , vertexD ) ;
341+
342+ const graph = new Graph ( ) ;
343+ graph
344+ . addEdge ( edgeAB )
345+ . addEdge ( edgeBC )
346+ . addEdge ( edgeCD )
347+ . addEdge ( edgeBD ) ;
348+
349+ const adjacencyMatrix = graph . getAdjacencyMatrix ( ) ;
350+ expect ( adjacencyMatrix ) . toEqual ( [
351+ [ 0 , 1 , 0 , 0 ] ,
352+ [ 1 , 0 , 1 , 1 ] ,
353+ [ 0 , 1 , 0 , 1 ] ,
354+ [ 0 , 1 , 1 , 0 ] ,
355+ ] ) ;
356+ } ) ;
357+
358+ it ( 'should generate adjacency matrix for directed graph' , ( ) => {
359+ const vertexA = new GraphVertex ( 'A' ) ;
360+ const vertexB = new GraphVertex ( 'B' ) ;
361+ const vertexC = new GraphVertex ( 'C' ) ;
362+ const vertexD = new GraphVertex ( 'D' ) ;
363+
364+ const edgeAB = new GraphEdge ( vertexA , vertexB , 2 ) ;
365+ const edgeBC = new GraphEdge ( vertexB , vertexC , 1 ) ;
366+ const edgeCD = new GraphEdge ( vertexC , vertexD , 5 ) ;
367+ const edgeBD = new GraphEdge ( vertexB , vertexD , 7 ) ;
368+
369+ const graph = new Graph ( true ) ;
370+ graph
371+ . addEdge ( edgeAB )
372+ . addEdge ( edgeBC )
373+ . addEdge ( edgeCD )
374+ . addEdge ( edgeBD ) ;
375+
376+ const adjacencyMatrix = graph . getAdjacencyMatrix ( ) ;
377+ expect ( adjacencyMatrix ) . toEqual ( [
378+ [ 0 , 2 , 0 , 0 ] ,
379+ [ 0 , 0 , 1 , 7 ] ,
380+ [ 0 , 0 , 0 , 5 ] ,
381+ [ 0 , 0 , 0 , 0 ] ,
382+ ] ) ;
383+ } ) ;
303384} ) ;
0 commit comments