AdventOfCode 2022

Utils

src.aoc2022.utils.get_raw_data(file_path: str) → str

Returns the raw data from a path

Parameters:

file_path (str) – filepath for data

Returns:

Raw text input for example

Return type:

str

Days

Day 1

src.aoc2022.days.day1.get_3_largest_group_sum(groups: List[List[int]]) → List[Tuple[int, int]]

Finds the 3 top group with the largests sums

Parameters:

groups (List[List[int]]) – A list of groups, where each group is a list of integers

Returns:

Index of the 3 groups with the largests sums + corresponding sums

Return type:

List[Tuple[int, int]]

src.aoc2022.days.day1.get_largest_group_sum(groups: List[List[int]]) → Tuple[int, int]

Finds the group with the largest sum

Parameters:

groups (List[List[int]]) – A list of groups, where each group is a list of integers

Returns:

Index of the group with the largest sum and corresponding sum

Return type:

Tuple[int, int]

src.aoc2022.days.day1.parse_data_to_array(raw_data: str) → List[List[int]]

Parses the raw text input into lists of numerical values, with one list per grouping of lines

Parameters:

raw_data (str) – Raw text data to be parsed

Returns:

Parsed integer values

Return type:

List[List[int]]

Day 2

class src.aoc2022.days.day2.Move(value)

Enum for valid Rock-Paper-Scissors game

PAPER = 2

Value for ‘Paper’ move.

ROCK = 1

Value for ‘Rock’ move.

SCISSORS = 3

Value for ‘Scissors’ move.

class src.aoc2022.days.day2.Strategy(value)

Enum for valid strategies

DRAW = 2

Value for ‘Draw’ strategy.

LOSE = 1

Value for ‘Lose’ strategy.

WIN = 3

Value for ‘Win’ strategy.

src.aoc2022.days.day2.calculate_points(rounds: List[Tuple[int, int]], pts_mapping: Dict[Tuple[int, int], int]) → int

Calculates the number of points given a list of rounds and a point mapping

Parameters:
  • rounds (List[Tuple[Enum, Enum]]) – List of tuples for each round

  • pts_mapping (Dict[str, Enum]) – Mapping to convert a round to a point count

Returns:

Total score across all rounds

Return type:

int

src.aoc2022.days.day2.parse_data(raw_data: str, l_mapping: Dict[str, Move], r_mapping: Union[Dict[str, Move], Dict[str, Strategy]]) → List[Tuple[int, int]]

Parses the raw text input into lists of tuples of (Enum, Enum)

Parameters:
  • raw_data (str) – Raw text data to be parsed

  • l_mapping – Mapping to convert string to enum value

  • r_mapping – Mapping to convert string to enum value

Returns:

List of parsed tuples

Return type:

List[Tuple[Enum, Enum]]

Day 3

src.aoc2022.days.day3.count_total_priority(items: List[List[int]]) → int

Count the total priority for the 2 compartment case

Parameters:

items (List[List[int]]) – list of all backpack contents

Returns:

total sum of priority for the shared items

Return type:

int

src.aoc2022.days.day3.count_triplet_priority(items: List[List[int]]) → int

Count the total priority for the 3 compartment case

Parameters:

items (List[List[int]]) – list of all backpack contents

Returns:

total sum of priority for the shared items

Return type:

int

src.aoc2022.days.day3.get_shared_element(left_list: List[int], right_list: List[int]) → int

Get the shared element between the two lists

Parameters:
  • left_list (List[int]) – left list of items

  • right_list (List[int]) – right list of items

Returns:

shared element between lists

Return type:

int

src.aoc2022.days.day3.get_triplet_shared_element(left_list: List[int], middle_list: List[int], right_list: List[int]) → int

Get the shared element between the three lists

Parameters:
  • left_list (List[int]) – left list of items

  • middle_list (List[int]) – left list of items

  • right_list (List[int]) – right list of items

Returns:

shared element between lists

Return type:

int

src.aoc2022.days.day3.item_priority(char: str) → int

Get the priority value for a character

Parameters:

char (str) – the character to convert to a priority value

Returns:

Priority value

Return type:

int

src.aoc2022.days.day3.parse_data_to_array(raw_data: str) → List[List[int]]

Parses the raw text input into lists of priority values

Parameters:

raw_data (str) – Raw text data to be parsed

Returns:

Parsed list of lists values

Return type:

List[List[int]]

Day 4

src.aoc2022.days.day4.parse_data_to_array(raw_data: str) → List[Tuple[int, int, int, int]]

Parses the raw text input into lists of value tuples

Parameters:

raw_data (str) – Raw text data to be parsed

Returns:

Parsed list of value tuples

Return type:

List[Tuple[int]]

src.aoc2022.days.day4.set_contains_other_set(ranges: Tuple[int, int, int, int]) → bool

check whether one of the ranges in entirely contained by the other

Parameters:

ranges (Tuple[int]) – tuple of (start_left, end_left, start_right, end_right)

Returns:

flag whether if one set is a subset of the other

Return type:

bool

src.aoc2022.days.day4.set_overlaps(ranges: Tuple[int, int, int, int]) → bool

check whether the sets overlap at all

Parameters:

ranges (Tuple[int]) – tuple of (start_left, end_left, start_right, end_right)

Returns:

flag whether the sets overlap

Return type:

bool

Day 5

src.aoc2022.days.day5.parse_data(raw_data: str) → Tuple[Tuple[List[str], ...], List[Tuple[int, int, int]]]

Parses the raw text input into the initial configuration and the move list

Parameters:

raw_data (str) – Raw text data to be parsed

Returns:

Initial Configuration and move list

Return type:

List[Tuple[int]]

src.aoc2022.days.day5.transfer_items(stacks: Tuple[List[str], ...], moves: List[Tuple[int, int, int]]) → str

Computes the final state of the stacks after applying the moves

Parameters:
  • stacks (Tuple[List[str]]) – Tuple of lists representing each stack

  • moves (List[Tuple[int]]) – List of tuples for each move

Returns:

value at the top of each stack after moves

Return type:

str

src.aoc2022.days.day5.transfer_multiple_items(stacks: Tuple[List[str], ...], moves: List[Tuple[int, int, int]]) → str

Computes the final state of the stacks after applying the moves moving multiple boxes in a single move

Parameters:
  • stacks (Tuple[List[str]]) – Tuple of lists representing each stack

  • moves (List[Tuple[int]]) – List of tuples for each move

Returns:

value at the top of each stack after moves

Return type:

str

Day 6

src.aoc2022.days.day6.detect_start_of_packet(sequence: str, num_distinct: int) → int

Identifies the position of the starting packet defined by num_distinct consecutive unique characters

Parameters:
  • sequence (str) – Sequence of characters to detect the start packet

  • num_distinct (int) – Number of consecutive distinct characters needed

Returns:

Position of the end of the starting packet

Return type:

int

Day 7

class src.aoc2022.days.day7.DirectoryNode(dirname: str, level: int)

Class representing a single directory

Parameters:
  • dirname (str) – the name of the directory

  • level (int) – the depth of the directory in the tree structure

add_child(child: DirectoryNode)

Add a child directory to this directory

Parameters:

child (DirectoryNode) – child directory to add

add_file(file: FileNode)

Add a child file to this directory

Parameters:

child (FileNode) – child file to add

get_child(dirname: str)

Get a child directory by name

Parameters:

dirname (str) – name of child directory to retrieve

update_size(updated_size: int)

Update the size of this directory

Parameters:

updated_size (int) – number of bytes to add to current size

class src.aoc2022.days.day7.FileNode(filesize: int, filename: str)

Class representing a single file

Parameters:
  • filesize (int) – the size of the file in bytes

  • filename (str) – the name of the file

src.aoc2022.days.day7.get_directories_under_size(root: DirectoryNode, max_size: int) → int

Calculates the sum of directory sizes for all directories with a max size under the given threshold

Parameters:
  • root (DirectoryNode) – root node for the directory/file tree

  • max_size (int) – maximum allowable size for a directory to be kept

Returns:

sum of total sizes for directories smaller than max_size

Return type:

int

src.aoc2022.days.day7.get_smallest_directory_to_delete(root: DirectoryNode, total_space: int, needed_space: int) → int

Find the smallest directory to delete to free the needed space

Parameters:
  • root (DirectoryNode) – root node for the directory/file tree

  • total_space (int) – total space of the storage device

  • needed_space (int) – amount of free space required

Returns:

size of the directory to delete

Return type:

int

src.aoc2022.days.day7.parse_data_to_tree(raw_data: str) → DirectoryNode

Parse the raw data into a tree-structure representing the nodes and files

Parameters:

raw_data (str) – Raw data containing commands

Returns:

Root of the directory tree

Return type:

DirectoryNode

src.aoc2022.days.day7.tree_iterator(node: DirectoryNode) → Generator[DirectoryNode, None, None]

Produces a generator for traversing the directory/file tree

Parameters:

node (DirectoryNode) – node to traverse

Returns:

Generator for traversing the directory/file tree

Return type:

Generator[DirectoryNode]

Day 8

src.aoc2022.days.day8.compute_scenic_score(height_map: ndarray, pos: Tuple[int, int]) → int

Compute the scenic view given a starting position

Parameters:
  • height_map (np.ndarray) – 2D array of heights

  • pos (Tuple[int, int]) – tuple of (x, y) positions in the grid

Returns:

Scenic score of the position given

Return type:

int

src.aoc2022.days.day8.count_visible_trees(height_map: ndarray) → int

Count number of trees visible from perimeter

Parameters:

height_map (np.ndarray) – 2D array of heights

Returns:

Total count of trees visible from perimeter

Return type:

int

src.aoc2022.days.day8.get_max_scenic_score(height_map: ndarray) → int

Find the maximum scenic score given the height map

Parameters:

height_map (np.ndarray) – 2D array of heights

Returns:

Maximum possible scenic score

Return type:

int

src.aoc2022.days.day8.parse_data_to_array(raw_data: str) → ndarray

Parse the raw data into a 2D list of lists

Parameters:

raw_data (str) – Raw data containing numerical data

Returns:

parsed matrix of values

Return type:

List[List[int]]

src.aoc2022.days.day8.scan_height_row(height_map: ndarray) → Set[int]

Scan a list of heights to determine which trees are visible from either side

Parameters:

height_map (np.ndarray) – 1D array of heights

Returns:

Set of positions that are visible from either side

Return type:

Set[int]

Day 9

class src.aoc2022.days.day9.Move(value)

Enum for valid rope moves

DOWN = 'D'

Value for ‘DOWN’ move.

LEFT = 'L'

Value for ‘LEFT’ move.

RIGHT = 'R'

Value for ‘RIGHT’ move.

UP = 'U'

Value for ‘UP’ move.

src.aoc2022.days.day9.parse_data_to_array(raw_data: str) → List[Tuple[Move, int]]

Parse the raw data into a 1D list of move Tuples

Parameters:

raw_data (str) – Raw data containing numerical data

Returns:

parsed matrix of values

Return type:

List[Tuple[Move, int]]

Day 10

src.aoc2022.days.day10.get_total_signal_strength(instructions: List[List[str]]) → int

Computes the total signal strength as sum of cycle * register value for n = 20, 60, 100, 140…

Parameters:

instructions (List[List[str]]) – List of instructions to execute

Returns:

total signal strength

Return type:

int

src.aoc2022.days.day10.parse_data_to_array(raw_data: str) → List[List[str]]

Parse the raw data into a 1D list of instruction sets

Parameters:

raw_data (str) – Raw data containing numerical data

Returns:

parsed matrix of values

Return type:

List[List[str]]

src.aoc2022.days.day10.render_cpu_pixel_values(instructions: List[List[str]]) → str

Render the signal to a simulated console

Parameters:

instructions (List[List[str]]) – List of instructions to execute

Returns:

rendered console output

Return type:

str

src.aoc2022.days.day10.simulate_cpu_state_machine(instructions: List[List[str]]) → Generator[Tuple[int, int], None, None]

Creates a generator that simulates the CPU on a per-cycle basis

Parameters:

instructions (List[List[str]]) – List of instructions to execute

Returns:

per-cycle CPU simulator

Return type:

Generator[Tuple[int, int], None, None]

Day 11

class src.aoc2022.days.day11.Monkey(items: List[int], operation: Callable[[int], int], divisible: int, false_throw: int, true_throw: int)

Data class representing the monkey configuration

Parameters:
  • items (List[int]) – list of items the monkey is currently holding

  • operation (Callable[[int], int]) – lambda function for updating the item priority

  • divisible (int) – number used for divisible check when throwing items

  • false_throw (int) – id of monkey to throw to on item % divisible != 0

  • true_throw (int) – id of monkey to throw to on item % divisible == 0

add_items(items: List[int])

Add a list of items to the items held by the monkey

Parameters:

items (List[int]) – List of items to add to the monkey’s held items

copy() → Monkey

Create a new copy of this monkey

Returns:

Monkey copy

Return type:

Monkey

divisible: int

Alias for field number 2

false_throw: int

Alias for field number 3

items: List[int]

Alias for field number 0

operation: Callable[[int], int]

Alias for field number 1

pop_items() → List[int]

Pop all the items from the monkey and return the list

Returns:

items held by monkey

Return type:

List[int]

true_throw: int

Alias for field number 4

src.aoc2022.days.day11.compute_number_of_counted_items(num_rounds: int, monkeys: Dict[int, Monkey]) → Dict[int, int]

Compute the number of items each monkey has examined during a game

Parameters:
  • num_rounds (int) – Number of rounds to simulate

  • monkeys (Dict[int, Monkey]) – Monkeys instances to simulate playing the game

Returns:

Examined items counts for each monkey id

Return type:

Dict[int, int]

src.aoc2022.days.day11.compute_number_of_counted_items_no_div(num_rounds: int, monkeys: Dict[int, Monkey]) → Dict[int, int]

Compute the number of items each monkey has examined during a game with no division rule

Parameters:
  • num_rounds (int) – Number of rounds to simulate

  • monkeys (Dict[int, Monkey]) – Monkeys instances to simulate playing the game

Returns:

Examined items counts for each monkey id

Return type:

Dict[int, int]

src.aoc2022.days.day11.parse_block(raw_data_block: str) → Monkey

Parse block of raw data to a single monkey monkey

Parameters:

raw_data_block (str) – Raw data containing data for single monkey

Returns:

parsed Monkey instance

Return type:

Monkey

src.aoc2022.days.day11.parse_data_to_dict(raw_data: str) → Dict[int, Monkey]

Parse the raw data intoa dict of monkeys

Parameters:

raw_data (str) – Raw data containing numerical data

Returns:

parsed dict of Monkey id, Monkey

Return type:

Dict[int, Monkey]

Day 12

src.aoc2022.days.day12.get_distance_matrix(data: ndarray, pos: Tuple[int, int]) → ndarray

Compute the breadth-first distance matrix from aa starting position

Parameters:
  • data (np.ndarray) – Height map for the traversal

  • pos (Tuple[int, int]) – starting position for the depth-first search

Returns:

the shortest distance from the starting pos to all other points

Return type:

np.ndarray

src.aoc2022.days.day12.parse_data_to_array(raw_data: str) → ndarray

Parse the raw data into a 1D list of instruction sets

Parameters:

raw_data (str) – Raw data containing numerical data

Returns:

parsed matrix of values

Return type:

List[List[str]]

Day 13

src.aoc2022.days.day13.element_is_equal(left_val: Union[List, int], right_val: Union[List, int]) → int

Perform ternary comparison on two elements. Returns following: - 1 if left_val smaller - 0 if equal - -1 if right_val smaller

Parameters:
  • left_val (element_type) – left value for comparison

  • right_val (element_type) – right value for comparison

Returns:

Ternary value for equality comparison

Return type:

int

src.aoc2022.days.day13.parse_data_to_array(raw_data: str) → List[Tuple[List[Union[List, int]], List[Union[List, int]]]]

Parse raw data into a list of packet tuples

Parameters:

raw_data (str) – Raw data to parse into packets

Returns:

a list of all packet pairs

Return type:

List[Tuple[List, List]]

src.aoc2022.days.day13.sort_packets(packets: List[List[Union[List, int]]]) → List[List[Union[List, int]]]

Sort packets using comparison function

Parameters:

packets (List[pack_type]) – list of packets to sort

Returns:

List of sorted packets

Return type:

List[pack_type]

Day 14

src.aoc2022.days.day14.add_floor_to_map(map_: ndarray, starting_point: Tuple[int, int]) → Tuple[ndarray, Tuple[int, int]]

Add a floor underneath the given map

Parameters:
  • map (np.ndarray) – The map to which the extra floor is added

  • starting_point (Tuple[int, int]) – Starting point from where sand is dropped

Returns:

the updated map and starting point

Return type:

Tuple[np.ndarray, Tuple[int, int]]

src.aoc2022.days.day14.parse_data_to_array(raw_data: str, starting_point: Tuple[int, int]) → Tuple[ndarray, Tuple[int, int]]

Parse raw data into a grid of air/stone cells

Parameters:
  • raw_data (str) – Raw data to parse into packets

  • starting_point (Tuple[int, int]) – Starting point from where sand is dropped

Returns:

the generated map and updated starting point

Return type:

Tuple[np.ndarray, Tuple[int, int]]

src.aoc2022.days.day14.render_map(map_: ndarray, start_point: Tuple[int, int]) → str

Render the map for visualization

Parameters:
  • map (np.ndarray) – The map through which the grain of sand falls

  • starting_point (Tuple[int, int]) – Starting point from where sand is dropped

Returns:

A rendered representation of the map

Return type:

str

src.aoc2022.days.day14.simulate_grain_of_sand(map_: ndarray, starting_point: Tuple[int, int]) → Tuple[int, int]

Simulate a grain of sand falling through the map

Parameters:
  • map (np.ndarray) – The map through which the grain of sand falls

  • starting_point (Tuple[int, int]) – Starting point from where sand is dropped

Returns:

The updated cell that the grain of sand falls onto

Return type:

Tuple[int, int]

src.aoc2022.days.day14.simulate_sand_falling(map_: ndarray, starting_point: Tuple[int, int]) → ndarray

Repeatedly drop grains of sand til convergence

Parameters:
  • map (np.ndarray) – The map through which the grain of sand falls

  • starting_point (Tuple[int, int]) – Starting point from where sand is dropped

Returns:

converged map state after grain of sand fall off edge of map

Return type:

np.ndarray

Day 15

src.aoc2022.days.day15.count_scanned_location(beacon_sensor_locations: List[Tuple[int, int, int, int]], row_number: int, bounding_range: Optional[Tuple[int, int]] = None) → Tuple[List[Tuple[int, int]], int]

Count how many locations have been scanned given the beacon/sensor locations and the row number

Parameters:
  • beacon_sensor_locations (List[Tuple[int, int, int, int]]) – List of sensor/beacon locations

  • row_number (int) – The row for which to count the scan locations

  • bounding_range (Optional[Tuple[int, int]]) – an optional bounding range for scan range

Returns:

the ranges scanned as well as the total number of scanned cells

Return type:

Tuple[List[Tuple[int, int]], int]

src.aoc2022.days.day15.parse_data_to_array(raw_data: str) → List[Tuple[int, int, int, int]]

Parse raw data into a list of sensor/closest beacon locations

Parameters:

raw_data (str) – Raw data to parse into sensor/beacon locations

Returns:

the parsed sensor/beacon locations

Return type:

List[Tuple[int, int]]

Day 16

class src.aoc2022.days.day16.Graph(flow_rates: Dict[str, int], cons: Dict[str, List[str]])

Data class representing a graph of nodes and edges

Parameters:
  • flow_rates (Dict[str, int]) – A dict of node name, flow rate

  • cons (Dict[str, List[str]]) – a dict of node name, node edges

compute_distance_matrix(start: str) → Dict[str, int]

Compute shortest distance from starting node to all other nodes

Parameters:

start (str) – Name of starting node

Returns:

shortest distance from starting node to all other nodes

Return type:

Dict[str, int]

get_connections(node_name: str) → List[str]

Get connections for a specified node

Parameters:

node_name (str) – Name of node to retrieve connections

Returns:

the names of the connected nodes for the given node

Return type:

List[str]

get_flow_rate(node_name) → int

Get flow rate for a specified node

Parameters:

node_name (str) – Name of node to retrieve flow rate

Returns:

Flow rate of given node

Return type:

int

get_flow_rates() → Dict[str, int]

Get flow rates for all nodes

Returns:

Dict of node name, flow rate

Return type:

Dict[str, int]

get_minimal_distance(start: str, end: str) → int

Get shortest distance between two valves

Parameters:
  • start (str) – Name of starting node

  • node_name (str) – Name of end node

Returns:

shortest distance between both nodes

Return type:

int

get_valves() → List[str]

Get a list of all valve names

Returns:

valve names

Return type:

List[str]

time_aware_permutations(position: str, remaining_valves: Set[str], remaining_time: int) → Generator[List[Tuple[str, int]], None, None]

Generate all possible permutations of valve openings that respect the time limits

Parameters:
  • position (str) – Name of current node

  • remaining_valves (Set[str]) – valves that have not yet been opened

  • remaining_time (int) – Amount of time remaining before eruption

Returns:

shortest distance from starting node to all other nodes

Return type:

Dict[str, int]

src.aoc2022.days.day16.get_optimal_dual_sequence(graph: Graph, start: str, total_time: int) → Tuple[List[Tuple[str, int]], List[Tuple[str, int]], int]

Compute the optimal valve opening sequence for two agents

Parameters:
  • graph (Graph) – Graph of valves to open

  • start (str) – Name of starting node

  • total_time (int) – total time for valve sequence

Returns:

Optimal paths for elephant and person, and associated score

Return type:

Tuple[List[Tuple[str, int]], List[Tuple[str, int]], int]

src.aoc2022.days.day16.get_optimal_sequence(graph: Graph, start: str, total_time: int, non_zero_valves: Optional[List[str]] = None) → Tuple[List[Tuple[str, int]], int]

Compute the optimal valve opening sequence

Parameters:
  • graph (Graph) – Graph of valves to open

  • start (str) – Name of starting node

  • total_time (int) – total time for valve sequence

  • non_zero_valves (Optional[List[str]]) – Optional list of valves to specify for search

Returns:

Optimal sequence and score for opening valves

Return type:

Tuple[List[Tuple[str, int]], int]

src.aoc2022.days.day16.parse_data_to_graph(raw_data: str) → Graph

Parse raw data into a Graph of valves and connections

Parameters:

raw_data (str) – Raw data to parse into Graph

Returns:

the parsed Graph data

Return type:

Graph