Advent of Code 2020


Reading time: about 4 minutes

Day 1

For this challenge, we need to find two numbers from our input that sum to 2020, and calculate their multiplication.

In [2]:
def mul(numbers):
    x = 1
    for n in numbers:
        x *= n
    return x
In [3]:
def day_1(nums, N = 2):
    for numbers in itertools.combinations(nums, N):
        if sum(numbers) == 2020:
            return mul(numbers)
In [4]:
day_1(read_numbers("day-1-example.txt"))
Out [4]:
514579
In [5]:
day_1(read_numbers("day-1.txt"))
Out [5]:
224436

Part Two

Part two uses the same input but wants the product of three numbers that add up to 2020.

In [6]:
day_1(read_numbers("day-1.txt"), 3)
Out [6]:
303394260

Day 2

Password rules

Part one

In [7]:
def is_valid(line):
    rule, password = line.split(": ")
    num, letter = rule.split(" ")
    low, high = num.split("-")
    low, high = int(low), int(high)
    
    count = password.count(letter)
    return count >= low and count <= high
In [8]:
def num_valid(path):
    lines = read_lines(path)
    valid_lines = map(is_valid, lines)
    return sum(valid_lines)
In [9]:
num_valid("day-2-example.txt")
num_valid("day-2.txt")
Out [9]:
2
Out [9]:
528

Part two

In [10]:
def is_valid(line):
    rule, pw = line.split(": ")
    num, letter = rule.split(" ")
    pos1, pos2 = num.split("-")
    pos1, pos2 = int(pos1) - 1, int(pos2) - 1
    
    res = int(pw[pos1] == letter)
    res += int(pw[pos2] == letter)
    
    return res == 1
In [11]:
num_valid("day-2.txt")
Out [11]:
497

The following pages link here

Citation

If you find this work useful, please cite it as:
@article{yaltirakli202012adventofcode2020,
  title   = "Advent of Code 2020",
  author  = "Yaltirakli, Gokberk",
  journal = "gkbrk.com",
  year    = "2020",
  url     = "https://www.gkbrk.com/2020/12/advent-of-code-2020/"
}
Not using BibTeX? Click here for more citation styles.
IEEE Citation
Gokberk Yaltirakli, "Advent of Code 2020", December, 2020. [Online]. Available: https://www.gkbrk.com/2020/12/advent-of-code-2020/. [Accessed Oct. 10, 2024].
APA Style
Yaltirakli, G. (2020, December 01). Advent of Code 2020. https://www.gkbrk.com/2020/12/advent-of-code-2020/
Bluebook Style
Gokberk Yaltirakli, Advent of Code 2020, GKBRK.COM (Dec. 01, 2020), https://www.gkbrk.com/2020/12/advent-of-code-2020/

Comments

© 2024 Gokberk Yaltirakli