2021 - Day 1 (Sonar Sweep)

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
#!/usr/bin/env python3

#Advent of Code
#2021 Day 1, 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):
    return sum(map(lambda a: a[0] < a[1], zip(puzzle_input[:-1], puzzle_input[1:])))

def main():
    puzzle_input = util.read.as_int_list("\n")

    larger_measurements = solve(puzzle_input)

    print("The number of larger measurements is " + str(larger_measurements) + ".")

class AOC_Tests(unittest.TestCase):
    def test_ex1(self):
        return self.assertEqual(solve([199,
                                       200,
                                       208,
                                       210,
                                       200,
                                       207,
                                       240,
                                       269,
                                       260,
                                       263]), 7)

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
#!/usr/bin/env python3

#Advent of Code
#2021 Day 1, 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):
    total = 0
    for i in range(len(puzzle_input) - 3):
        a = sum(puzzle_input[i : i+3])
        b = sum(puzzle_input[i+1 : i+4])
        total += a < b
    return total

def main():
    puzzle_input = util.read.as_int_list("\n")

    larger_measurements = solve(puzzle_input)

    print("The number of larger measurements is " + str(larger_measurements) + ".")

class AOC_Tests(unittest.TestCase):
    def test_ex1(self):
        return self.assertEqual(solve([199,
                                       200,
                                       208,
                                       210,
                                       200,
                                       207,
                                       240,
                                       269,
                                       260,
                                       263]), 5)

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