Skip to content

Instantly share code, notes, and snippets.

@theglauber
Created December 4, 2019 06:14
Show Gist options
  • Save theglauber/4bc5326b570ed48b0598f523da92d795 to your computer and use it in GitHub Desktop.
Save theglauber/4bc5326b570ed48b0598f523da92d795 to your computer and use it in GitHub Desktop.
Advent of code 2019 day 4
#! python
# https://adventofcode.com/2019/day/4
min = 265275
max = 781584
counter = 0
def check_pw(n):
"""
dupe: number has at least one pair of equal adjacent digits
Will return true if the number has at least one pair of
adjacent digits and the digits never decrease.
"""
dupe = False
prev = None
for c in str(n):
if prev is not None:
if c == prev:
dupe = True
elif c < prev:
return False
prev = c
# if we got here, no decreasing digits
return dupe
for p in range(min, max + 1):
if check_pw(p):
counter += 1
print(counter)
#! python
# https://adventofcode.com/2019/day/4
min = 265275
max = 781584
counter = 0
def check_pw(n):
"""
Will return true if the number has at least one pair of
adjacent digits that are not part of a larger set of
adjacent digits, and the digits never decrease.
So now we need to keep track of how many repeats
there are in a repeating group, and add to the count
only if there is exactly 1 repeat (i.e.: a pair).
We return true if there are no descending digits
and there is at least one pair.
"""
pairs = 0
repeats = 0
prev = None
for c in str(n):
if prev is not None:
if c < prev:
# ooops, decreased
return False
elif c == prev:
# a possible pair
repeats += 1
else:
# different and larger
if repeats == 1:
# found a pair!
pairs += 1
repeats = 0 # reset
prev = c
# if we got here, no decreasing digits
# were the last 2 digits a pair?
if repeats == 1:
pairs += 1
return (pairs > 0)
for n in [ 112233, 123444, 111122 ]:
print( "{} -> {}".format(n, check_pw(n)))
for p in range(min, max + 1):
if check_pw(p):
counter += 1
print(counter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment