Skip to content

Instantly share code, notes, and snippets.

@m-r-r
Last active December 8, 2017 22:01
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 m-r-r/17514a8b1fb152a18a01f07b8009cf56 to your computer and use it in GitHub Desktop.
Save m-r-r/17514a8b1fb152a18a01f07b8009cf56 to your computer and use it in GitHub Desktop.
Advent of code 2017 — Day 1
// http://adventofcode.com/2017/day/1
// Sums the digits matching the next digit.
// The list is circular: is the first and last digits are the same, the last digit matches.
const sumMatchesNext = input =>
Array.from(String(input)) // Turn the input into an array of characters
.map(Number) // Turn the caracters into number
.reduce((sum, digit, i, digits) => {
const index = (i + 1) % digits.length; // The list is circular
// If the digit is the same as the next digit, add it to the sum
if (digit === digits[index]) {
return sum + digit;
} else {
return sum;
}
}, 0);
// Solution to the second part
const sumMatchesHalwfayAround = input =>
Array.from(String(input)) // Turn the input into an array of characters
.map(Number) // Turn the caracters into number
.reduce((sum, digit, i, digits) => {
const index = i + digits.length / 2;
if (digit === digits[index % digits.length]) {
return sum + digit;
} else {
return sum;
}
}, 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment