Created
December 1, 2017 08:21
-
-
Save HumanEquivalentUnit/9fee0c40c5a7ef0ccf632c689a51135a to your computer and use it in GitHub Desktop.
2017 Advent of Code - 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
$in = '1212' | |
# Just regex out the characters which are the same as the following character, with a backreference | |
# convert to int, and sum them. Handle the wraparound condition by adding the first character | |
# to the end of the string | |
function day1 { | |
param($s) | |
$s = $s + $s[0] | |
[regex]::Matches($s, '(.)(?=\1)') |% { [int]($_.Groups[1].Value) } | measure -Sum | % sum | |
} | |
day1 $in | |
# Can't do part2 with regex as easily; | |
# loop through the indexes, use remainder calculation to wrap around. | |
# careful to convert strings to digit-value-ints, not chars to ASCII-character-code-ints | |
function day1-part2 { | |
param([string]$s) | |
$halfway = $s.Length / 2 | |
$nums = for ($i = 0; $i -lt $s.Length; $i++) | |
{ | |
$nextidx = ($i + $halfway) % $s.Length | |
if ($s[$i] -eq $s[$nextidx]) | |
{ | |
[int][string]$s[$i] | |
} | |
} | |
$nums | Measure-Object -Sum | Select-Object -ExpandProperty Sum | |
} | |
day1-part2 $in |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment