var components = require("fs").readFileSync("input.txt").toString().split("\n").filter(a=>(a)).map(a=>(a.split("/").map(b=>(parseInt(b))))); var finalBridges = []; function getLongerChains(state){ var additions = components.filter(a=>(state.components.indexOf(a) == -1)).filter(a=>(a[0] == state.end || a[1] == state.end)); if(additions.length == 0){ finalBridges.push(state.components) } else{ additions.forEach(a=>{ var newState = { components: state.components.slice(), end: a.filter((b,i)=>(i!=a.indexOf(state.end)))[0] } newState.components.push(a); getLongerChains(newState); }); } } getLongerChains({ components: [], end: 0 }); var bridgeLengths = finalBridges.map(bridge=>(bridge.length)); var maxLength = bridgeLengths.reduce((g, b)=>((b>g || g==null) ? b : g),null); var maxLengthBridges = finalBridges.filter(bridge=>(bridge.length == maxLength)); var bridgeStrengths = maxLengthBridges.map(bridge=>(bridge.map(a=>(a[0] + a[1])).reduce((a,b)=>(a+b)))); var maxStrength = bridgeStrengths.reduce((g, b)=>((b>g || g==null) ? b : g),null); console.log(maxStrength);