Skip to content

Instantly share code, notes, and snippets.

@ghaiklor
Last active January 5, 2016 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghaiklor/c20c0c293d30560080cd to your computer and use it in GitHub Desktop.
Save ghaiklor/c20c0c293d30560080cd to your computer and use it in GitHub Desktop.
Advent of Code (Day 13 Part 1)
const fs = require('fs');
const INPUT = fs.readFileSync('./input.txt', 'utf-8').split('\n');
const PERSON_ATTRIBUTES_REGEX = /(\w+) would (\w+) (\d+) happiness units by sitting next to (\w+)./;
// Generate all possible permutations for an array
const permute = input => {
const array = Array.from(input);
const permute = (res, item, key, arr) => {
return res.concat(arr.length > 1 && arr.slice(0, key).concat(arr.slice(key + 1)).reduce(permute, []).map(perm => [item].concat(perm)) || item);
};
return array.reduce(permute, []);
};
// Parse input and return map with attributes of each person
const getPersonAttributes = input => {
return input.reduce((map, person) => {
const parsed = person.match(PERSON_ATTRIBUTES_REGEX);
const name = parsed[1];
const isLose = parsed[2] === 'lose';
const count = +parsed[3];
const neighbour = parsed[4];
return map.set(`${name} -> ${neighbour}`, isLose ? -count : count);
}, new Map());
};
// Get attendees list
const getAttendees = input => {
return input.reduce((set, person) => {
const parsed = person.match(PERSON_ATTRIBUTES_REGEX);
return set.add(parsed[1]);
}, new Set());
};
// Get all persons' attributes
const personAttributes = getPersonAttributes(INPUT);
// Get all possible permutations of the guests
const allPossiblePermutations = permute(getAttendees(INPUT));
const totalHappinnes = allPossiblePermutations.reduce((totalHappiness, permutation) => {
const total = permutation.reduce((total, person, index, arr) => {
const leftOne = arr[index - 1 < 0 ? arr.length - 1 : index - 1];
const rightOne = arr[index + 1 > arr.length - 1 ? 0 : index + 1];
total += personAttributes.get(`${person} -> ${leftOne}`);
total += personAttributes.get(`${person} -> ${rightOne}`);
return total;
}, 0);
return total > totalHappiness ? total : totalHappiness;
}, 0);
console.log(totalHappinnes);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment