Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- var Immutable = require('immutable');
- var List = Immutable.List;
- var Map = Immutable.Map;
- var Range = Immutable.Range;
- var Set = Immutable.Set;
- var Stack = Immutable.Stack;
- var isNotNull = function (x) { return x !== null; };
- var createNode = function (func, number) {
- return {
- func: func,
- number: number,
- incoming: Math.floor(number / 100),
- outgoing: number % 100,
- neighbours: new List(),
- hasSameFunction: function (other) { return func === other.func; }
- };
- };
- var hasLessThanFourDigits = function (n) { return n < 1000; };
- var hasMoreThanFourDigits = function (n) { return n >= 10000; };
- var calculateFourDigitValues = function (func) {
- return new Range(1)
- .map(func)
- .skipWhile(hasLessThanFourDigits)
- .takeUntil(hasMoreThanFourDigits);
- };
- var findSolution = function (expectedSize, nodes) {
- var find = function (node, result, usedFunctions) {
- var newResult = result.push(node);
- if (newResult.size === expectedSize) {
- if (newResult.first().outgoing === newResult.last().incoming) {
- return newResult;
- }
- } else {
- var subResult = node.neighbours.toSeq().map(function (neighbour) {
- var newUsedFunctions = usedFunctions.add(node.func);
- return (newUsedFunctions.contains(neighbour.func)) ?
- null : find(neighbour, newResult, newUsedFunctions);
- }).find(isNotNull);
- if (subResult !== undefined) { return subResult; }
- }
- return null;
- };
- return nodes.toSeq().map(function (node) {
- return find(node, new Stack(), new Set());
- }).find(isNotNull).map(function (node) { return node.number; });
- };
- var connectNodes = function (nodes) {
- var empty = new List();
- var incoming2nodes = nodes.reduce(
- function (result, node) {
- var incoming = node.incoming;
- return result.set(incoming, result.get(incoming, empty).push(node));
- },
- new Map()
- );
- nodes.forEach(function (node) {
- node.neighbours = incoming2nodes
- .get(node.outgoing, empty)
- .filterNot(node.hasSameFunction);
- });
- };
- var main = function () {
- var functions = List.of(
- function (n) { return n * (n + 1) / 2; },
- function (n) { return n * n; },
- function (n) { return n * (3 * n - 1) / 2; },
- function (n) { return n * (2 * n - 1); },
- function (n) { return n * (5 * n - 3) / 2; },
- function (n) { return n * (3 * n - 2); }
- );
- var nodes = functions.toSeq().flatMap(function (func) {
- return calculateFourDigitValues(func).map(
- function (number) { return createNode(func, number); }
- );
- }).cacheResult();
- connectNodes(nodes);
- var numbers = findSolution(functions.size, nodes);
- console.log(numbers);
- console.log(numbers.reduce(function (a, b) { return a + b; }, 0));
- };
- if (require.main === module) { main(); }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement