2019 - Day 4 (Secure Container)

View puzzle description on AdventOfCode.com
Part 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/env python3

#Advent of Code
#2019 Day 4, Part 1
#Solution by James C. (https://github.com/JamesMCo)

import os, sys
sys.path.append(os.path.abspath("../.."))
import unittest, util.read
from util.tests import run

def solve(puzzle_input):
    def adjacency_rule(n):
        n = str(n)
        for i in range(len(n) - 1):
            if n[i] == n[i+1]:
                return True
        return False

    def increase_rule(n):
        n = str(n)
        return n == "".join(sorted(n))

    count = 0
    for candidate in range(puzzle_input[0], puzzle_input[1] + 1):
        if len(str(candidate)) == 6 and adjacency_rule(candidate) and increase_rule(candidate):
           count += 1
    return count

def main():
    puzzle_input = [int(x) for x in util.read.as_string().split("-")]

    count = solve(puzzle_input)

    print("The number of passwords within the range given is " + str(count) + ".")

class AOC_Tests(unittest.TestCase):
    @unittest.skip("No test cases")
    def test_ex1(self):
        pass

if __name__ == "__main__":
    run(main)
Part 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/env python3

#Advent of Code
#2019 Day 4, Part 2
#Solution by James C. (https://github.com/JamesMCo)

import os, sys
sys.path.append(os.path.abspath("../.."))
import unittest, util.read
from util.tests import run

def solve(puzzle_input):
    def adjacency_rule(n):
        n = str(n)
        for i in range(len(n) - 1):
            if n[i] == n[i+1]:
                if i != 0 and n[i-1] == n[i]:
                    continue
                if i != len(n) - 2 and n[i+2] == n[i]:
                    continue
                return True

        return False

    def increase_rule(n):
        n = str(n)
        return n == "".join(sorted(n))

    count = 0
    for candidate in range(puzzle_input[0], puzzle_input[1] + 1):
        if len(str(candidate)) == 6 and adjacency_rule(candidate) and increase_rule(candidate):
           count += 1
    return count

def main():
    puzzle_input = [int(x) for x in util.read.as_string().split("-")]

    count = solve(puzzle_input)

    print("The number of passwords within the range given is " + str(count) + ".")

class AOC_Tests(unittest.TestCase):
    @unittest.skip("No test cases")
    def test_ex1(self):
        pass

if __name__ == "__main__":
    run(main)
Return to solution index