Last active
December 8, 2017 22:01
-
-
Save m-r-r/17514a8b1fb152a18a01f07b8009cf56 to your computer and use it in GitHub Desktop.
Advent of code 2017 — Day 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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