adapap

AoC 2017 - 24B

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