Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function solve(s) {
- let a = s.split('\n')
- let ports = []
- for (let port of a) {
- ports.push(port.trim().split('/').map(e=>+e))
- }
- let roots = ports.filter(e=>e[0] == 0 || e[1] == 0)
- let nodes = []
- for (let r of roots) {
- nodes.push(new Node(r, ports.slice(0), 1))
- }
- let m = 0
- let ml = 0
- let ml_v = 0
- for (let node of nodes) {
- let ansA = getTotal(node, 0)
- if (ansA > m) {
- m = ansA
- }
- let largest = getLargest(node, 0, 1, [])['a']
- for (let key of largest) {
- if (key['l'] >= ml) {
- ml = key['l']
- if (key['m'] > 0) {
- ml_v = key['m']
- }
- }
- }
- }
- // Max value from all roots
- console.log('Day 24a:',m)
- // Max value of longest bridge
- console.log('Day 24b:',ml_v)
- }
- function getTotal(parent, sum) {
- let val = parent.value[0] + parent.value[1]
- let total = sum + val
- let max = total
- if (parent.children.length > 0) {
- for (let child of parent.children) {
- let res = getTotal(child, total)
- if (res > max) {
- max = res
- }
- }
- }
- return max
- }
- function getLargest(parent, sum, max_length, max_arr) {
- let val = parent.value[0] + parent.value[1]
- let max = sum + val
- let max_len = max_length
- let maxes = max_arr
- if (parent.children.length > 0) {
- for (let child of parent.children) {
- let res = getLargest(child, max, max_len + 1, maxes)
- if (res['l'] >= max_len) {
- maxes.push({'m': res['m'], 'l': res['l']})
- }
- }
- }
- return {'m': max, 'l': max_len, 'a': maxes}
- }
- function Node(v,copy,valid_side) {
- this.value = v
- this.children = []
- let val = this.value
- let c = copy.slice(0)
- c.splice(c.indexOf(val),1)
- if (c.length > 0) {
- for (let el of c) {
- if (el[0] == val[valid_side]) {
- this.children.push(new Node(el, c, 1))
- }
- else if (el[1] == val[valid_side]) {
- this.children.push(new Node(el, c, 0))
- }
- }
- }
- }
- const fs = require('fs')
- const path = 'day24.txt'
- fs.readFile(path, 'utf8', (e, input) => {
- solve(input)
- })
Advertisement
Add Comment
Please, Sign In to add comment