|
| 1 | +/** |
| 2 | + * Using the JavaScript language, have the function farthestNodes(strArr) read |
| 3 | + * strArr which will be an array of hyphenated letters representing paths |
| 4 | + * between those two nodes. For example: ["a-b","b-c","b-d"] means that there is |
| 5 | + * a path from node a to b (and b to a), b to c, and b to d. Your program should |
| 6 | + * determine the longest path that exists in the graph and return the length of |
| 7 | + * that path. So for the example above, your program should return 2 because of |
| 8 | + * the paths a-b-c and d-b-c. The path a-b-c also means that there is a path |
| 9 | + * c-b-a. No cycles will exist in the graph and every node will be connected to |
| 10 | + * some other node in the graph. |
| 11 | + * |
| 12 | + * https://www.coderbyte.com/results/bhanson:Farthest%20Nodes:JavaScript |
| 13 | + * |
| 14 | + * @param {array} strArr |
| 15 | + * @return {number} |
| 16 | + */ |
| 17 | +function farthestNodes(strArr) { |
| 18 | + const nodeKeys = new Set(strArr.join('-').split('-')); |
| 19 | + |
| 20 | + const map = new Map(); |
| 21 | + |
| 22 | + // Initialize empty nodes |
| 23 | + nodeKeys.forEach(key => { |
| 24 | + map.set(key, new Node(key)); |
| 25 | + }); |
| 26 | + |
| 27 | + // Connect nodes |
| 28 | + strArr.forEach(connection => { |
| 29 | + const [nodeA, nodeB] = connection.split('-'); |
| 30 | + map.get(nodeA).addEdge(map.get(nodeB)); |
| 31 | + map.get(nodeB).addEdge(map.get(nodeA)); |
| 32 | + }); |
| 33 | + |
| 34 | + // Try each node as a start node |
| 35 | + let longestPath = 0; |
| 36 | + map.forEach(node => { |
| 37 | + const path = node.getFarthestPath(); |
| 38 | + if (path.length > longestPath) { |
| 39 | + longestPath = path.length; |
| 40 | + } |
| 41 | + }); |
| 42 | + |
| 43 | + return longestPath - 1; |
| 44 | +} |
| 45 | + |
| 46 | +function Node(key) { |
| 47 | + this.key = key; |
| 48 | + this.edges = []; |
| 49 | +} |
| 50 | + |
| 51 | +Node.prototype.addEdge = function(node) { |
| 52 | + this.edges.push(node); |
| 53 | +}; |
| 54 | + |
| 55 | +Node.prototype.getFarthestPath = function(visited = []) { |
| 56 | + if (visited.includes(this.key)) { |
| 57 | + return visited; |
| 58 | + } |
| 59 | + |
| 60 | + visited = visited.slice(); |
| 61 | + visited.push(this.key); |
| 62 | + |
| 63 | + const selfAndChildren = []; |
| 64 | + |
| 65 | + this.edges.forEach(edge => { |
| 66 | + const child = edge.getFarthestPath(visited); |
| 67 | + selfAndChildren.push(child); |
| 68 | + }); |
| 69 | + |
| 70 | + if (selfAndChildren.length === 0) { |
| 71 | + return visited; |
| 72 | + } |
| 73 | + |
| 74 | + // Select longest of child paths to return |
| 75 | + selfAndChildren.sort((a, b) => b.length - a.length); |
| 76 | + return selfAndChildren[0]; |
| 77 | +}; |
| 78 | + |
| 79 | +module.exports = farthestNodes; |
0 commit comments