AdventOfCode/fred.py

67 lines
2.1 KiB
Python
Raw Normal View History

2024-11-28 15:10:22 +01:00
import re
2024-11-24 19:14:52 +01:00
def list2int(x):
return list(map(int, x))
2024-11-25 12:27:11 +01:00
2024-11-28 15:10:22 +01:00
def get_re(pattern,str):
match = re.match(pattern, str)
if match:
return match
return None
2024-11-25 12:27:11 +01:00
def ppprint(x):
for idx,i in enumerate(x):
for jdx,j in enumerate(i):
print(x[idx][jdx],end='')
print()
2024-11-28 13:58:15 +01:00
def get_value_in_direction(grid, position, direction=None):
"""
Get the value in a specified direction from a given position in a grid.
If no direction is provided, returns the value at the current position.
Parameters:
grid (list of list of int/float): The 2D grid.
position (set): A set containing x (row index) and y (column index) as integers.
direction (str, optional): The direction to check.
Options: 'up', 'down', 'left', 'right',
'up-left', 'up-right', 'down-left', 'down-right'.
Returns:
The value in the grid in the specified direction, or None if out of bounds.
"""
# Ensure the position is a set of two integers
if len(position) != 2 or not all(isinstance(coord, int) for coord in position):
raise ValueError("Position must be a set containing two integers (x, y).")
x, y = position
offsets = {
'up': (-1, 0),
'down': (1, 0),
'left': (0, -1),
'right': (0, 1),
'up-left': (-1, -1),
'up-right': (-1, 1),
'down-left': (1, -1),
'down-right': (1, 1)
}
# If no direction is given, return the value at the current position
if direction is None:
if 0 <= x < len(grid) and 0 <= y < len(grid[x]):
return grid[x][y]
else:
return None
# Validate direction
if direction not in offsets:
raise ValueError(f"Invalid direction: {direction}. Choose from {list(offsets.keys())}")
dx, dy = offsets[direction]
new_x, new_y = x + dx, y + dy
# Check for out-of-bounds, considering varying row lengths
if 0 <= new_x < len(grid) and 0 <= new_y < len(grid[new_x]):
return grid[new_x][new_y]
else:
return None