language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
Python
def process_count_by_consumer(self, name): """Return the process count by consumer only. :param str name: The consumer name :rtype: int """ count = 0 for connection in self._consumers[name]['connections']: count += len(self._consumers[name]['connections'][connection]) return count
def process_count_by_consumer(self, name): """Return the process count by consumer only. :param str name: The consumer name :rtype: int """ count = 0 for connection in self._consumers[name]['connections']: count += len(self._consumers[name]['connections'][connection]) return count
Python
def process_spawn_qty(self, name, connection): """Return the number of processes to spawn for the given consumer name and connection. :param str name: The consumer name :param str connection: The connection name :rtype: int """ return self._consumers[name]['qty'] - self.process_count(name, connection)
def process_spawn_qty(self, name, connection): """Return the number of processes to spawn for the given consumer name and connection. :param str name: The consumer name :param str connection: The connection name :rtype: int """ return self._consumers[name]['qty'] - self.process_count(name, connection)
Python
def remove_consumer_process(self, consumer, name): """Remove all details for the specified consumer and process name. :param str consumer: The consumer name :param str name: The process name """ for conn in self._consumers[consumer]['connections']: if name in self._consumers[consumer]['connections'][conn]: self._consumers[consumer]['connections'][conn].remove(name) if name in self._consumers[consumer]['processes']: try: self._consumers[consumer]['processes'][name].terminate() except OSError: pass del self._consumers[consumer]['processes'][name]
def remove_consumer_process(self, consumer, name): """Remove all details for the specified consumer and process name. :param str consumer: The consumer name :param str name: The process name """ for conn in self._consumers[consumer]['connections']: if name in self._consumers[consumer]['connections'][conn]: self._consumers[consumer]['connections'][conn].remove(name) if name in self._consumers[consumer]['processes']: try: self._consumers[consumer]['processes'][name].terminate() except OSError: pass del self._consumers[consumer]['processes'][name]
Python
def run(self): """When the consumer is ready to start running, kick off all of our consumer consumers and then loop while we process messages. """ # Set the state to active self.set_state(self.STATE_ACTIVE) # Get the consumer section from the config if 'Consumers' not in self._config.application: LOGGER.error('Missing Consumers section of configuration, ' 'aborting: %r', self._config.application) return self.set_state(self.STATE_STOPPED) # Strip consumers if a consumer is specified if self._consumer: consumers = self._config.application.Consumers.keys() for consumer in consumers: if consumer != self._consumer: LOGGER.debug('Removing %s for %s only processing', consumer, self._consumer) del self._config.application.Consumers[consumer] # Setup consumers and start the processes self.setup_consumers() # Set the SIGALRM handler for poll interval signal.signal(signal.SIGALRM, self.on_timer) # Kick off the poll timer signal.setitimer(signal.ITIMER_REAL, self._poll_interval, 0) # Loop for the lifetime of the app, pausing for a signal to pop up while self.is_running and self.total_process_count: if self._state != self.STATE_SLEEPING: self.set_state(self.STATE_SLEEPING) signal.pause() # Note we're exiting run LOGGER.info('Exiting Master Control Program')
def run(self): """When the consumer is ready to start running, kick off all of our consumer consumers and then loop while we process messages. """ # Set the state to active self.set_state(self.STATE_ACTIVE) # Get the consumer section from the config if 'Consumers' not in self._config.application: LOGGER.error('Missing Consumers section of configuration, ' 'aborting: %r', self._config.application) return self.set_state(self.STATE_STOPPED) # Strip consumers if a consumer is specified if self._consumer: consumers = self._config.application.Consumers.keys() for consumer in consumers: if consumer != self._consumer: LOGGER.debug('Removing %s for %s only processing', consumer, self._consumer) del self._config.application.Consumers[consumer] # Setup consumers and start the processes self.setup_consumers() # Set the SIGALRM handler for poll interval signal.signal(signal.SIGALRM, self.on_timer) # Kick off the poll timer signal.setitimer(signal.ITIMER_REAL, self._poll_interval, 0) # Loop for the lifetime of the app, pausing for a signal to pop up while self.is_running and self.total_process_count: if self._state != self.STATE_SLEEPING: self.set_state(self.STATE_SLEEPING) signal.pause() # Note we're exiting run LOGGER.info('Exiting Master Control Program')
Python
def start_process(self, name, connection): """Start a new consumer process for the given consumer & connection name :param str name: The consumer name :param str connection: The connection name """ process_name, process = self.new_process(name, connection) LOGGER.info('Spawning %s process for %s to %s', process_name, name, connection) # Append the process to the consumer process list self._consumers[name]['processes'][process_name] = process self._consumers[name]['connections'][connection].append(process_name) # Start the process process.start()
def start_process(self, name, connection): """Start a new consumer process for the given consumer & connection name :param str name: The consumer name :param str connection: The connection name """ process_name, process = self.new_process(name, connection) LOGGER.info('Spawning %s process for %s to %s', process_name, name, connection) # Append the process to the consumer process list self._consumers[name]['processes'][process_name] = process self._consumers[name]['connections'][connection].append(process_name) # Start the process process.start()
Python
def start_processes(self, name, connection, quantity): """Start the specified quantity of consumer processes for the given consumer and connection. :param str name: The consumer name :param str connection: The connection name :param int quantity: The quantity of processes to start """ for process in xrange(0, quantity): self.start_process(name, connection)
def start_processes(self, name, connection, quantity): """Start the specified quantity of consumer processes for the given consumer and connection. :param str name: The consumer name :param str connection: The connection name :param int quantity: The quantity of processes to start """ for process in xrange(0, quantity): self.start_process(name, connection)
Python
def stop_processes(self): """Iterate through all of the consumer processes shutting them down.""" self.set_state(self.STATE_SHUTTING_DOWN) LOGGER.info('Stopping consumer processes') signal.signal(signal.SIGALRM, signal.SIG_IGN) signal.signal(signal.SIGCHLD, signal.SIG_IGN) signal.signal(signal.SIGPROF, signal.SIG_IGN) signal.setitimer(signal.ITIMER_REAL, 0, 0) # Send SIGABRT LOGGER.info('Sending SIGABRT to active children') for process in multiprocessing.active_children(): if int(process.pid) != os.getpid(): os.kill(int(process.pid), signal.SIGABRT) # Wait for them to finish up to MAX_SHUTDOWN_WAIT iterations = 0 processes = self.total_process_count while processes: LOGGER.info('Waiting on %i active processes to shut down', processes) try: time.sleep(0.5) except KeyboardInterrupt: LOGGER.info('Caught CTRL-C, Killing Children') self.kill_processes() self.set_state(self.STATE_STOPPED) return iterations += 1 if iterations == self._MAX_SHUTDOWN_WAIT: self.kill_processes() break processes = self.total_process_count LOGGER.debug('All consumer processes stopped') self.set_state(self.STATE_STOPPED)
def stop_processes(self): """Iterate through all of the consumer processes shutting them down.""" self.set_state(self.STATE_SHUTTING_DOWN) LOGGER.info('Stopping consumer processes') signal.signal(signal.SIGALRM, signal.SIG_IGN) signal.signal(signal.SIGCHLD, signal.SIG_IGN) signal.signal(signal.SIGPROF, signal.SIG_IGN) signal.setitimer(signal.ITIMER_REAL, 0, 0) # Send SIGABRT LOGGER.info('Sending SIGABRT to active children') for process in multiprocessing.active_children(): if int(process.pid) != os.getpid(): os.kill(int(process.pid), signal.SIGABRT) # Wait for them to finish up to MAX_SHUTDOWN_WAIT iterations = 0 processes = self.total_process_count while processes: LOGGER.info('Waiting on %i active processes to shut down', processes) try: time.sleep(0.5) except KeyboardInterrupt: LOGGER.info('Caught CTRL-C, Killing Children') self.kill_processes() self.set_state(self.STATE_STOPPED) return iterations += 1 if iterations == self._MAX_SHUTDOWN_WAIT: self.kill_processes() break processes = self.total_process_count LOGGER.debug('All consumer processes stopped') self.set_state(self.STATE_STOPPED)
Python
def total_process_count(self): """Returns the active consumer process count :rtype: int """ return len(self.active_processes)
def total_process_count(self): """Returns the active consumer process count :rtype: int """ return len(self.active_processes)
Python
def is_connecting(self): """Returns a bool specifying if the process is currently connecting. :rtype: bool """ return self._state == self.STATE_CONNECTING
def is_connecting(self): """Returns a bool specifying if the process is currently connecting. :rtype: bool """ return self._state == self.STATE_CONNECTING
Python
def is_running(self): """Returns a bool determining if the process is in a running state or not :rtype: bool """ return self._state in [self.STATE_IDLE, self.STATE_ACTIVE, self.STATE_SLEEPING]
def is_running(self): """Returns a bool determining if the process is in a running state or not :rtype: bool """ return self._state in [self.STATE_IDLE, self.STATE_ACTIVE, self.STATE_SLEEPING]
Python
def is_shutting_down(self): """Designates if the process is shutting down. :rtype: bool """ return self._state == self.STATE_SHUTTING_DOWN
def is_shutting_down(self): """Designates if the process is shutting down. :rtype: bool """ return self._state == self.STATE_SHUTTING_DOWN
Python
def is_waiting_to_shutdown(self): """Designates if the process is waiting to start shutdown :rtype: bool """ return self._state == self.STATE_STOP_REQUESTED
def is_waiting_to_shutdown(self): """Designates if the process is waiting to start shutdown :rtype: bool """ return self._state == self.STATE_STOP_REQUESTED
Python
def state_description(self): """Return the string description of our running state. :rtype: str """ return self._STATES[self._state]
def state_description(self): """Return the string description of our running state. :rtype: str """ return self._STATES[self._state]
Python
def sample_account_type(user, name='Sample Account Type', calculate=True): """Create and return a sample account type""" return AccountType.objects.create( user=user, name=name, calculate=calculate )
def sample_account_type(user, name='Sample Account Type', calculate=True): """Create and return a sample account type""" return AccountType.objects.create( user=user, name=name, calculate=calculate )
Python
def sample_operation(user, account, **params): """Create and return a sample operation""" defaults = { 'name': 'Sample Operation', 'value': 1.00, 'date': datetime.now().date(), 'account': account } defaults.update(params) return Operation.objects.create(user=user, **defaults)
def sample_operation(user, account, **params): """Create and return a sample operation""" defaults = { 'name': 'Sample Operation', 'value': 1.00, 'date': datetime.now().date(), 'account': account } defaults.update(params) return Operation.objects.create(user=user, **defaults)
Python
def sample_account(user, **params): """Create and return a sample account""" defaults = { 'name': 'Sample Account' } defaults.update(params) return Account.objects.create(user=user, **defaults)
def sample_account(user, **params): """Create and return a sample account""" defaults = { 'name': 'Sample Account' } defaults.update(params) return Account.objects.create(user=user, **defaults)
Python
def sample_tag(user, name='Samlpe tag'): """Create and return a sample tag object""" return Tag.objects.create( user=user, name=name )
def sample_tag(user, name='Samlpe tag'): """Create and return a sample tag object""" return Tag.objects.create( user=user, name=name )
Python
def runtest(grid, px, test): """Tests if applying test to px moves px to unoccupied space""" for p in px: if(p[0]+test[0] >= grid.n or p[0]+test[0] < 0): return False if(p[1]-test[1] >= grid.m or p[1]-test[1] < 0): return False if(isoccupied([p[0]+test[0], p[1]-test[1]], grid)): return False return True
def runtest(grid, px, test): """Tests if applying test to px moves px to unoccupied space""" for p in px: if(p[0]+test[0] >= grid.n or p[0]+test[0] < 0): return False if(p[1]-test[1] >= grid.m or p[1]-test[1] < 0): return False if(isoccupied([p[0]+test[0], p[1]-test[1]], grid)): return False return True
Python
def move(self, x, y): """Moves the block x times right and y times down.\ Raises OccupiedError if desired pixels are occupied.""" for p in self._pixels: if(p[1]+y >= self._grid.m or p[0]+x >= self._grid.n): raise IndexError("Cannot move block outside of grid.") if(p[1]+y < 0 or p[0]+x < 0): raise IndexError("Cannot move block outside of grid.") self.remself() for p in self._pixels: if(isoccupied([p[0]+x, p[1]+y], self._grid)): self.updategrid() raise OccupiedError("Can't move block to ["+str(p[0]+x)+","+str(p[1]+y)+"].") self._center[0] += x self._center[1] += y for p in self._pixels: p[0] += x p[1] += y self.updategrid()
def move(self, x, y): """Moves the block x times right and y times down.\ Raises OccupiedError if desired pixels are occupied.""" for p in self._pixels: if(p[1]+y >= self._grid.m or p[0]+x >= self._grid.n): raise IndexError("Cannot move block outside of grid.") if(p[1]+y < 0 or p[0]+x < 0): raise IndexError("Cannot move block outside of grid.") self.remself() for p in self._pixels: if(isoccupied([p[0]+x, p[1]+y], self._grid)): self.updategrid() raise OccupiedError("Can't move block to ["+str(p[0]+x)+","+str(p[1]+y)+"].") self._center[0] += x self._center[1] += y for p in self._pixels: p[0] += x p[1] += y self.updategrid()
Python
def remself(self): """Removes the current pixels from the grid. To be used with self.updategrid() to\ properly modify the grid without leaving remnants.""" for p in self._pixels: self._grid[p[1]][p[0]] = 0
def remself(self): """Removes the current pixels from the grid. To be used with self.updategrid() to\ properly modify the grid without leaving remnants.""" for p in self._pixels: self._grid[p[1]][p[0]] = 0
Python
def transpose(self): """Returns the transposed version of the matrix.""" newm = [[] for a in range(self.n)] for r in self.rows: for j, v in enumerate(r): newm[j].append(v) return Matrix(newm)
def transpose(self): """Returns the transposed version of the matrix.""" newm = [[] for a in range(self.n)] for r in self.rows: for j, v in enumerate(r): newm[j].append(v) return Matrix(newm)
Python
def start(): """Simulates turtlebot movement and publishes new state continuously""" global x, y, h, v, w global pub #ROS setup pub = rospy.Publisher('virtual_agent/pose', PoseStamped, queue_size = 100) rospy.init_node('Virtual_Agent') hz = 200 r = rospy.Rate(hz) #ROS main loop while not rospy.is_shutdown(): dt = 1/float(hz) #simulate turtlebot dynamics dx = v*cos(h) dy = v*sin(h) dh = w x = x + dt * dx y = y + dt * dy h = h + dt * dh #ROS Pose format with Quaternions Orientation: ps = PoseStamped() ps.header.stamp = rospy.Time.now() ps.header.frame_id = '/virtual_base_link' ps.pose.position.x = x ps.pose.position.y = y ps.pose.position.z = 0 ps.pose.orientation.x = 0 ps.pose.orientation.y = 0 ps.pose.orientation.z = sin(h/2.0) ps.pose.orientation.w = cos(h/2.0) #Publish message to topic pub.publish(ps) r.sleep()
def start(): """Simulates turtlebot movement and publishes new state continuously""" global x, y, h, v, w global pub #ROS setup pub = rospy.Publisher('virtual_agent/pose', PoseStamped, queue_size = 100) rospy.init_node('Virtual_Agent') hz = 200 r = rospy.Rate(hz) #ROS main loop while not rospy.is_shutdown(): dt = 1/float(hz) #simulate turtlebot dynamics dx = v*cos(h) dy = v*sin(h) dh = w x = x + dt * dx y = y + dt * dy h = h + dt * dh #ROS Pose format with Quaternions Orientation: ps = PoseStamped() ps.header.stamp = rospy.Time.now() ps.header.frame_id = '/virtual_base_link' ps.pose.position.x = x ps.pose.position.y = y ps.pose.position.z = 0 ps.pose.orientation.x = 0 ps.pose.orientation.y = 0 ps.pose.orientation.z = sin(h/2.0) ps.pose.orientation.w = cos(h/2.0) #Publish message to topic pub.publish(ps) r.sleep()
Python
def parse_input() -> Graph: """ Parses the input and returns a Graph """ with open(INPUT_FILE) as f: links = [line.strip().split("-") for line in f] return Graph(links)
def parse_input() -> Graph: """ Parses the input and returns a Graph """ with open(INPUT_FILE) as f: links = [line.strip().split("-") for line in f] return Graph(links)
Python
def visited_a_small_cave_twice(path: Path) -> bool: """ Checks if you've already visited a small cave twice """ c = Counter(cave.name for cave in path if cave.is_small) return any(value > 1 for value in c.values())
def visited_a_small_cave_twice(path: Path) -> bool: """ Checks if you've already visited a small cave twice """ c = Counter(cave.name for cave in path if cave.is_small) return any(value > 1 for value in c.values())
Python
def can_visit(cave: Cave, path: Path, part: int) -> bool: """ Checks if you can visit the cave """ if not cave.is_small: return True if cave.is_start: return False if cave in path: return not visited_a_small_cave_twice(path) if part == 2 else False return True
def can_visit(cave: Cave, path: Path, part: int) -> bool: """ Checks if you can visit the cave """ if not cave.is_small: return True if cave.is_start: return False if cave in path: return not visited_a_small_cave_twice(path) if part == 2 else False return True
Python
def count_paths(graph: Graph, part: int) -> int: """ Counts all possible paths from start to end """ candidates: deque[PathCandidate] = deque([(graph.get("start"), [])]) path_count = 0 while candidates: current_node, path = candidates.popleft() path = path[:] + [current_node] for neighbour in current_node.neighbours: if neighbour.is_end: path_count += 1 elif can_visit(neighbour, path, part): candidates.append((neighbour, path)) return path_count
def count_paths(graph: Graph, part: int) -> int: """ Counts all possible paths from start to end """ candidates: deque[PathCandidate] = deque([(graph.get("start"), [])]) path_count = 0 while candidates: current_node, path = candidates.popleft() path = path[:] + [current_node] for neighbour in current_node.neighbours: if neighbour.is_end: path_count += 1 elif can_visit(neighbour, path, part): candidates.append((neighbour, path)) return path_count
Python
def parse_input() -> RiskGrid: """ Parses the input and return a grid of risk levels """ with open(INPUT_FILE) as f: return [[int(x) for x in line.strip()] for line in f]
def parse_input() -> RiskGrid: """ Parses the input and return a grid of risk levels """ with open(INPUT_FILE) as f: return [[int(x) for x in line.strip()] for line in f]
Python
def enlarge(grid: RiskGrid, factor: int) -> RiskGrid: """ Enlarges the grid as described in part 2 by the given factor """ HEIGHT = len(grid) WIDTH = len(grid[0]) def risk(x: int, y: int): base_risk = grid[x % WIDTH][y % HEIGHT] increase = x // WIDTH + y // HEIGHT return (base_risk + increase) % 9 or 9 return [[risk(x, y) for x in range(WIDTH * factor)] for y in range(HEIGHT * factor)]
def enlarge(grid: RiskGrid, factor: int) -> RiskGrid: """ Enlarges the grid as described in part 2 by the given factor """ HEIGHT = len(grid) WIDTH = len(grid[0]) def risk(x: int, y: int): base_risk = grid[x % WIDTH][y % HEIGHT] increase = x // WIDTH + y // HEIGHT return (base_risk + increase) % 9 or 9 return [[risk(x, y) for x in range(WIDTH * factor)] for y in range(HEIGHT * factor)]
Python
def neighbours(position: Position, height: int, width: int) -> set[Position]: """ Returns the neighbouring positions within the grid """ x, y = position return { (new_x, new_y) for new_x, new_y in { (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1), } if 0 <= new_x < width and 0 <= new_y < height }
def neighbours(position: Position, height: int, width: int) -> set[Position]: """ Returns the neighbouring positions within the grid """ x, y = position return { (new_x, new_y) for new_x, new_y in { (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1), } if 0 <= new_x < width and 0 <= new_y < height }
Python
def lowest_total_risk(grid: RiskGrid) -> int: """ Returns the lowest total risk for the given grid """ HEIGHT = len(grid) WIDTH = len(grid[0]) options: defaultdict[Risk, set[Position]] = defaultdict(set, {0: {(0, 0)}}) lowest_risks: dict[Position, Risk] = {(0, 0): 0} bottom_right = (HEIGHT - 1, WIDTH - 1) while options: current_risk = min(options) position = options[current_risk].pop() if not options[current_risk]: del options[current_risk] for neighbour in neighbours(position, HEIGHT, WIDTH): x, y = neighbour new_risk = current_risk + grid[y][x] if neighbour not in lowest_risks or new_risk < lowest_risks[neighbour]: lowest_risks[neighbour] = new_risk options[new_risk].add(neighbour) return lowest_risks[bottom_right]
def lowest_total_risk(grid: RiskGrid) -> int: """ Returns the lowest total risk for the given grid """ HEIGHT = len(grid) WIDTH = len(grid[0]) options: defaultdict[Risk, set[Position]] = defaultdict(set, {0: {(0, 0)}}) lowest_risks: dict[Position, Risk] = {(0, 0): 0} bottom_right = (HEIGHT - 1, WIDTH - 1) while options: current_risk = min(options) position = options[current_risk].pop() if not options[current_risk]: del options[current_risk] for neighbour in neighbours(position, HEIGHT, WIDTH): x, y = neighbour new_risk = current_risk + grid[y][x] if neighbour not in lowest_risks or new_risk < lowest_risks[neighbour]: lowest_risks[neighbour] = new_risk options[new_risk].add(neighbour) return lowest_risks[bottom_right]
Python
def add_link(self, link: list[str]): """ Adds the given link to the graph """ cave1 = self.get(link[0]) cave2 = self.get(link[1]) cave1.add_neighbour(cave2) cave2.add_neighbour(cave1)
def add_link(self, link: list[str]): """ Adds the given link to the graph """ cave1 = self.get(link[0]) cave2 = self.get(link[1]) cave1.add_neighbour(cave2) cave2.add_neighbour(cave1)
Python
def parse_input() -> LanternfishCounter: """ Parses the input and returns a LanternfishCounter """ with open(INPUT_FILE) as f: numbers = [int(x) for x in f.readline().split(",")] return dict(Counter(numbers))
def parse_input() -> LanternfishCounter: """ Parses the input and returns a LanternfishCounter """ with open(INPUT_FILE) as f: numbers = [int(x) for x in f.readline().split(",")] return dict(Counter(numbers))
Python
def counter_after_n_days(counter: LanternfishCounter, n: int) -> LanternfishCounter: """ Returns a LanternfishCounter after the specified number of days from the given starting position """ for _ in range(n): counter = {days - 1: count_ for days, count_ in counter.items() if days >= 0} new_counter = counter.get(-1, 0) counter[6] = counter.get(6, 0) + new_counter counter[8] = new_counter counter[-1] = 0 return counter
def counter_after_n_days(counter: LanternfishCounter, n: int) -> LanternfishCounter: """ Returns a LanternfishCounter after the specified number of days from the given starting position """ for _ in range(n): counter = {days - 1: count_ for days, count_ in counter.items() if days >= 0} new_counter = counter.get(-1, 0) counter[6] = counter.get(6, 0) + new_counter counter[8] = new_counter counter[-1] = 0 return counter
Python
def count_lanternfish(counter: LanternfishCounter) -> int: """ Counts the number of all lanternfish """ return sum(counter.values())
def count_lanternfish(counter: LanternfishCounter) -> int: """ Counts the number of all lanternfish """ return sum(counter.values())
Python
def parse_input() -> InstructionGenerator: """ Parses the input and returns a generator of Instructions """ with open(INPUT_FILE, "r") as f: for line in f: command, value = line.strip().split() command = Command(command) value = int(value) yield (command, value)
def parse_input() -> InstructionGenerator: """ Parses the input and returns a generator of Instructions """ with open(INPUT_FILE, "r") as f: for line in f: command, value = line.strip().split() command = Command(command) value = int(value) yield (command, value)
Python
def solve_part1(instructions: InstructionGenerator) -> int: """ Processes the instructions according to rules stated in part 1 and returns the answer, i.e. the product of the horizontal position and the depth """ horizontal = 0 depth = 0 for command, value in instructions: match command: case Command.FORWARD: horizontal += value case Command.DOWN: depth += value case Command.UP: depth -= value return horizontal * depth
def solve_part1(instructions: InstructionGenerator) -> int: """ Processes the instructions according to rules stated in part 1 and returns the answer, i.e. the product of the horizontal position and the depth """ horizontal = 0 depth = 0 for command, value in instructions: match command: case Command.FORWARD: horizontal += value case Command.DOWN: depth += value case Command.UP: depth -= value return horizontal * depth
Python
def solve_part2(instructions: InstructionGenerator) -> int: """ Processes the instructions according to rules stated in part 2 and returns the answer, i.e. the product of the horizontal position and the depth """ aim = 0 horizontal = 0 depth = 0 for command, value in instructions: match command: case Command.FORWARD: horizontal += value depth += aim * value case Command.DOWN: aim += value case Command.UP: aim -= value return horizontal * depth
def solve_part2(instructions: InstructionGenerator) -> int: """ Processes the instructions according to rules stated in part 2 and returns the answer, i.e. the product of the horizontal position and the depth """ aim = 0 horizontal = 0 depth = 0 for command, value in instructions: match command: case Command.FORWARD: horizontal += value depth += aim * value case Command.DOWN: aim += value case Command.UP: aim -= value return horizontal * depth
Python
def parse_input() -> list[str]: """ Parses the data and returns a list of binary entries """ with open(INPUT_FILE, "r") as f: return [line.strip() for line in f]
def parse_input() -> list[str]: """ Parses the data and returns a list of binary entries """ with open(INPUT_FILE, "r") as f: return [line.strip() for line in f]
Python
def more_common_bit(bits: Iterable[str]) -> str: """ Returns the more common bit or "1" if both are equally common """ c = Counter(bits) return "1" if c["1"] >= c["0"] else "0"
def more_common_bit(bits: Iterable[str]) -> str: """ Returns the more common bit or "1" if both are equally common """ c = Counter(bits) return "1" if c["1"] >= c["0"] else "0"
Python
def less_common_bit(bits: Iterable[str]) -> str: """ Returns the less common bit or "0" if both are equally common """ c = Counter(bits) return "0" if c["1"] >= c["0"] else "1"
def less_common_bit(bits: Iterable[str]) -> str: """ Returns the less common bit or "0" if both are equally common """ c = Counter(bits) return "0" if c["1"] >= c["0"] else "1"
Python
def multiply_binary(first: str, second: str) -> int: """ Parses two strings representing binary numbers and multiplies them """ return int(first, 2) * int(second, 2)
def multiply_binary(first: str, second: str) -> int: """ Parses two strings representing binary numbers and multiplies them """ return int(first, 2) * int(second, 2)
Python
def solve_part1(data: list[str]) -> int: """ Finds the solution to part 1 (the power consumption of the submarine) """ gamma = "" epsilon = "" for bits in zip(*data): gamma += more_common_bit(bits) epsilon += less_common_bit(bits) return multiply_binary(gamma, epsilon)
def solve_part1(data: list[str]) -> int: """ Finds the solution to part 1 (the power consumption of the submarine) """ gamma = "" epsilon = "" for bits in zip(*data): gamma += more_common_bit(bits) epsilon += less_common_bit(bits) return multiply_binary(gamma, epsilon)
Python
def find_rating(data: list[str], keep_condition: Callable[[list[str]], str]) -> str: """ Finds the rating by going through each bit position and keeping only those entries where the ith bit matches the one returned by the keep_condition function """ for i in range(len(data[0])): bits = [entry[i] for entry in data] data = [entry for entry in data if entry[i] == keep_condition(bits)] if len(data) == 1: return data[0] raise ValueError("could not find the rating")
def find_rating(data: list[str], keep_condition: Callable[[list[str]], str]) -> str: """ Finds the rating by going through each bit position and keeping only those entries where the ith bit matches the one returned by the keep_condition function """ for i in range(len(data[0])): bits = [entry[i] for entry in data] data = [entry for entry in data if entry[i] == keep_condition(bits)] if len(data) == 1: return data[0] raise ValueError("could not find the rating")
Python
def solve_part2(data: list[str]) -> int: """ Finds the solution to part 2 (the life support rating of the submarine) """ oxygen_generator_rating = find_rating(data, more_common_bit) co2_scrubber_rating = find_rating(data, less_common_bit) return multiply_binary(oxygen_generator_rating, co2_scrubber_rating)
def solve_part2(data: list[str]) -> int: """ Finds the solution to part 2 (the life support rating of the submarine) """ oxygen_generator_rating = find_rating(data, more_common_bit) co2_scrubber_rating = find_rating(data, less_common_bit) return multiply_binary(oxygen_generator_rating, co2_scrubber_rating)
Python
def parse_input() -> EnergyLevelGrid: """ Parses the input and returns an EnergyLevelGrid """ with open(INPUT_FILE) as f: return [[int(x) for x in line.strip()] for line in f]
def parse_input() -> EnergyLevelGrid: """ Parses the input and returns an EnergyLevelGrid """ with open(INPUT_FILE) as f: return [[int(x) for x in line.strip()] for line in f]
Python
def neighbours(row_number: int, column_number: int) -> set[tuple[int, int]]: """ Returns all the neighboring cells within the grid """ output: set[tuple[int, int]] = set() for i in (-1, 0, 1): for j in (-1, 0, 1): if i == 0 and j == 0: continue new_row_number = row_number + i new_column_number = column_number + j if 0 <= new_row_number < HEIGHT and 0 <= new_column_number < WIDTH: output.add((new_row_number, new_column_number)) return output
def neighbours(row_number: int, column_number: int) -> set[tuple[int, int]]: """ Returns all the neighboring cells within the grid """ output: set[tuple[int, int]] = set() for i in (-1, 0, 1): for j in (-1, 0, 1): if i == 0 and j == 0: continue new_row_number = row_number + i new_column_number = column_number + j if 0 <= new_row_number < HEIGHT and 0 <= new_column_number < WIDTH: output.add((new_row_number, new_column_number)) return output
Python
def step(energy_levels: EnergyLevelGrid) -> tuple[int, EnergyLevelGrid]: """ Applies one step to the energy level grid and returns the number of flashes and the updated energy level grid """ energy_levels = [[x + 1 for x in line] for line in energy_levels] flashed = [[False for _ in row] for row in energy_levels] still_flashing = True while still_flashing: still_flashing = False for (r, row) in enumerate(energy_levels): for (c, cell) in enumerate(row): if cell > 9 and not flashed[r][c]: still_flashing = True flashed[r][c] = True for y, x in neighbours(r, c): energy_levels[y][x] += 1 flash_count = sum(chain(*flashed)) energy_levels = [ [level if level < 10 else 0 for level in row] for row in energy_levels ] return (flash_count, energy_levels)
def step(energy_levels: EnergyLevelGrid) -> tuple[int, EnergyLevelGrid]: """ Applies one step to the energy level grid and returns the number of flashes and the updated energy level grid """ energy_levels = [[x + 1 for x in line] for line in energy_levels] flashed = [[False for _ in row] for row in energy_levels] still_flashing = True while still_flashing: still_flashing = False for (r, row) in enumerate(energy_levels): for (c, cell) in enumerate(row): if cell > 9 and not flashed[r][c]: still_flashing = True flashed[r][c] = True for y, x in neighbours(r, c): energy_levels[y][x] += 1 flash_count = sum(chain(*flashed)) energy_levels = [ [level if level < 10 else 0 for level in row] for row in energy_levels ] return (flash_count, energy_levels)
Python
def solve(energy_levels: EnergyLevelGrid) -> tuple[int, int]: """ Applies the steps until conditions for both parts are fulfilled and returns the answers for both parts """ part1 = 0 part2 = 0 synchronised = False for steps in count(1): flash_count, energy_levels = step(energy_levels) if steps <= 100: part1 += flash_count if flash_count == HEIGHT * WIDTH: synchronised = True part2 = steps if steps >= 100 and synchronised: break return (part1, part2)
def solve(energy_levels: EnergyLevelGrid) -> tuple[int, int]: """ Applies the steps until conditions for both parts are fulfilled and returns the answers for both parts """ part1 = 0 part2 = 0 synchronised = False for steps in count(1): flash_count, energy_levels = step(energy_levels) if steps <= 100: part1 += flash_count if flash_count == HEIGHT * WIDTH: synchronised = True part2 = steps if steps >= 100 and synchronised: break return (part1, part2)
Python
def step(self, step_x: int, step_y: int) -> "Point": """ Returns a new Point a given number of steps away from self """ return Point(self.x + step_x, self.y + step_y)
def step(self, step_x: int, step_y: int) -> "Point": """ Returns a new Point a given number of steps away from self """ return Point(self.x + step_x, self.y + step_y)
Python
def is_horizontal_or_vertical(self) -> bool: """ Checks whether the line is horizontal or vertical """ return self.start.x == self.end.x or self.start.y == self.end.y
def is_horizontal_or_vertical(self) -> bool: """ Checks whether the line is horizontal or vertical """ return self.start.x == self.end.x or self.start.y == self.end.y
Python
def delta_x(self) -> int: """ Returns the difference of the x coordinates of the points defining the line """ return self.end.x - self.start.x
def delta_x(self) -> int: """ Returns the difference of the x coordinates of the points defining the line """ return self.end.x - self.start.x
Python
def delta_y(self) -> int: """ Returns the difference of the y coordinates of the points defining the line """ return self.end.y - self.start.y
def delta_y(self) -> int: """ Returns the difference of the y coordinates of the points defining the line """ return self.end.y - self.start.y
Python
def points(self) -> Generator[Point, None, None]: """ Returns a generator of all points lying on the line """ step_x = 0 if self.delta_x == 0 else self.delta_x // abs(self.delta_x) step_y = 0 if self.delta_y == 0 else self.delta_y // abs(self.delta_y) current_point = self.start while True: yield current_point if current_point == self.end: break current_point = current_point.step(step_x, step_y)
def points(self) -> Generator[Point, None, None]: """ Returns a generator of all points lying on the line """ step_x = 0 if self.delta_x == 0 else self.delta_x // abs(self.delta_x) step_y = 0 if self.delta_y == 0 else self.delta_y // abs(self.delta_y) current_point = self.start while True: yield current_point if current_point == self.end: break current_point = current_point.step(step_x, step_y)
Python
def parse_input() -> list[Line]: """ Parses the input and returns a list of Lines """ with open(INPUT_FILE) as f: return [Line(line) for line in f]
def parse_input() -> list[Line]: """ Parses the input and returns a list of Lines """ with open(INPUT_FILE) as f: return [Line(line) for line in f]
Python
def count_overlaps(lines: list[Line]) -> int: """ Counts the number of points where at least two lines overlap """ points = (line.points() for line in lines) counter = Counter(chain(*points)) return sum(count > 1 for count in counter.values())
def count_overlaps(lines: list[Line]) -> int: """ Counts the number of points where at least two lines overlap """ points = (line.points() for line in lines) counter = Counter(chain(*points)) return sum(count > 1 for count in counter.values())
Python
def parse_input() -> list[str]: """ Parses the input and returns a list of snailfish numbers """ with open(INPUT_FILE) as f: return [line.strip() for line in f]
def parse_input() -> list[str]: """ Parses the input and returns a list of snailfish numbers """ with open(INPUT_FILE) as f: return [line.strip() for line in f]
Python
def pair(first: int | str, second: int | str) -> str: """ Takes two numbers (regular or snailfish) and returns a snailfish number """ return f"[{first},{second}]"
def pair(first: int | str, second: int | str) -> str: """ Takes two numbers (regular or snailfish) and returns a snailfish number """ return f"[{first},{second}]"
Python
def find_explodable(number: str) -> re.Match[str] | None: """ Finds the first pair nested inside four pairs and returns a Match object or None, if there are no such pairs """ for match in re.finditer(r"(\[(?P<first>\d+),(?P<second>\d+)\])", number): before_match = number[: match.start()] if before_match.count("[") - before_match.count("]") >= 4: return match return None
def find_explodable(number: str) -> re.Match[str] | None: """ Finds the first pair nested inside four pairs and returns a Match object or None, if there are no such pairs """ for match in re.finditer(r"(\[(?P<first>\d+),(?P<second>\d+)\])", number): before_match = number[: match.start()] if before_match.count("[") - before_match.count("]") >= 4: return match return None
Python
def find_splittable(number: str) -> re.Match[str] | None: """ Finds the first regular number that is 10 or greater and returns a Match object or None, if there are no such numbers """ return re.search(r"\d{2,}", number)
def find_splittable(number: str) -> re.Match[str] | None: """ Finds the first regular number that is 10 or greater and returns a Match object or None, if there are no such numbers """ return re.search(r"\d{2,}", number)
Python
def magnitude(number: str) -> int: """ Returns the magnitude of the snailfish number """ while m := re.search(r"(\[(?P<first>\d+),(?P<second>\d+)\])", number): number = ( number[: m.start()] + str(3 * int(m["first"]) + 2 * int(m["second"])) + number[m.end() :] ) return int(number)
def magnitude(number: str) -> int: """ Returns the magnitude of the snailfish number """ while m := re.search(r"(\[(?P<first>\d+),(?P<second>\d+)\])", number): number = ( number[: m.start()] + str(3 * int(m["first"]) + 2 * int(m["second"])) + number[m.end() :] ) return int(number)
Python
def solve_part1(numbers: list[str]) -> int: """ Finds the solution for part 1 """ return magnitude(reduce(add, numbers))
def solve_part1(numbers: list[str]) -> int: """ Finds the solution for part 1 """ return magnitude(reduce(add, numbers))
Python
def solve_part2(numbers: list[str]) -> int: """ Finds the solution for part 2 """ return max(magnitude(add(a, b)) for a, b in permutations(numbers, 2))
def solve_part2(numbers: list[str]) -> int: """ Finds the solution for part 2 """ return max(magnitude(add(a, b)) for a, b in permutations(numbers, 2))
Python
def standardise_signal_pattern(signal_pattern: str) -> str: """ Sorts the letters in the given signal pattern alphabetically """ return "".join(sorted(signal_pattern))
def standardise_signal_pattern(signal_pattern: str) -> str: """ Sorts the letters in the given signal pattern alphabetically """ return "".join(sorted(signal_pattern))
Python
def parse_puzzle_input() -> list[Entry]: """ Parses the puzzle input and returns a list of entries """ entries: list[Entry] = [] with open(INPUT_FILE) as f: for line in f: parts = [part.split() for part in line.split(" | ")] input_ = {standardise_signal_pattern(pattern) for pattern in parts[0]} output = [standardise_signal_pattern(pattern) for pattern in parts[1]] entries.append((input_, output)) return entries
def parse_puzzle_input() -> list[Entry]: """ Parses the puzzle input and returns a list of entries """ entries: list[Entry] = [] with open(INPUT_FILE) as f: for line in f: parts = [part.split() for part in line.split(" | ")] input_ = {standardise_signal_pattern(pattern) for pattern in parts[0]} output = [standardise_signal_pattern(pattern) for pattern in parts[1]] entries.append((input_, output)) return entries
Python
def understand_input(input_: set[str]) -> dict[str, int]: """ Figures out which signal pattern corresponds to which digit """ digits: dict[str, int] = {} five_segments: set[str] = set() six_segments: set[str] = set() one = "" four = "" for digit in input_: match len(digit): case 2: one = digit digits[digit] = 1 case 3: digits[digit] = 7 case 4: four = digit digits[digit] = 4 case 5: five_segments.add(digit) case 6: six_segments.add(digit) case 7: digits[digit] = 8 for digit in five_segments: if len(set(digit) & set(one)) == 2: digits[digit] = 3 elif len(set(digit) & (set(four) - set(one))) == 2: digits[digit] = 5 else: digits[digit] = 2 for digit in six_segments: if len(set(digit) & (set(four) - set(one))) == 1: digits[digit] = 0 elif len(set(digit) & set(one)) == 2: digits[digit] = 9 else: digits[digit] = 6 return digits
def understand_input(input_: set[str]) -> dict[str, int]: """ Figures out which signal pattern corresponds to which digit """ digits: dict[str, int] = {} five_segments: set[str] = set() six_segments: set[str] = set() one = "" four = "" for digit in input_: match len(digit): case 2: one = digit digits[digit] = 1 case 3: digits[digit] = 7 case 4: four = digit digits[digit] = 4 case 5: five_segments.add(digit) case 6: six_segments.add(digit) case 7: digits[digit] = 8 for digit in five_segments: if len(set(digit) & set(one)) == 2: digits[digit] = 3 elif len(set(digit) & (set(four) - set(one))) == 2: digits[digit] = 5 else: digits[digit] = 2 for digit in six_segments: if len(set(digit) & (set(four) - set(one))) == 1: digits[digit] = 0 elif len(set(digit) & set(one)) == 2: digits[digit] = 9 else: digits[digit] = 6 return digits
Python
def parse_output(entry: Entry) -> list[int]: """ Returns a list of digits corresponding to the output signal patterns """ input_, output = entry digit_parser = understand_input(input_) return [digit_parser[digit] for digit in output]
def parse_output(entry: Entry) -> list[int]: """ Returns a list of digits corresponding to the output signal patterns """ input_, output = entry digit_parser = understand_input(input_) return [digit_parser[digit] for digit in output]
Python
def solve_part1(outputs: list[list[int]]) -> int: """ Counts the number of digits 1, 4, 7, and 8 in the outputs """ return sum(digit in (1, 4, 7, 8) for digit in chain(*outputs))
def solve_part1(outputs: list[list[int]]) -> int: """ Counts the number of digits 1, 4, 7, and 8 in the outputs """ return sum(digit in (1, 4, 7, 8) for digit in chain(*outputs))
Python
def solve_part2(outputs: list[list[int]]) -> int: """ Sums the numbers represented in the outputs """ numbers = [int("".join(str(digit) for digit in number)) for number in outputs] return sum(numbers)
def solve_part2(outputs: list[list[int]]) -> int: """ Sums the numbers represented in the outputs """ numbers = [int("".join(str(digit) for digit in number)) for number in outputs] return sum(numbers)
Python
def parse_input() -> list[int]: """ Parses the input and returns a list of depth measurements. """ with open(INPUT_FILE, "r") as f: return [int(line) for line in f]
def parse_input() -> list[int]: """ Parses the input and returns a list of depth measurements. """ with open(INPUT_FILE, "r") as f: return [int(line) for line in f]
Python
def count_increases(measurements: list[int]) -> int: """ Counts the number of times a measurement increases from the previous measurement. """ return sum(1 for a, b in zip(measurements[:-1], measurements[1:]) if a < b)
def count_increases(measurements: list[int]) -> int: """ Counts the number of times a measurement increases from the previous measurement. """ return sum(1 for a, b in zip(measurements[:-1], measurements[1:]) if a < b)
Python
def parse_input() -> dict[int, Scanner]: """ Parses the input and return a dict of scanner number and their scans as a set of position vectors """ with open(INPUT_FILE) as f: scans = f.read().strip().split("\n\n") scanners: dict[int, Scanner] = {} for i, scan in enumerate(scans): vectors: set[Vector] = set() for line in scan.split("\n")[1:]: x, y, z = line.strip().split(",") vectors.add((int(x), int(y), int(z))) scanners[i] = vectors return scanners
def parse_input() -> dict[int, Scanner]: """ Parses the input and return a dict of scanner number and their scans as a set of position vectors """ with open(INPUT_FILE) as f: scans = f.read().strip().split("\n\n") scanners: dict[int, Scanner] = {} for i, scan in enumerate(scans): vectors: set[Vector] = set() for line in scan.split("\n")[1:]: x, y, z = line.strip().split(",") vectors.add((int(x), int(y), int(z))) scanners[i] = vectors return scanners
Python
def distance(first: Vector, second: Vector) -> Vector: """ Calculates the difference of two position vectors """ return (first[0] - second[0], first[1] - second[1], first[2] - second[2])
def distance(first: Vector, second: Vector) -> Vector: """ Calculates the difference of two position vectors """ return (first[0] - second[0], first[1] - second[1], first[2] - second[2])
Python
def match( oriented_scanner: Scanner, other_scanner: Scanner ) -> tuple[Scanner, Vector] | None: """ Returns the scans of the other_scanner relative to the oriented_scanner and the position of the other_scanner relative to the oriented_scanner or None, if the scanners have less than 12 beacons in common """ for symmetry in get_direct_symmetries(other_scanner): distance_counter: Counter[Vector] = Counter() for a, b in product(oriented_scanner, symmetry): distance_counter[distance(a, b)] += 1 for vector, count in distance_counter.items(): if count >= 12: absolute_scanner = { (x + vector[0], y + vector[1], z + vector[2]) for x, y, z in symmetry } return absolute_scanner, vector return None
def match( oriented_scanner: Scanner, other_scanner: Scanner ) -> tuple[Scanner, Vector] | None: """ Returns the scans of the other_scanner relative to the oriented_scanner and the position of the other_scanner relative to the oriented_scanner or None, if the scanners have less than 12 beacons in common """ for symmetry in get_direct_symmetries(other_scanner): distance_counter: Counter[Vector] = Counter() for a, b in product(oriented_scanner, symmetry): distance_counter[distance(a, b)] += 1 for vector, count in distance_counter.items(): if count >= 12: absolute_scanner = { (x + vector[0], y + vector[1], z + vector[2]) for x, y, z in symmetry } return absolute_scanner, vector return None
Python
def orient_scanners(scanners: dict[int, Scanner]) -> tuple[list[Scanner], set[Vector]]: """ Orients all scanners relative to Scanner 0 and returns a list of oriented scanners and a set of the positions of scanners """ oriented_scanners = {0: scanners[0]} scanner_positions: dict[int, Vector] = {0: (0, 0, 0)} while not_oriented_scanners := set(scanners) - set(oriented_scanners): for oriented, new in product(oriented_scanners, not_oriented_scanners): oriented_scanner = oriented_scanners[oriented] new_scanner = scanners[new] if output := match(oriented_scanner, new_scanner): scanner, vector = output oriented_scanners[new] = scanner scanner_positions[new] = vector break return list(oriented_scanners.values()), set(scanner_positions.values())
def orient_scanners(scanners: dict[int, Scanner]) -> tuple[list[Scanner], set[Vector]]: """ Orients all scanners relative to Scanner 0 and returns a list of oriented scanners and a set of the positions of scanners """ oriented_scanners = {0: scanners[0]} scanner_positions: dict[int, Vector] = {0: (0, 0, 0)} while not_oriented_scanners := set(scanners) - set(oriented_scanners): for oriented, new in product(oriented_scanners, not_oriented_scanners): oriented_scanner = oriented_scanners[oriented] new_scanner = scanners[new] if output := match(oriented_scanner, new_scanner): scanner, vector = output oriented_scanners[new] = scanner scanner_positions[new] = vector break return list(oriented_scanners.values()), set(scanner_positions.values())
Python
def solve_part1(oriented_scanners: list[Scanner]) -> int: """ Calculates the solution for part 1 """ beacons = set(chain(*oriented_scanners)) return len(beacons)
def solve_part1(oriented_scanners: list[Scanner]) -> int: """ Calculates the solution for part 1 """ beacons = set(chain(*oriented_scanners)) return len(beacons)
Python
def manhattan_distance(a: Vector, b: Vector) -> int: """ Calculates the Manhattan distance between two position vectors """ return sum(abs(x - y) for x, y in zip(a, b))
def manhattan_distance(a: Vector, b: Vector) -> int: """ Calculates the Manhattan distance between two position vectors """ return sum(abs(x - y) for x, y in zip(a, b))
Python
def solve_part2(scanner_positions: set[Vector]) -> int: """ Calculates the solution for part 2 """ return max(manhattan_distance(a, b) for a, b in combinations(scanner_positions, 2))
def solve_part2(scanner_positions: set[Vector]) -> int: """ Calculates the solution for part 2 """ return max(manhattan_distance(a, b) for a, b in combinations(scanner_positions, 2))
Python
def hex_to_bin(char: str) -> Bits: """ Takes a hex digit and returns a 4-digit binary representation """ b = bin(int(char, 16)).removeprefix("0b") padding = "0" * (4 - len(b)) return padding + b
def hex_to_bin(char: str) -> Bits: """ Takes a hex digit and returns a 4-digit binary representation """ b = bin(int(char, 16)).removeprefix("0b") padding = "0" * (4 - len(b)) return padding + b
Python
def parse_input() -> Bits: """ Parses the input and returns a string of bits with trailing 0s removed """ with open(INPUT_FILE) as f: return "".join(hex_to_bin(char) for char in f.readline().strip()).rstrip("0")
def parse_input() -> Bits: """ Parses the input and returns a string of bits with trailing 0s removed """ with open(INPUT_FILE) as f: return "".join(hex_to_bin(char) for char in f.readline().strip()).rstrip("0")
Python
def read_packets(data: Bits) -> tuple[Packet, Bits]: """ Parses the bits and returns the first packet it finds and the remaining bits (so that it can be used recursively) """ version, type_id, data = int(data[:3], 2), int(data[3:6], 2), data[6:] if type_id == 4: number_bits = "" while True: group, data = data[:5], data[5:] number_bits += group[1:] if group[0] == "0": break return LiteralValue(version, int(number_bits, 2)), data length_type, data = data[0], data[1:] args: list[Packet] = [] match length_type: case "0": data_length, data = int(data[:15], 2), data[15:] subpacket_data, data = data[:data_length], data[data_length:] while subpacket_data: packet, subpacket_data = read_packets(subpacket_data) args.append(packet) case "1": subpacket_count, data = int(data[:11], 2), data[11:] for _ in range(subpacket_count): packet, data = read_packets(data) args.append(packet) operator = Operation(type_id) return Operator(version, operator, args), data
def read_packets(data: Bits) -> tuple[Packet, Bits]: """ Parses the bits and returns the first packet it finds and the remaining bits (so that it can be used recursively) """ version, type_id, data = int(data[:3], 2), int(data[3:6], 2), data[6:] if type_id == 4: number_bits = "" while True: group, data = data[:5], data[5:] number_bits += group[1:] if group[0] == "0": break return LiteralValue(version, int(number_bits, 2)), data length_type, data = data[0], data[1:] args: list[Packet] = [] match length_type: case "0": data_length, data = int(data[:15], 2), data[15:] subpacket_data, data = data[:data_length], data[data_length:] while subpacket_data: packet, subpacket_data = read_packets(subpacket_data) args.append(packet) case "1": subpacket_count, data = int(data[:11], 2), data[11:] for _ in range(subpacket_count): packet, data = read_packets(data) args.append(packet) operator = Operation(type_id) return Operator(version, operator, args), data
Python
def evaluate(packet: Packet) -> LiteralValue: """ Applies all operators in the packet and returns a LiteralValue, where the version is the sum of all versions of (sub)packets composing the given packet, and the value is the result of the operations """ match packet: case LiteralValue(): return packet case Operator(): literal_values = [evaluate(subpacket) for subpacket in packet.subpackets] versions = [lv.version for lv in literal_values] values = [lv.value for lv in literal_values] version_sum = packet.version + sum(versions) return LiteralValue(version_sum, apply_operator(packet.operation, values)) case _: raise ValueError
def evaluate(packet: Packet) -> LiteralValue: """ Applies all operators in the packet and returns a LiteralValue, where the version is the sum of all versions of (sub)packets composing the given packet, and the value is the result of the operations """ match packet: case LiteralValue(): return packet case Operator(): literal_values = [evaluate(subpacket) for subpacket in packet.subpackets] versions = [lv.version for lv in literal_values] values = [lv.value for lv in literal_values] version_sum = packet.version + sum(versions) return LiteralValue(version_sum, apply_operator(packet.operation, values)) case _: raise ValueError
Python
def apply_operator(operation: Operation, args: list[int]) -> int: """ Applies the correct operation to the arguments """ match operation: case Operation.SUM: return sum(args) case Operation.PRODUCT: return prod(args) case Operation.MINIMUM: return min(args) case Operation.MAXIMUM: return max(args) case Operation.GREATER_THAN: return args[0] > args[1] case Operation.LESS_THAN: return args[0] < args[1] case Operation.EQUAL: return args[0] == args[1] case _: raise ValueError
def apply_operator(operation: Operation, args: list[int]) -> int: """ Applies the correct operation to the arguments """ match operation: case Operation.SUM: return sum(args) case Operation.PRODUCT: return prod(args) case Operation.MINIMUM: return min(args) case Operation.MAXIMUM: return max(args) case Operation.GREATER_THAN: return args[0] > args[1] case Operation.LESS_THAN: return args[0] < args[1] case Operation.EQUAL: return args[0] == args[1] case _: raise ValueError
Python
def parse_block(block: str) -> Board: """ Parses a block of 5 lines (passed as a single string with '\n's) and returns a list of 5 rows, where each row is a list of 5 numbers """ return [[int(x) for x in line.split()] for line in block.split("\n")]
def parse_block(block: str) -> Board: """ Parses a block of 5 lines (passed as a single string with '\n's) and returns a list of 5 rows, where each row is a list of 5 numbers """ return [[int(x) for x in line.split()] for line in block.split("\n")]
Python
def parse_input() -> tuple[list[int], list[Board]]: """ Parses the input and returns a list of numbers that were drawn and a list of Boards """ with open(INPUT_FILE) as f: first, *rest = f.read().strip().split("\n\n") draws = [int(x) for x in first.split(",")] boards = [parse_block(block) for block in rest] return (draws, boards)
def parse_input() -> tuple[list[int], list[Board]]: """ Parses the input and returns a list of numbers that were drawn and a list of Boards """ with open(INPUT_FILE) as f: first, *rest = f.read().strip().split("\n\n") draws = [int(x) for x in first.split(",")] boards = [parse_block(block) for block in rest] return (draws, boards)
Python
def board_lines(board: Board) -> list[set[int]]: """ Returns a list of all lines (rows and columns) on a given board """ return [set(row) for row in board] + [set(column) for column in zip(*board)]
def board_lines(board: Board) -> list[set[int]]: """ Returns a list of all lines (rows and columns) on a given board """ return [set(row) for row in board] + [set(column) for column in zip(*board)]
Python
def predicted_win(board: Board, draws: list[int]) -> Prediction: """ Goes through the drawn numbers and returns a Prediction, which is a tuple of two numbers: - the turn on which the board wins - the score of the board at that moment """ lines = board_lines(board) for i, draw in enumerate(draws): for line in lines: if draw in line: line.remove(draw) if not all(lines): score = get_score(board, draws[: i + 1]) return (i, score) raise ValueError
def predicted_win(board: Board, draws: list[int]) -> Prediction: """ Goes through the drawn numbers and returns a Prediction, which is a tuple of two numbers: - the turn on which the board wins - the score of the board at that moment """ lines = board_lines(board) for i, draw in enumerate(draws): for line in lines: if draw in line: line.remove(draw) if not all(lines): score = get_score(board, draws[: i + 1]) return (i, score) raise ValueError
Python
def parse_input() -> Target: """ Parses the input and returns the target boundaries """ with open(INPUT_FILE) as f: min_x, max_x, min_y, max_y = re.findall(r"-?\d+", f.readline()) return (int(min_x), int(max_x), int(min_y), int(max_y))
def parse_input() -> Target: """ Parses the input and returns the target boundaries """ with open(INPUT_FILE) as f: min_x, max_x, min_y, max_y = re.findall(r"-?\d+", f.readline()) return (int(min_x), int(max_x), int(min_y), int(max_y))
Python
def in_target(target: Target, position: Position) -> bool: """ Checks if the position is within the target """ x, y = position min_x, max_x, min_y, max_y = target return min_x <= x <= max_x and min_y <= y <= max_y
def in_target(target: Target, position: Position) -> bool: """ Checks if the position is within the target """ x, y = position min_x, max_x, min_y, max_y = target return min_x <= x <= max_x and min_y <= y <= max_y
Python
def solve(target: Target) -> tuple[int, int]: """ Evaluates all reasonable starting velocities and counts the number of possible starting velocities (for part 2) and the highest y coordinate reached from these velocities (for part 1) """ possible_velocities_count = 0 highest_y_overall = -1 _, max_x, min_y, _ = target for velocity_x in range(max_x + 1): for velocity_y in range(min_y, -min_y): velocity = (velocity_x, velocity_y) path = get_path(target, velocity) if any(in_target(target, position) for position in path): possible_velocities_count += 1 highest_y = max(position[1] for position in path) highest_y_overall = max(highest_y_overall, highest_y) return highest_y_overall, possible_velocities_count
def solve(target: Target) -> tuple[int, int]: """ Evaluates all reasonable starting velocities and counts the number of possible starting velocities (for part 2) and the highest y coordinate reached from these velocities (for part 1) """ possible_velocities_count = 0 highest_y_overall = -1 _, max_x, min_y, _ = target for velocity_x in range(max_x + 1): for velocity_y in range(min_y, -min_y): velocity = (velocity_x, velocity_y) path = get_path(target, velocity) if any(in_target(target, position) for position in path): possible_velocities_count += 1 highest_y = max(position[1] for position in path) highest_y_overall = max(highest_y_overall, highest_y) return highest_y_overall, possible_velocities_count
Python
def parse_input() -> Heightmap: """ Parses the input and returns a Heightmap """ with open(INPUT_FILE) as f: heights = [[int(x) for x in line.strip()] for line in f] heightmap: Heightmap = dict() for (y, row) in enumerate(heights): for (x, height) in enumerate(row): heightmap[(x, y)] = height return heightmap
def parse_input() -> Heightmap: """ Parses the input and returns a Heightmap """ with open(INPUT_FILE) as f: heights = [[int(x) for x in line.strip()] for line in f] heightmap: Heightmap = dict() for (y, row) in enumerate(heights): for (x, height) in enumerate(row): heightmap[(x, y)] = height return heightmap
Python
def solve_part1(heightmap: Heightmap, low_points: set[Point]) -> int: """ Calculates the sum of the risk levels of all low points """ return sum(1 + heightmap[point] for point in low_points)
def solve_part1(heightmap: Heightmap, low_points: set[Point]) -> int: """ Calculates the sum of the risk levels of all low points """ return sum(1 + heightmap[point] for point in low_points)
Python
def solve_part2(heightmap: Heightmap, low_points: set[Point]) -> int: """ Calculates the product of the sizes of the three largest basins """ basins = get_basins(heightmap, low_points) basin_sizes = sorted((len(basin) for basin in basins), reverse=True) return basin_sizes[0] * basin_sizes[1] * basin_sizes[2]
def solve_part2(heightmap: Heightmap, low_points: set[Point]) -> int: """ Calculates the product of the sizes of the three largest basins """ basins = get_basins(heightmap, low_points) basin_sizes = sorted((len(basin) for basin in basins), reverse=True) return basin_sizes[0] * basin_sizes[1] * basin_sizes[2]
Python
def parse_input() -> tuple[set[Point], list[Fold]]: """ Parses the input and returns a set of points and a list of folding instructions """ with open(INPUT_FILE) as f: blocks = f.read().split("\n\n") point_lines, fold_lines = (block.splitlines() for block in blocks) points: set[Point] = set() for line in point_lines: x, y = line.split(",") points.add((int(x), int(y))) folds: list[Fold] = [] for line in fold_lines: axis, value = line.removeprefix("fold along ").split("=") folds.append((axis, int(value))) return (points, folds)
def parse_input() -> tuple[set[Point], list[Fold]]: """ Parses the input and returns a set of points and a list of folding instructions """ with open(INPUT_FILE) as f: blocks = f.read().split("\n\n") point_lines, fold_lines = (block.splitlines() for block in blocks) points: set[Point] = set() for line in point_lines: x, y = line.split(",") points.add((int(x), int(y))) folds: list[Fold] = [] for line in fold_lines: axis, value = line.removeprefix("fold along ").split("=") folds.append((axis, int(value))) return (points, folds)
Python
def apply_fold(points: set[Point], fold: Fold) -> set[Point]: """ Folds the paper and returns a set of points that are visible """ axis, value = fold new_points: set[Point] = set() for point in points: x, y = point if axis == "x": distance_from_line = abs(x - value) new_x = value - distance_from_line new_points.add((new_x, y)) elif axis == "y": distance_from_line = abs(y - value) new_y = value - distance_from_line new_points.add((x, new_y)) return new_points
def apply_fold(points: set[Point], fold: Fold) -> set[Point]: """ Folds the paper and returns a set of points that are visible """ axis, value = fold new_points: set[Point] = set() for point in points: x, y = point if axis == "x": distance_from_line = abs(x - value) new_x = value - distance_from_line new_points.add((new_x, y)) elif axis == "y": distance_from_line = abs(y - value) new_y = value - distance_from_line new_points.add((x, new_y)) return new_points
Python
def solve_part1(points: set[Point], fold: Fold) -> int: """ Counts the number of points that remain visible after the fold """ return len(apply_fold(points, fold))
def solve_part1(points: set[Point], fold: Fold) -> int: """ Counts the number of points that remain visible after the fold """ return len(apply_fold(points, fold))
Python
def solve_part2(points: set[Point], folds: list[Fold]) -> str: """ Applies all folds to the given points and returns a multi-line string that reveals the eight-letter code when printed """ for fold in folds: points = apply_fold(points, fold) height = max(y for _, y in points) + 1 width = max(x for x, _ in points) + 1 output: list[str] = [] for y in range(height): row = "".join("#" if (x, y) in points else "." for x in range(width)) output.append(row) return "\n".join(output)
def solve_part2(points: set[Point], folds: list[Fold]) -> str: """ Applies all folds to the given points and returns a multi-line string that reveals the eight-letter code when printed """ for fold in folds: points = apply_fold(points, fold) height = max(y for _, y in points) + 1 width = max(x for x, _ in points) + 1 output: list[str] = [] for y in range(height): row = "".join("#" if (x, y) in points else "." for x in range(width)) output.append(row) return "\n".join(output)
Python
def add_neighbour(self, cave: "Cave"): """ Adds the given cave to the list of neighbours """ self.neighbours.append(cave)
def add_neighbour(self, cave: "Cave"): """ Adds the given cave to the list of neighbours """ self.neighbours.append(cave)
Python
def parse_input() -> tuple[str, Ruleset]: """ Parses the input and returns the polymer template and the pair insertion rules """ with open(INPUT_FILE) as f: template, _, *rules = f.read().splitlines() ruleset = dict(rule.split(" -> ") for rule in rules) return (template, ruleset)
def parse_input() -> tuple[str, Ruleset]: """ Parses the input and returns the polymer template and the pair insertion rules """ with open(INPUT_FILE) as f: template, _, *rules = f.read().splitlines() ruleset = dict(rule.split(" -> ") for rule in rules) return (template, ruleset)
Python
def step(ruleset: Ruleset, pair_counter: Counter[str]) -> Counter[str]: """ Applies a single step to the given pair_counter """ new_pair_counter: Counter[str] = Counter() for pair, count in pair_counter.items(): inserted = ruleset[pair] first, second = pair new_pair_counter[first + inserted] += count new_pair_counter[inserted + second] += count return new_pair_counter
def step(ruleset: Ruleset, pair_counter: Counter[str]) -> Counter[str]: """ Applies a single step to the given pair_counter """ new_pair_counter: Counter[str] = Counter() for pair, count in pair_counter.items(): inserted = ruleset[pair] first, second = pair new_pair_counter[first + inserted] += count new_pair_counter[inserted + second] += count return new_pair_counter
Python
def calculate_answer(template: str, pair_counter: Counter[str]) -> int: """ Calculates how many times each letter occurs by adding the counts of pairs where the given letter comes first and 1 for the last letter of the original template (which does not change), then subtracts the lowest count from the highest count and returns the answer """ letter_counter = Counter(template[-1]) for pair, count in pair_counter.items(): first_letter, _ = pair letter_counter[first_letter] += count return max(letter_counter.values()) - min(letter_counter.values())
def calculate_answer(template: str, pair_counter: Counter[str]) -> int: """ Calculates how many times each letter occurs by adding the counts of pairs where the given letter comes first and 1 for the last letter of the original template (which does not change), then subtracts the lowest count from the highest count and returns the answer """ letter_counter = Counter(template[-1]) for pair, count in pair_counter.items(): first_letter, _ = pair letter_counter[first_letter] += count return max(letter_counter.values()) - min(letter_counter.values())