Advertisement
pkspyder

Untitled

Jan 30th, 2023 (edited)
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. /**
  2. * Each beacon is represented as (x, y, r)
  3. * ToDo: Your changes go here
  4. */
  5. function maximumActivations(beacons) {
  6. const graph = new Map();
  7. const visited = new Set();
  8.  
  9. // Create a graph where each node is a beacon and edges are drawn between
  10. // two nodes if the range of one node covers the other node
  11. for (let i = 0; i < beacons.length; i++) {
  12. for (let j = i + 1; j < beacons.length; j++) {
  13. const [x1, y1, r1] = beacons[i];
  14. const [x2, y2, r2] = beacons[j];
  15. const distance = Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2);
  16. if (distance <= r1 + r2) {
  17. if (!graph.has(i)) graph.set(i, []);
  18. if (!graph.has(j)) graph.set(j, []);
  19. graph.get(i).push(j);
  20. graph.get(j).push(i);
  21. }
  22. }
  23. }
  24.  
  25. let maxSize = 0;
  26.  
  27. // Perform DFS from each node and keep track of the size of the connected component
  28. for (let i = 0; i < beacons.length; i++) {
  29. if (!visited.has(i)) {
  30. let size = {val: 0};
  31. dfs(i, size);
  32. maxSize = Math.max(maxSize, size.val);
  33. }
  34. }
  35.  
  36. function dfs(node, size) {
  37. visited.add(node);
  38. size.val++;
  39. if (graph.has(node)) {
  40. for (const nextNode of graph.get(node)) {
  41. if (!visited.has(nextNode)) {
  42. dfs(nextNode, size);
  43. }
  44. }
  45. }
  46. }
  47.  
  48. return maxSize;
  49. }
  50.  
  51.  
  52.  
  53. function testSolution() {
  54. testCases = [
  55. [[1, 2, 3], [2, 3, 1], [3, 4, 2], [4, 5, 3], [5, 6, 4]],
  56. [[1, 2, 3], [2, 3, 1], [3, 4, 2], [4, 5, 2], [7, 7, 1]],
  57. [[1, 1, 5], [10, 10, 5]],
  58. [[2, 1, 3], [6, 1, 4]],
  59. [[1, 2, 3], [3, 4, 2], [8, 9, 2], [6, 7, 1], [5, 5, 1]],
  60. [[1, 2, 3], [3, 4, 2], [8, 9, 2], [6, 7, 1], [5, 5, 1], [0, 0, 1]],
  61. ]
  62. maxActivations = [5, 4, 1, 2, 2, 3]
  63. let success = 0
  64. for (let id = 0; id < testCases.length; id++) {
  65. if (maximumActivations(testCases[id]) == maxActivations[id]) success += 1
  66. }
  67. console.log(`# of test cases passed: ${success}/${testCases.length}`)
  68. }
  69.  
  70. testSolution()
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement