adapap

AoC 2017 - 24B Updated

Dec 24th, 2017
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. // Difficulty: 8/10
  2. function solve(s) {
  3. let a = s.split('\n')
  4. let ports = []
  5. for (let port of a) {
  6. ports.push(port.trim().split('/').map(e=>+e))
  7. }
  8. let roots = ports.filter(e=>e[0] == 0 || e[1] == 0)
  9. let nodes = []
  10. for (let r of roots) {
  11. nodes.push(new Node(r, ports.slice(0), 1, 0))
  12. }
  13. let m = 0
  14. let ml = 0
  15. let ml_v = 0
  16. for (let node of nodes) {
  17. let ansA = getTotal(node, 0)
  18. if (ansA > m) {
  19. m = ansA
  20. }
  21. let largest = getLargest(node, 0, node.distance, [])['a']
  22. for (let key of largest) {
  23. if (key['d'] >= ml) {
  24. ml = key['d']
  25. if (key['m'] > ml_v) {
  26. ml_v = key['m']
  27. }
  28. }
  29. }
  30. }
  31. // Max value from all roots
  32. console.log('Day 24a:',m)
  33. // Max value of longest bridge
  34. console.log('Day 24b:',ml_v)
  35. }
  36.  
  37. function getTotal(parent, sum) {
  38. let val = parent.value[0] + parent.value[1]
  39. let total = sum + val
  40. let max = total
  41. if (parent.children.length > 0) {
  42. for (let child of parent.children) {
  43. let res = getTotal(child, total)
  44. if (res > max) {
  45. max = res
  46. }
  47. }
  48. }
  49. return max
  50. }
  51.  
  52. function getLargest(parent, sum, distance, max_arr) {
  53. let val = parent.value[0] + parent.value[1]
  54. let total = sum + val
  55. let max = total
  56. let max_dist = distance
  57. let maxes = max_arr
  58. if (parent.children.length > 0) {
  59. for (let child of parent.children) {
  60. if (child.distance >= max_dist) {
  61. let res = getLargest(child, total, max_dist, maxes)
  62. maxes.push({'m': res['m'], 'd': res['d']})
  63. max_dist = child.distance
  64. }
  65. }
  66. }
  67. return {'m': max, 'd': max_dist, 'a': maxes}
  68. }
  69.  
  70. function Node(v,copy,valid_side,dist) {
  71. this.value = v
  72. this.distance = dist
  73. this.children = []
  74. let val = this.value
  75. let c = copy.slice(0)
  76. c.splice(c.indexOf(val),1)
  77. if (c.length > 0) {
  78. for (let el of c) {
  79. if (el[0] == val[valid_side]) {
  80. this.children.push(new Node(el, c, 1, dist + 1))
  81. }
  82. else if (el[1] == val[valid_side]) {
  83. this.children.push(new Node(el, c, 0, dist + 1))
  84. }
  85. }
  86. }
  87. }
  88.  
  89. const fs = require('fs')
  90. const path = 'day24.txt'
  91. fs.readFile(path, 'utf8', (e, input) => {
  92. solve(input)
  93. })
Advertisement
Add Comment
Please, Sign In to add comment