Skip to content

Instantly share code, notes, and snippets.

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 HumanEquivalentUnit/9fee0c40c5a7ef0ccf632c689a51135a to your computer and use it in GitHub Desktop.
Save HumanEquivalentUnit/9fee0c40c5a7ef0ccf632c689a51135a to your computer and use it in GitHub Desktop.
2017 Advent of Code - day 1
$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