qid
stringlengths
2
6
ground_truth_solution
stringlengths
249
4.55k
ground_truth_diagram_description
stringlengths
759
3.88k
test_script
stringlengths
839
9.64k
function_signature
stringlengths
218
1.05k
diagram
imagewidth (px)
596
1.02k
capability_aspects
dict
task_type
stringclasses
6 values
q1
def solution(red_triangle: tuple, orange_dots: list) -> int: """ Determine the number of iterations required to absorb all the orange dots. Parameters: red_triangle (tuple): The coordinates of the red triangle (x0, y0). orange_dots (list): A list of tuples, where each tuple represents the coordinates of an orange dot (xi, yi). Returns: int: The number of iterations. """ x0, y0 = red_triangle slopes = set() for x, y in orange_dots: if x == x0: slopes.add('vertical') elif y == y0: slopes.add('horizontal') else: slopes.add((y - y0) / (x - x0)) return len(slopes)
# Problem Description This is a geometric transformation problem on a grid where we need to simulate the absorption of orange dots by purple lines emanating from a red triangle. The goal is to calculate the minimum number of iterations needed to convert all orange dots into purple dots, following specific geometric rules of absorption. # Visual Facts 1. Grid Structure: - The grid is a 4x4 coordinate system (0-3 on both axes) - Grid points are discrete integer coordinates - The origin (0,0) is at the top-left corner 2. Components: - One red triangle (fixed position) - Multiple orange dots (initial state) - Purple dots (transformed state) - Purple lines (transformation medium) 3. Transformation Sequence: - Initial state shows orange dots and one red triangle - Iter1: Vertical line absorption - Iter2: Diagonal line absorption - Iter3: Horizontal line absorption - Iter4: Final diagonal absorption - Process completes in exactly 4 iterations in the example # Visual Patterns 1. Line Properties: - Each purple line must pass through the red triangle - Lines can be: * Vertical (constant x) * Horizontal (constant y) * Diagonal (linear with slope) 2. Absorption Rules: - Any orange dot lying exactly on a purple line gets absorbed - Multiple dots can be absorbed in a single iteration if they lie on the same line - Each dot can only be absorbed once - The line must pass through both the triangle and at least one orange dot 3. Optimization Patterns: - Lines are chosen to maximize the number of dots absorbed per iteration - Dots that share geometric alignment (same x, y, or slope relative to triangle) should be absorbed together - The order of absorption can affect the total number of iterations - Priority seems to be given to lines that can absorb multiple dots simultaneously 4. Mathematical Constraints: - For dots to be absorbed in the same iteration, they must satisfy one of: * Same x-coordinate as triangle (vertical line) * Same y-coordinate as triangle (horizontal line) * Share the same slope relative to triangle position (diagonal line) * Points must be collinear with the triangle 5. Iteration Strategy: - Given the red triangle's position (x0, y0) - Find the dots with xi=x0, these points can be absorbed in the first iteration - Then compute all the slopes to the orange dots (yi-y0)/(xi-x0) - Count the groups that dots share the same slope or x/y coordinate - the total iteration is the number of groups (+1 if there are dots with the same x coordinate as the triangle)
def test(): test_cases = [ ((2, 2), [(2, 4)], 1), ((3, 0), [(3, 1), (3, 2), (3, 3)], 1), ((0, 3), [(1, 3), (2, 3), (4, 3)], 1), ((2, 2), [(1, 1), (0, 0), (3, 3)], 1), ((2, 2), [(0, 2), (2, 4), (4, 4), (2, 0)], 3), ((2, 2), [], 0), ((0, 0), [(1, 1), (2, 2), (3, 3), (4, 4)], 1), ((2, 0), [(0, 0), (0, 1), (1, 3), (2, 1), (3, 2), (4, 0)], 5), ((2, 3), [(0, 3), (2, 1), (4, 3), (3, 4), (1, 5), (0, 5)], 5), ((5, 5), [(0, 0), (0, 5), (5, 0), (10, 5), (5, 10), (10, 10)], 3) ] for i, (red_triangle, orange_dots, expected_output) in enumerate(test_cases): try: output = solution(red_triangle, orange_dots) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`red_triangle`: {red_triangle}\n" f"`orange_dots`: {orange_dots}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`red_triangle`: {red_triangle}\n" f"`orange_dots`: {orange_dots}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(red_triangle: tuple, orange_dots: list) -> int: """ Determine the number of iterations required to absorb all the orange dots. Parameters: red_triangle (tuple): The coordinates of the red triangle (x0, y0). orange_dots (list): A list of tuples, where each tuple represents the coordinates of an orange dot (xi, yi). Returns: int: The number of iterations. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": [ "Propagation" ], "Geometric Objects": [ "Coordinate System", "Point", "Line", "Grid", "Triangle" ], "Mathematical Operations": null, "Spatial Transformations": null, "Topological Relations": [ "Connectivity", "Intersection", "Connection" ] }
Iterative Calculation
q1-2
def solution(red_triangle: tuple, orange_dots: list) -> int: """ Determine the number of iterations required to absorb all the orange dots. Parameters: red_triangle (tuple): The coordinates of the red triangle (x0, y0). orange_dots (list): A list of tuples, where each tuple represents the coordinates of an orange dot (xi, yi). Returns: int: The number of iterations. """ x0, y0 = red_triangle slopes = set() for x, y in orange_dots: if x == x0: slopes.add('vertical+' if y > y0 else 'vertical-') elif y == y0: slopes.add('horizontal+' if x > x0 else 'horizontal-') else: slopes.add(f'+_{(y - y0) / (x - x0)}' if y > y0 else f'-_{(y - y0) / (x - x0)}') return len(slopes)
# Problem Description This problem involves a grid-based transformation where we need to simulate the absorption of orange dots by purple lines emanating from a red triangle. The goal is to calculate the minimum number of iterations required to convert all orange dots into purple dots, following specific geometric rules of absorption. # Visual Facts 1. **Grid Structure:** - The grid is a 4x4 coordinate system (0-3 on both axes). - Grid points are discrete integer coordinates. - The origin (0,0) is at the top-left corner. 2. **Components:** - One red triangle (fixed position). - Multiple orange dots (initial state). - Purple dots (transformed state). - Purple lines (transformation medium). 3. **Transformation Sequence:** - Initial state shows orange dots and one red triangle. - Iter1: Vertical line absorption. - Iter2: Diagonal line absorption. - Iter3: Horizontal line absorption. - Iter4: Final vertical absorption. - Process completes in exactly 4 iterations in the example. # Visual Patterns 1. **Line Properties:** - Each purple line must pass through the red triangle. - Lines can be: * Vertical (constant x). * Horizontal (constant y). * Diagonal (linear with slope). - The line has only one direction, emitting from the red triangle. 2. **Absorption Rules:** - Any orange dot lying exactly on a purple line gets absorbed. - Multiple dots can be absorbed in a single iteration if they lie on the same line. - Each dot can only be absorbed once. - The line must pass through both the triangle and at least one orange dot. - The line is emitted unidirectionally from the red triangle. For example, if two purple points and the red triangle are on the same horizontal line, but one is to the left of the triangle and the other to the right, the triangle needs to emit two lines to absorb them. - Example: red_triangle=(3, 1), orange_dots=[(3, 0), (3, 2), (3, 3)] The orange dots and the red triangle share the same x-coordinate (3), but have different y-coordinates. It can be observed that (3, 0) and the other two orange dots are not on the same side. To convert the three orange dots, the red triangle needs to emit a purple line to (3, 0) first, and then emit another purple line to (3, 2) and (3, 3). Therefore, it takes a total of two iterations to convert them. 3. **Optimization Patterns:** - Lines are chosen to maximize the number of dots absorbed per iteration. - Dots that share geometric alignment (same x, y, or slope relative to triangle) should be absorbed together. - The order of absorption can affect the total number of iterations. - Priority seems to be given to lines that can absorb multiple dots simultaneously. 4. **Mathematical Constraints:** - For dots to be absorbed in the same iteration, they must satisfy one of: * Same x-coordinate as triangle (vertical line). * Same y-coordinate as triangle (horizontal line). * Share the same slope relative to triangle position (diagonal line). * Points must be collinear with the triangle. 5. **Iteration Strategy:** - Given the red triangle's position (x0, y0): - Traverse all the orange dots and classify each dot into a group according to the following rule. - Find the dots with xi=x0 and y>y0, these points belong to the same group. - Find the dots with xi=x0 and y<y0, these points belong to the same group. - Find the dots with yi=y0 and x>x0, these points belong to the same group. - Find the dots with yi=y0 and x<x0, these points belong to the same group. - Then compute all the slopes to the orange dots (yi-y0)/(xi-x0). - Slopes that are equal and have y > y0 belong to the same group, while slopes that are equal and have y<y0 belong to another group. - The total iteration is the number of groups.
def test(): test_cases = [ ((2, 2), [(2, 4)], 1), ((3, 0), [(3, 1), (3, 2), (3, 3)], 1), ((0, 3), [(1, 3), (2, 3), (4, 3)], 1), ((3, 1), [(3, 0), (3, 2), (3, 3)], 2), ((2, 3), [(1, 3), (0, 3), (4, 3)], 2), ((2, 2), [(1, 1), (0, 0), (3, 3)], 2), ((2, 2), [(0, 2), (2, 4), (4, 4), (2, 0)], 4), ((2, 2), [], 0), ((1, 1), [(0, 0), (2, 2), (3, 3), (4, 4)], 2), ((2, 0), [(0, 0), (0, 1), (1, 3), (2, 1), (3, 2), (4, 0)], 6), ((2, 3), [(0, 3), (2, 1), (4, 3), (3, 4), (1, 5), (0, 5)], 6), ((5, 5), [(0, 0), (0, 5), (5, 0), (10, 5), (5, 10), (10, 10), (3, 5)], 6) ] for i, (red_triangle, orange_dots, expected_output) in enumerate(test_cases): try: output = solution(red_triangle, orange_dots) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`red_triangle`: {red_triangle}\n" f"`orange_dots`: {orange_dots}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`red_triangle`: {red_triangle}\n" f"`orange_dots`: {orange_dots}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(red_triangle: tuple, orange_dots: list) -> int: """ Determine the number of iterations required to absorb all the orange dots. Parameters: red_triangle (tuple): The coordinates of the red triangle (x0, y0). orange_dots (list): A list of tuples, where each tuple represents the coordinates of an orange dot (xi, yi). Returns: int: The number of iterations. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": [ "Propagation" ], "Geometric Objects": [ "Coordinate System", "Point", "Line", "Grid", "Triangle" ], "Mathematical Operations": null, "Spatial Transformations": null, "Topological Relations": [ "Connectivity", "Intersection", "Connection" ] }
Iterative Calculation
q1-3
def solution(red_triangle: tuple, orange_dots: list) -> int: """ Determine the number of iterations required to absorb all the orange dots. Parameters: red_triangle (tuple): The coordinates of the red triangle (x0, y0). orange_dots (list): A list of tuples, where each tuple represents the coordinates of an orange dot (xi, yi). Returns: int: The number of iterations. """ x0, y0 = red_triangle slopes = set() for x, y in orange_dots: if x == x0: slopes.add('vertical') elif y == y0: slopes.add('horizontal') else: slopes.add((y - y0) / (x - x0)) return len(slopes) * 2
# Problem Description This problem involves a grid where a red triangle and several orange dots are placed. The goal is to determine the number of iterations required to convert all orange dots into purple dots. Each iteration involves drawing a line through the red triangle, and any orange dot that lies on this line is absorbed and turned into a purple dot in the next iteration. The task is to calculate the minimum number of iterations needed to absorb all the orange dots. # Visual Facts 1. **Grid Structure:** - The grid is a 4x4 coordinate system (0-3 on both axes). - The origin (0,0) is at the top-left corner. 2. **Components:** - One red triangle (fixed position). - Multiple orange dots (initial state). - Light orange dots (transitioning state). - Purple dots (transformed state). - Purple lines (transformation medium). 3. **Transformation Sequence:** - Initial state shows orange dots and one red triangle. - Iterations involve drawing lines through the red triangle. - Orange dots on these lines turn into light orange dots in this iteration, and in the next iteration, they transform into purple dots. - Each orange dot needs two iterations to turn into a purple dot. - The process continues until all orange dots are converted to purple dots. # Visual Patterns 1. **Line Properties:** - Each purple line must pass through the red triangle. - Lines can be: * Vertical (constant x-coordinate). * Horizontal (constant y-coordinate). * Diagonal (linear with slope). 2. **Absorption Rules:** - Any orange dot lying exactly on a purple line gets absorbed. - Each orange dot needs two iterations to turn into a purple dot. - Multiple dots can be absorbed in two iterations if they lie on the same line. - Each dot can only be absorbed once. - The line must pass through both the triangle and at least one orange dot. 3. **Optimization Patterns:** - Lines are chosen to maximize the number of dots absorbed per iteration. - Dots that share geometric alignment (same x, y, or slope relative to the triangle) should be absorbed together. - The order of absorption can affect the total number of iterations. - Priority seems to be given to lines that can absorb multiple dots simultaneously. 4. **Mathematical Constraints:** - For dots to be absorbed in the same two iterations, they must satisfy one of: * Same x-coordinate as the triangle (vertical line). * Same y-coordinate as the triangle (horizontal line). * Share the same slope relative to the triangle position (diagonal line). * Points must be collinear with the triangle. 5. **Iteration Strategy:** - Given the red triangle's position (x0, y0): - Find the dots with xi=x0; these points can be absorbed in the first two iteration. - Then compute all the slopes to the orange dots (yi-y0)/(xi-x0). - Count the groups of dots that share the same slope or x/y coordinate. - The number of iterations multiplied by two is the number of unique groups (+2 if there are dots with the same x-coordinate as the triangle).
def test(): test_cases = [ ((2, 2), [(2, 4)], 2), ((3, 0), [(3, 1), (3, 2), (3, 3)], 2), ((0, 3), [(1, 3), (2, 3), (4, 3)], 2), ((2, 2), [(1, 1), (0, 0), (3, 3)], 2), ((2, 2), [(0, 2), (2, 4), (4, 4), (2, 0)], 6), ((2, 2), [], 0), ((0, 0), [(1, 1), (2, 2), (3, 3), (4, 4)], 2), ((2, 0), [(0, 0), (0, 1), (1, 3), (2, 1), (3, 2), (4, 0)], 10), ((2, 3), [(0, 3), (2, 1), (4, 3), (3, 4), (1, 5), (0, 5)], 10), ((5, 5), [(0, 0), (0, 5), (5, 0), (10, 5), (5, 10), (10, 10)], 6) ] for i, (red_triangle, orange_dots, expected_output) in enumerate(test_cases): try: output = solution(red_triangle, orange_dots) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`red_triangle`: {red_triangle}\n" f"`orange_dots`: {orange_dots}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`red_triangle`: {red_triangle}\n" f"`orange_dots`: {orange_dots}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(red_triangle: tuple, orange_dots: list) -> int: """ Determine the number of iterations required to absorb all the orange dots. Parameters: red_triangle (tuple): The coordinates of the red triangle (x0, y0). orange_dots (list): A list of tuples, where each tuple represents the coordinates of an orange dot (xi, yi). Returns: int: The number of iterations. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": [ "Propagation" ], "Geometric Objects": [ "Coordinate System", "Point", "Line", "Grid", "Triangle" ], "Mathematical Operations": null, "Spatial Transformations": null, "Topological Relations": [ "Connectivity", "Intersection", "Connection" ] }
Iterative Calculation
q10
from typing import List def solution(n: int) -> List[List[int]]: """ Given an n x n grid, determine the coordinates of a specific pattern that is formed on the grid. Parameters: n (int): The dimensions of the grid (which is an n*n 2D matrix). n is always an odd number. Returns: List[List[int]]: A n*n 2D matrix where the coordinates of the black cells are marked with 1 and the rest are marked with 0. """ grid = [[0 for _ in range(n)] for _ in range(n)] mid = n // 2 grid[mid][mid] = 1 for i in range(mid + 1): if (i-mid) % 2 == 1: continue grid[i][i] = 1 grid[i][n - 1 - i] = 1 grid[n - 1 - i][i] = 1 grid[n - 1 - i][n - 1 - i] = 1 return grid
# Problem Description This is a grid pattern generation problem where we need to: - Create an n×n grid (where n is always odd) - Place black cells (represented as 1) in specific positions - Fill remaining cells with white (represented as 0) - Return the resulting grid as a 2D matrix - The pattern follows a specific rule of expansion as n increases # Visual Facts 1. Grid Properties: - Each grid is n×n where n is odd (1, 3, 5, 7, 9) - Each step adds 2 to n, creating a new outer ring 2. Cell States: - Cells are either black (filled) or white (empty) - For n=1: Single black cell - For n=3: One black cell at the center - For n=5: Five black cells - For n=7: Five black cells - For n=9: Nine black cells # Visual Patterns A cell at position [i][j] is black when either: 1. It's the center: i = j = n//2 2. It's a corner of an odd ring: |i-n//2| = |j-n//2| = 2k where k ≥ 1 This means black cells appear at: - Center position - Positions where distance from center (in both x and y) is equal and is a multiple of 2 All other cells are white. This explains: - n=1: Center only - n=3: Center only - n=5: Center + 4 cells at distance 2 - n=7: Same as n=5 - n=9: Center + 4 cells at distance 2 + 4 cells at distance 4
def reference(n): grid = [[0 for _ in range(n)] for _ in range(n)] # Middle index mid = n // 2 # Set the center grid[mid][mid] = 1 # Set the diagonals for i in range(mid + 1): if (i-mid) % 2 == 1: continue grid[i][i] = 1 grid[i][n-1-i] = 1 grid[n-1-i][i] = 1 grid[n-1-i][n-1-i] = 1 return grid def test(): for n in range(3, 40, 4): try: result = solution(n) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`n`: {n}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message expected = reference(n) if result != expected: error_message = ( f"The following Test Case failed:\n" f"`n`: {n}\n\n" f"Actual Output:\n{result}\n\n" f"Expected Output:\n{expected}" ) assert False, error_message test()
from typing import List def solution(n: int) -> List[List[int]]: """ Given an n x n grid, determine the coordinates of a specific pattern that is formed on the grid. Parameters: n (int): The dimensions of the grid (which is an n*n 2D matrix). n is always an odd number. Returns: List[List[int]]: A n*n 2D matrix where the coordinates of the black cells are marked with 1 and the rest are marked with 0. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": [ "Concentric Arrangement", "Cross Pattern" ], "Geometric Objects": [ "Square", "Grid" ], "Mathematical Operations": null, "Spatial Transformations": [ "Scaling" ], "Topological Relations": [ "Adjacency", "Boundary" ] }
Expansion
q10-2
from typing import List def solution(n: int) -> List[List[int]]: """ Given an n x n grid, determine the coordinates of a specific pattern that is formed on the grid. Parameters: n (int): The dimensions of the grid (which is an n*n 2D matrix). n is always an odd number. Returns: List[List[int]]: A n*n 2D matrix where the coordinates of the black cells are marked with 1 and the rest are marked with 0. """ grid = [[0 for _ in range(n)] for _ in range(n)] # Middle index mid = n // 2 # Set the center grid[mid][mid] = 1 # Set the diagonals for i in range(mid + 1): if (i-mid) % 2 == 1: continue grid[i][mid] = 1 grid[mid][i] = 1 grid[n - 1 - i][mid] = 1 grid[mid][n - 1 - i] = 1 return grid
# Problem Description This is a grid pattern generation problem where we need to: - Create an n×n grid (where n is always odd) - Place black cells (represented as 1) in specific positions - Fill remaining cells with white (represented as 0) - Return the resulting grid as a 2D matrix - The pattern follows a specific rule of expansion as n increases # Visual Facts 1. Grid Properties: - Each grid is n×n where n is odd (1, 3, 5, 7, 9) - Each step adds 2 to n, creating a new outer ring 2. Cell States: - Cells are either black (filled) or white (empty) - For n=1: Single black cell - For n=3: Single black cell in center - For n=5: Five black cells - For n=7: Five black cells - For n=9: Nine black cells # Visual Patterns A cell at position [i][j] is black when either: 1. It's at the center (i = j = n//2) 2. It's 2*k units away from center vertically: j = n//2 & |i-n//2| = 2k, where k ≥ 1 3. It's 2*k units away from center horizontally: i = n//2 & |j-n//2| = 2k, where k ≥ 1 This means black cells appear at: - Center position - Positions where lies in the same row or column as the center and its distance from the center is a multiple of 2 - All other cells are white. This explains: - n=1: Center only - n=3: Center only - n=5: Center + 4 cells at distance 2 - n=7: Same as n=5 - n=9: Center + 4 cells at distance 2 + 4 cells at distance 4
def reference(n): grid = [[0 for _ in range(n)] for _ in range(n)] # Middle index mid = n // 2 # Set the center grid[mid][mid] = 1 # Set the diagonals for i in range(mid + 1): if (i-mid) % 2 == 1: continue grid[i][mid] = 1 grid[mid][i] = 1 grid[n - 1 - i][mid] = 1 grid[mid][n - 1 - i] = 1 return grid def test(): for n in range(3, 40, 4): try: output = solution(n) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`n`: {n}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message expected_output = reference(n) if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`n`: {n}\n\n" f"Actual Output (n x n matrix):\n" f"{'\n'.join(str(row) for row in output)}\n\n" f"Expected Output (n x n matrix):\n" f"{'\n'.join(str(row) for row in expected_output)}" ) assert False, error_message test()
from typing import List def solution(n: int) -> List[List[int]]: """ Given an n x n grid, determine the coordinates of a specific pattern that is formed on the grid. Parameters: n (int): The dimensions of the grid (which is an n*n 2D matrix). n is always an odd number. Returns: List[List[int]]: A n*n 2D matrix where the coordinates of the black cells are marked with 1 and the rest are marked with 0. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": [ "Concentric Arrangement", "Cross Pattern" ], "Geometric Objects": [ "Square", "Grid" ], "Mathematical Operations": null, "Spatial Transformations": [ "Scaling" ], "Topological Relations": [ "Adjacency", "Boundary" ] }
Expansion
q10-3
from typing import List def solution(n: int) -> List[List[int]]: """ Given an n x n grid, determine the coordinates of a specific pattern that is formed on the grid. Parameters: n (int): The dimensions of the grid (which is an n*n 2D matrix). n is always an odd number. Returns: List[List[int]]: A n*n 2D matrix where the coordinates of the black cells are marked with 1 and the rest are marked with 0. """ grid = [[0 for _ in range(n)] for _ in range(n)] # Middle index mid = n // 2 # Set the center grid[mid][mid] = 0 # Set the diagonals for i in range(mid + 1): if (i-mid) % 2 == 0: continue grid[i][i] = 1 grid[i][n - 1 - i] = 1 grid[n - 1 - i][i] = 1 grid[n - 1 - i][n - 1 - i] = 1 return grid
# Problem Description This is a grid pattern generation problem where we need to: - Create an n×n grid (where n is always odd) - Place black cells (represented as 1) in specific positions - Fill remaining cells with white (represented as 0) - Return the resulting grid as a 2D matrix - The pattern follows a specific rule of expansion as n increases # Visual Facts 1. Grid Properties: - Each grid is n×n where n is odd (1, 3, 5, 7, 9, 11) - Each step adds 2 to n, creating a new outer ring 2. Cell States: - Cells are either black (filled) or white (empty) - For n=1: no black cells - For n=3: four black cells - For n=5: four black cells - For n=7: eight black cells - For n=9: eight black cells - For n=11: twelve black cells # Visual Patterns A cell at position [i][j] is black when it's a corner of an odd ring: |i-n//2| = |j-n//2| = 1+2k where k ≥ 0 This means black cells appear at: - Positions where distance from center (in both x and y) is equal and is a odd number All other cells are white. This explains: - n=1: no black cells - n=3: four cells at distance 1 - n=5: four cells at distance 1 - n=7: four cells at distance 1 + four cells at distance 3 - n=9: four cells at distance 1 + four cells at distance 3 - n=11: four cells at distance 1 + four cells at distance 3 + four cells at distance 5
def reference(n): grid = [[0 for _ in range(n)] for _ in range(n)] # Middle index mid = n // 2 # Set the center grid[mid][mid] = 0 # Set the diagonals for i in range(mid + 1): if (i-mid) % 2 == 0: continue grid[i][i] = 1 grid[i][n - 1 - i] = 1 grid[n - 1 - i][i] = 1 grid[n - 1 - i][n - 1 - i] = 1 return grid def test(): test_cases = [n for n in range(3, 40, 4)] for n in test_cases: try: output = solution(n) expected_output = reference(n) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`n`: {n}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`n`: {n}\n\n" f"Actual Output (grid):\n" f"{'\n'.join([str(row) for row in output])}\n\n" f"Expected Output (grid):\n" f"{'\n'.join([str(row) for row in expected_output])}" ) assert False, error_message test()
from typing import List def solution(n: int) -> List[List[int]]: """ Given an n x n grid, determine the coordinates of a specific pattern that is formed on the grid. Parameters: n (int): The dimensions of the grid (which is an n*n 2D matrix). n is always an odd number. Returns: List[List[int]]: A n*n 2D matrix where the coordinates of the black cells are marked with 1 and the rest are marked with 0. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": [ "Concentric Arrangement", "Cross Pattern" ], "Geometric Objects": [ "Square", "Grid" ], "Mathematical Operations": null, "Spatial Transformations": [ "Scaling" ], "Topological Relations": [ "Adjacency", "Boundary" ] }
Expansion
q100
from typing import Tuple import math def solution(coordinate: Tuple[int, int]) -> int: """ Determines the color of the zone at the given coordinate. The colors follow an infinitely repeating pattern. Args: coordinate: A tuple (x, y) representing the coordinate point Returns: 0 for white 1 for black 3 for boarder """ x, y = coordinate sq = math.sqrt(x*x + y*y) if int(sq) == sq: return 3 r_floor = math.floor(sq) if x > 0 and y > 0: quadrant = 1 elif x < 0 and y > 0: quadrant = 2 elif x < 0 and y < 0: quadrant = 3 elif x > 0 and y < 0: quadrant = 4 else: quadrant = 1 if quadrant in [1, 3]: return 1 if (r_floor % 2 == 0) else 0 else: return 0 if (r_floor % 2 == 0) else 1
# Problem Description This is a coordinate-based zone coloring problem where we need to determine the color of a point given its (x,y) coordinates. The plane is divided into alternating black and white circular rings, with special rules for different quadrants. The coloring pattern depends on: 1. The distance from the origin (0,0) 2. Which quadrant the point lies in 3. Whether the point lies on a border # Visual Facts 1. Coordinate System: - X-axis ranges from -5 to 5 (visible portion) - Y-axis ranges from -5 to 5 (visible portion) - Grid is marked in unit intervals 2. Sample Points Given: - (-1, 1): Black zone - (3, 2): White zone - (0.5, -0.5): White zone - (20, -16): Black zone - (-3, -4): Border 3. Visual Structure: - Concentric circles centered at origin (0,0) - Circles are spaced at unit intervals - Pattern alternates between black and white rings # Visual Patterns 1. Distance-Based Rules: - Each ring represents a unit distance from the origin - The pattern alternates at every integer distance 2. Quadrant-Specific Rules: - Quadrants I & III: * Even distance → Black * Odd distance → White - Quadrants II & IV: * Even distance → White * Odd distance → Black 3. Border Detection: - Points exactly on integer distances from origin are borders - Border points return value 3 4. Mathematical Patterns: - Color determination requires: * Calculating distance from origin: √(x² + y²) * Determining quadrant: sign(x) and sign(y) * Checking if point is on border * Applying quadrant-specific even/odd rules using the lower bound of distance
def test(): test_cases = [ ((0.5, 0.5), 1), ((0.5, -0.5),0), ((3, 2), 0), ((-1, 1), 1), ((5, -3), 1), ((5, -4), 0), ((2, 2), 1), ((4, 3), 3), ((7, 7), 0), ((23009853, 23009853), 1), ((-23009853, -23009853), 1), ((992384, 223), 1) ] for i, (coordinate, expected_output) in enumerate(test_cases, 1): try: output = solution(coordinate) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`coordinate`: {coordinate}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`coordinate`: {coordinate}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import Tuple import math def solution(coordinate: Tuple[int, int]) -> int: """ Determines the color of the zone at the given coordinate. The colors follow an infinitely repeating pattern. Args: coordinate: A tuple (x, y) representing the coordinate point Returns: 0 for white 1 for black 3 for boarder """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": [ "Alternation", "Concentric Arrangement" ], "Geometric Objects": [ "Point", "Circle", "Distance", "Radius", "Coordinate System" ], "Mathematical Operations": [ "Value Comparison" ], "Spatial Transformations": null, "Topological Relations": [ "Nesting", "Boundary" ] }
Validation
q100-2
from typing import Tuple import math def solution(coordinate: Tuple[int, int]) -> int: """ Determines the color of the zone at the given coordinate. The colors follow an infinitely repeating pattern. Args: coordinate: A tuple (x, y) representing the coordinate point Returns: 0 for white 1 for black 3 for boarder """ x, y = coordinate sq = math.sqrt(x*x + y*y) if int(sq) == sq: return 3 r_floor = math.floor(sq) if x > 0 and y > 0: quadrant = 1 elif x < 0 and y > 0: quadrant = 2 elif x < 0 and y < 0: quadrant = 3 elif x > 0 and y < 0: quadrant = 4 else: quadrant = 1 if quadrant in [1, 3]: return 0 if (r_floor % 2 == 0) else 1 else: return 1 if (r_floor % 2 == 0) else 0
# Problem Description This is a coordinate-based zone coloring problem where we need to determine the color of a point given its (x,y) coordinates. The plane is divided into alternating black and white circular rings, with special rules for different quadrants. The coloring pattern depends on: 1. The distance from the origin (0,0) 2. Which quadrant the point lies in 3. Whether the point lies on a border # Visual Facts 1. Coordinate System: - X-axis ranges from -5 to 5 (visible portion) - Y-axis ranges from -5 to 5 (visible portion) - Grid is marked in unit intervals 2. Sample Points Given: - (-1, 1): White zone - (3, 2): Black zone - (0.5, -0.5): Black zone - (20, -16): White zone - (-3, -4): Border 3. Visual Structure: - Concentric circles centered at origin (0,0) - Circles are spaced at unit intervals - Pattern alternates between black and white rings # Visual Patterns 1. Distance-Based Rules: - Each ring represents a unit distance from the origin - The pattern alternates at every integer distance 2. Quadrant-Specific Rules: - Quadrants I & III: * Even distance → White * Odd distance → Black - Quadrants II & IV: * Even distance → Black * Odd distance → White 3. Border Detection: - Points exactly on integer distances from origin are borders - Border points return value 3 4. Mathematical Patterns: - Color determination requires: * Calculating distance from origin: √(x² + y²) * Determining quadrant: sign(x) and sign(y) * Checking if point is on border * Applying quadrant-specific even/odd rules using the lower bound of distance
def test(): test_cases = [ ((0.5, 0.5), 0), ((0.5, -0.5),1), ((3, 2), 1), ((-1, 1), 0), ((5, -3), 0), ((5, -4), 1), ((2, 2), 0), ((4, 3), 3), ((7, 7), 1), ((23009853, 23009853), 0), ((-23009853, -23009853), 0), ((992384, 223), 0) ] for i, (coordinate, expected_output) in enumerate(test_cases, 1): try: output = solution(coordinate) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`coordinate`: {coordinate}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`coordinate`: {coordinate}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import Tuple import math def solution(coordinate: Tuple[int, int]) -> int: """ Determines the color of the zone at the given coordinate. The colors follow an infinitely repeating pattern. Args: coordinate: A tuple (x, y) representing the coordinate point Returns: 0 for white 1 for black 3 for boarder """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": [ "Alternation", "Concentric Arrangement" ], "Geometric Objects": [ "Point", "Circle", "Distance", "Radius", "Coordinate System" ], "Mathematical Operations": [ "Value Comparison" ], "Spatial Transformations": null, "Topological Relations": [ "Nesting", "Boundary" ] }
Validation
q100-3
from typing import Tuple import math def solution(coordinate: Tuple[int, int]) -> int: """ Determines the color of the zone at the given coordinate. The colors follow an infinitely repeating pattern. Args: coordinate: A tuple (x, y) representing the coordinate point Returns: 0 for white 1 for black 3 for boarder """ x, y = coordinate sq = math.sqrt(x*x + y*y) if int(sq) == sq: return 3 r_floor = math.floor(sq) if x > 0 and y > 0: quadrant = 1 elif x < 0 and y > 0: quadrant = 2 elif x < 0 and y < 0: quadrant = 3 elif x > 0 and y < 0: quadrant = 4 else: quadrant = 1 if quadrant in [1, 3]: return 0 if (r_floor % 2 == 0) else 1 else: return 1 if (r_floor % 2 == 0) else 0
# Problem Description This is a coordinate-based zone coloring problem where we need to determine the color of a point given its (x,y) coordinates. The plane is divided into alternating black and white circular rings, with special rules. The coloring pattern depends on: 1. The distance from the origin (0,0) 2. Whether the point lies on a border # Visual Facts 1. Coordinate System: - X-axis ranges from 0 to 5 (visible portion) - Y-axis ranges from 0 to 5 (visible portion) - Grid is marked in unit intervals 2. Sample Points Given: - (1, 2): White zone - (3, 2): Black zone - (0.5, 0.5): White zone - (5, 2): Black zone - (2, 0): Border 3. Visual Structure: - Concentric circles centered at origin (0,0) - Circles are spaced at unit intervals - Pattern alternates between black and white rings # Visual Patterns 1. Distance-Based Rules: - Each ring represents a unit distance from the origin - The pattern alternates at every integer distance 2. Specific Rules: * Even distance → White * Odd distance → Black 3. Border Detection: - Points exactly on integer distances from origin are borders - Border points return value 3 4. Mathematical Patterns: - Color determination requires: * Calculating distance from origin: √(x² + y²) * Checking if point is on border * Applying quadrant-specific even/odd rules using the lower bound of distance
def test(): test_cases = [ ((0.5, 0.5), 0), ((0.5, 1.5),1), ((3, 2), 1), ((1, 1), 1), ((5, 3), 1), ((5, 4), 0), ((2, 2), 0), ((4, 3), 3), ((7, 7), 1), ((23009853, 23009853), 0), ((23009853, 23009853), 0), ((992384, 223), 0) ] for i, (coordinate, expected_output) in enumerate(test_cases, 1): try: output = solution(coordinate) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`coordinate`: {coordinate}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`coordinate`: {coordinate}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import Tuple import math def solution(coordinate: Tuple[int, int]) -> int: """ Determines the color of the zone at the given coordinate. The colors follow an infinitely repeating pattern. Args: coordinate: A tuple (x, y) representing the coordinate point Returns: 0 for white 1 for black 3 for boarder """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": [ "Alternation", "Concentric Arrangement" ], "Geometric Objects": [ "Point", "Circle", "Distance", "Radius", "Coordinate System" ], "Mathematical Operations": [ "Value Comparison" ], "Spatial Transformations": null, "Topological Relations": [ "Nesting", "Boundary" ] }
Validation
q11
from typing import Tuple def layer(x: int, y: int) -> int: """ Determine the layer of a point based on its coordinates. Parameters: x (int): The x-coordinate of the point. y (int): The y-coordinate of the point. Returns: int: The layer of the point. """ return max(x, y) def solution(point1: Tuple[int, int], point2: Tuple[int, int]) -> str: """ Determine the relationship between two points based on their layers. Parameters: point1 (Tuple[int, int]): The coordinates of the first point, where both x and y are non-negative integers. point2 (Tuple[int, int]): The coordinates of the second point, where both x and y are non-negative integers. Returns: str: Return 'A', 'B'. 'C'. """ x1, y1 = point1 x2, y2 = point2 layer1 = layer(x1, y1) layer2 = layer(x2, y2) if layer1 == layer2: return 'A' if abs(layer1 - layer2) == 1: return 'B' return 'C'
# Problem Description This is a point relationship classification problem in a layered grid system. Given two points in a coordinate system, we need to determine their relationship, which falls into one of three categories (A, B, or C) based on their relative layer positions. The layers are organized as concentric squares expanding outward from the origin, where each layer N forms a square with side length N. # Visual Facts 1. The coordinate system has both x and y axes starting from 0 2. Points are organized in layers (L0 to L4 shown) 3. Three types of relationships are illustrated: - "A": Same Layer (orange arrows) - "B": Adjacent Layer (green arrows) - "C": Non-Adjacent Layer (red arrows) 4. Layer 0 is a single point at the origin (0,0) 5. Each subsequent layer forms a square perimeter 6. Points only exist at integer coordinates 7. The maximum layer shown is L4 8. Each layer N forms a square of side length N # Visual Patterns 1. Layer Determination Pattern: - A point's layer number is determined by the maximum of its x and y coordinates - For any point (x,y), its layer = max(abs(x), abs(y)) 2. Relationship Classification Rules: - "A": Points are on the same layer Example: Two points both on L4 - "B": Points are on consecutive layers Example: Point on L2 connected to point on L3 - "C": Points are separated by at least one layer Example: Point on L1 connected to point on L3
def test(): test_cases = [ ((2, 0), (2, 1), 'A'), ((0, 0), (4, 0), 'C'), ((1, 0), (2, 0), 'B'), ((0, 0), (0, 0), 'A'), ((3, 10), (4, 4), 'C'), ((5, 6), (7, 4), 'B'), ((9, 9), (9, 10), 'B'), ((999, 1002), (1000, 1000), 'C'), ((0, 0), (0, 1), 'B'), ((0, 0), (1, 0), 'B') ] for point1, point2, expected_output in test_cases: try: output = solution(point1, point2) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`point1`: {point1}\n" f"`point2`: {point2}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`point1`: {point1}\n" f"`point2`: {point2}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import Tuple def solution(point1: Tuple[int, int], point2: Tuple[int, int]) -> str: """ Determine the relationship between two points based on their layers. Parameters: point1 (Tuple[int, int]): The coordinates of the first point, where both x and y are non-negative integers. point2 (Tuple[int, int]): The coordinates of the second point, where both x and y are non-negative integers. Returns: str: Return 'A', 'B'. 'C'. """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": [ "Linear Increment", "Concentric Arrangement", "Layered Structure" ], "Geometric Objects": [ "Line", "Arrow", "Point", "Coordinate System", "Grid" ], "Mathematical Operations": [ "Value Comparison" ], "Spatial Transformations": null, "Topological Relations": [ "Adjacency", "Connection", "Connectivity" ] }
Validation
q11-2
from typing import Tuple def solution(point1: Tuple[int, int], point2: Tuple[int, int]) -> str: """ Determine the relationship between two points based on their layers. Parameters: point1 (Tuple[int, int]): The coordinates of the first point, where both x and y are non-negative integers. point2 (Tuple[int, int]): The coordinates of the second point, where both x and y are non-negative integers. Returns: str: Return 'A', 'B', or 'C'. """ layer1 = point1[0] + point1[1] layer2 = point2[0] + point2[1] if layer1 == layer2: return 'A' elif abs(layer1 - layer2) == 1: return 'B' else: return 'C'
# Problem Description This problem involves determining the relationship between two points in a layered coordinate system. The layers are organized in a triangular grid pattern, expanding outward from the origin. Given two points, we need to classify their relationship into one of three categories: "A" (Same Layer), "B" (Adjacent Layer), or "C" (Non-Adjacent Layer). # Visual Facts 1. The coordinate system has both x and y axes starting from 0. 2. Points are organized in layers (L0 to L4 shown). 3. Three types of relationships are illustrated: - "A": Same Layer (orange arrows). - "B": Adjacent Layer (green arrows). - "C": Non-Adjacent Layer (red arrows). 4. Layer 0 is a single point at the origin (0,0). 5. Each subsequent layer forms a diagonal line. 6. Points only exist at integer coordinates. 7. The maximum layer shown is L4. 8. Each layer N forms a diagonal line with points (N, 0) to (0, N). # Visual Patterns 1. **Layer Determination Pattern**: - A point's layer number is determined by the sum of its x and y coordinates. - For any point (x, y), its layer = x + y. 2. **Relationship Classification Rules**: - "A": Points are on the same layer. - Example: Two points both on L4. - "B": Points are on consecutive layers. - Example: Point on L2 connected to point on L3. - "C": Points are separated by at least one layer. - Example: Point on L1 connected to point on L3.
def test(): test_cases = [ ((2, 0), (2, 1), 'B'), ((1, 1), (0, 2), 'A'), ((0, 3), (1, 2), 'A'), ((0, 0), (4, 0), 'C'), ((1, 0), (2, 0), 'B'), ((0, 0), (0, 0), 'A'), ((3, 10), (4, 4), 'C'), ((5, 6), (7, 4), 'A'), ((9, 9), (9, 10), 'B'), ((999, 1002), (1000, 1000), 'B'), ((0, 0), (0, 1), 'B'), ((0, 0), (1, 0), 'B') ] for point1, point2, expected_output in test_cases: try: output = solution(point1, point2) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`point1`: {point1}\n" f"`point2`: {point2}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`point1`: {point1}\n" f"`point2`: {point2}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import Tuple def solution(point1: Tuple[int, int], point2: Tuple[int, int]) -> str: """ Determine the relationship between two points based on their layers. Parameters: point1 (Tuple[int, int]): The coordinates of the first point, where both x and y are non-negative integers. point2 (Tuple[int, int]): The coordinates of the second point, where both x and y are non-negative integers. Returns: str: Return 'A', 'B'. 'C'. """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": [ "Linear Increment", "Concentric Arrangement", "Layered Structure" ], "Geometric Objects": [ "Line", "Arrow", "Point", "Coordinate System", "Grid" ], "Mathematical Operations": [ "Value Comparison" ], "Spatial Transformations": null, "Topological Relations": [ "Adjacency", "Connection", "Connectivity" ] }
Validation
q11-3
from typing import Tuple def layer(x: int, y: int) -> int: """ Determine the layer of a point based on its coordinates. Parameters: x (int): The x-coordinate of the point. y (int): The y-coordinate of the point. Returns: int: The layer of the point. """ return min(x, y) def solution(point1: Tuple[int, int], point2: Tuple[int, int]) -> str: """ Determine the relationship between two points based on their layers. Parameters: point1 (Tuple[int, int]): The coordinates of the first point, where both x and y are non-negative integers. point2 (Tuple[int, int]): The coordinates of the second point, where both x and y are non-negative integers. Returns: str: Return 'A', 'B'. 'C'. """ x1, y1 = point1 x2, y2 = point2 layer1 = layer(x1, y1) layer2 = layer(x2, y2) if layer1 == layer2: return 'A' if abs(layer1 - layer2) == 1: return 'B' return 'C'
# Problem Description This problem involves determining the relationship between two points on a coordinate grid based on their respective layers. The grid is divided into layers, with each layer forming a square perimeter around the origin. The relationship between the points can be one of three types: - "A": Points are on the same layer. - "B": Points are on adjacent layers. - "C": Points are on non-adjacent layers. Given two points, the task is to determine which of these three relationships they fall into. # Visual Facts 1. The coordinate system has both x and y axes starting from 0. 2. Points are organized into layers labeled L0, L1, L2, L3, etc. 3. Three types of relationships are illustrated: - "A": Same Layer (orange arrows) - "B": Adjacent Layer (green arrows) - "C": Non-Adjacent Layer (red arrows) 4. Layer 0 (L0) includes points where either x or y is 0. 5. Layer 1 (L1) includes points where either x or y is 1. 6. Layer 2 (L2) includes points where either x or y is 2. 7. Layer 3 (L3) includes points where either x or y is 3. 8. Each layer forms a square perimeter around the origin. 9. The maximum layer shown is L3. 10. Points only exist at integer coordinates. # Visual Patterns 1. **Layer Determination Pattern**: - A point's layer number is determined by the minimum of its x and y coordinates. - For any point (x, y), its layer = min(x, y). 2. **Relationship Classification Rules**: - "A": Points are on the same layer. - Example: Two points both on L3. - "B": Points are on consecutive layers. - Example: One point on L2 and another on L3. - "C": Points are separated by at least one layer. - Example: One point on L1 and another on L3.
def test(): test_cases = [ ((2, 0), (2, 1), 'B'), ((0, 0), (4, 0), 'A'), ((1, 0), (2, 0), 'A'), ((0, 0), (0, 0), 'A'), ((3, 10), (4, 4), 'B'), ((5, 6), (7, 4), 'B'), ((9, 9), (9, 10), 'A'), ((999, 1002), (1000, 1000), 'B'), ((0, 0), (0, 1), 'A'), ((0, 0), (1, 0), 'A'), ((0, 0), (2, 2), 'C'), ((7, 4), (7, 2), 'C'), ((9, 2), (4, 8), 'C') ] for point1, point2, expected_output in test_cases: try: output = solution(point1, point2) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`point1`: {point1}\n" f"`point2`: {point2}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`point1`: {point1}\n" f"`point2`: {point2}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import Tuple def solution(point1: Tuple[int, int], point2: Tuple[int, int]) -> str: """ Determine the relationship between two points based on their layers. Parameters: point1 (Tuple[int, int]): The coordinates of the first point, where both x and y are non-negative integers. point2 (Tuple[int, int]): The coordinates of the second point, where both x and y are non-negative integers. Returns: str: Return 'A', 'B'. 'C'. """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": [ "Linear Increment", "Concentric Arrangement", "Layered Structure" ], "Geometric Objects": [ "Line", "Arrow", "Point", "Coordinate System", "Grid" ], "Mathematical Operations": [ "Value Comparison" ], "Spatial Transformations": null, "Topological Relations": [ "Adjacency", "Connection", "Connectivity" ] }
Validation
q12
from typing import List def solution(input_matrix: List[List[str]]) -> List[List[str]]: """ Transform the input matrix based on the pattern shown in the figure Parameters: input_matrix (List[List[str]]): Input matrix as a 2d array. Returns: output_matrix (List[List[str]]): Output matrix as a 2d array. """ # To rotate 180 degrees, we can reverse the rows and then reverse each row # Or reverse each row and then reverse the rows - both work rows = len(input_matrix) cols = len(input_matrix[0]) # Create a new matrix to store the result new_matrix = [] for i in range(rows-1, -1, -1): new_row = [] for j in range(cols-1, -1, -1): new_row.append(input_matrix[i][j]) new_matrix.append(new_row) return new_matrix
# Problem Description The problem requires implementing a matrix transformation function that takes a NxN input matrix and produces a NxN output matrix following specific rotation patterns. The transformation appears to involve both repositioning and rearranging elements in a systematic way. # Visual Facts 1. Matrix Dimensions: - Both input and output matrices are 4x4 - Two example pairs are shown - A green arrow indicates a rotation transformation from input to output 2. First Example Contents: - Input Matrix Row 1: A, B, C, D - Input Matrix Row 2: +, -, *, / - Input Matrix Row 3: D, C, B, A - Input Matrix Row 4: /, *, -, + - Output Matrix Column 1: +, -, *, / - Output Matrix Column 2: A, B, C, D - Output Matrix Column 3: /, *, -, + - Output Matrix Column 4: D, C, B, A 3. Second Example Contents: - Input Matrix Row 1: 4, @, 1, 8 - Input Matrix Row 2: #, a, Q, E - Input Matrix Row 3: 9, ?, 6, & - Input Matrix Row 4: b, $, F, t - Output Matrix Column 1: t, F, $, b - Output Matrix Column 2: &, 6, ?, 9 - Output Matrix Column 3: E, Q, a, # - Output Matrix Column 4: 8, 1, @, 4 # Visual Patterns - The input matrix is rotated 180 degrees clockwise to produce the output matrix
def test(): test_cases = [ [['1', '2', '3'], ['4', '#', '6'], ['D', '8', 'a']], [['1', 'a'], ['3', '#']], [['4', '@', '1', '8'], ['#', 'a', 'Q', '&'], ['9', '?', '&', '%'], ['b', '$', 'F', 't']], [['6', '@', '2', '1'], ['9', '#', 'Q', '1'], ['9', '4', '5', '4'], ['1', '1', '1', '1']], [['4', '2'], ['6', '9']], [['7', '8', '9'], ['+', '#', '_'], [')', '8', '$']], [['6', '@', '2', '1', '&'], ['9', '#', 'Q', '1', '@'], ['9', '4', '5', '4', '!'], ['1', '1', '1', '1', '?'], ['(', ')', '#', '%', '5']], [['6', '@', '2', '1', '&', ']'], ['9', '#', 'Q', '1', '@', '['], ['9', '4', '5', '4', '!', '='], ['1', '1', '1', '1', '?', '9'], ['(', ')', '#', '%', '5', '4'], ['(', '6', '#', '4', '5', '-']], [['!', '2', '$'], ['6', '!', '9'], ['+', '!', '-']], [['1', '1', '1'], ['2', '2', '2'], ['3', '3', '3']], ] for i, input_matrix in enumerate(test_cases): # Create deep copy of input matrix original_input_matrix = [row[:] for row in input_matrix] try: result = solution(input_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`input_matrix`: {original_input_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message # Create expected result by rotating 180 degrees expected = [] rows = len(original_input_matrix) cols = len(original_input_matrix[0]) for i in range(rows-1, -1, -1): new_row = [] for j in range(cols-1, -1, -1): new_row.append(original_input_matrix[i][j]) expected.append(new_row) if result != expected: error_message = ( f"The following Test Case failed:\n" f"`input_matrix`: {original_input_matrix}\n\n" f"Actual Output: {result}\n" f"Expected Output: {expected}" ) assert False, error_message test()
from typing import List def solution(input_matrix: List[List[str]]) -> List[List[str]]: """ Transform the input matrix based on the pattern shown in the figure Parameters: input_matrix (List[List[str]]): Input matrix as a 2d array. Returns: output_matrix (List[List[str]]): Output matrix as a 2d array. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": null, "Geometric Objects": [ "Line", "Grid", "Arrow" ], "Mathematical Operations": null, "Spatial Transformations": [ "Rotation" ], "Topological Relations": [ "Boundary", "Adjacency" ] }
Transformation
q12-2
from typing import List def solution(input_matrix: List[List[str]]) -> List[List[str]]: """ Transform the input matrix based on the pattern shown in the figure Parameters: input_matrix (List[List[str]]): Input matrix as a 2d array. Returns: output_matrix (List[List[str]]): Output matrix as a 2d array. """ new_matrix = [row[::-1] for row in input_matrix] return new_matrix
# Problem Description The problem requires implementing a matrix transformation function that takes a NxN input matrix and produces a NxN output matrix. The transformation appears to be a reflection or mirroring operation around a vertical axis that runs through the center of the matrix. # Visual Facts 1. Matrix Properties: - Both input and output matrices are 4x4 - Two example cases are shown - A green dotted line marks the vertical axis in the middle of input matrices - Black arrows show the transformation from input to output 2. First Example: - Input Matrix rows: * [A, B, C, D] * [+, -, *, /] * [D, C, B, A] * [/, *, -, +] - Output Matrix rows: * [D, C, B, A] * [/, *, -, +] * [A, B, C, D] * [+, -, *, /] 3. Second Example: - Input Matrix rows: * [4, @, 1, 8] * [#, a, Q, E] * [9, ?, 6, &] * [b, $, F, t] - Output Matrix rows: * [8, 1, @, 4] * [E, Q, a, #] * [&, 6, ?, 9] * [t, F, $, b] # Visual Patterns 1. Transformation Rules: - The matrix is reflected across the vertical line between columns 2 and 3 - Each row in the input matrix becomes flipped horizontally in the output matrix - The relative positions of characters within each row remain in the same row, just reversed 2. Mathematical Properties: - For any element at position (i,j) in the input matrix, its new position in the output matrix is (i, n-1-j) where n is the matrix size (4) 3. Invariant Properties: - Matrix dimensions remain unchanged (4x4) - Content of the matrix remains the same, only positions change - The transformation applies consistently regardless of the type of characters (letters, numbers, or symbols)
def test(): test_cases = [ [['1', '2', '3'], ['4', '#', '6'], ['D', '8', 'a']], [['1', 'a'], ['3', '#']], [['4', '@', '1', '8'], ['#', 'a', 'Q', '&'], ['9', '?', '&', '%'], ['b', '$', 'F', 't']], [['6', '@', '2', '1'], ['9', '#', 'Q', '1'], ['9', '4', '5', '4'], ['1', '1', '1', '1']], [['4', '2'], ['6', '9']], [['7', '8', '9'], ['+', '#', '_'], [')', '8', '$']], [['6', '@', '2', '1', '&'], ['9', '#', 'Q', '1', '@'], ['9', '4', '5', '4', '!'], ['1', '1', '1', '1', '?'], ['(', ')', '#', '%', '5']], [['6', '@', '2', '1', '&', ']'], ['9', '#', 'Q', '1', '@', '['], ['9', '4', '5', '4', '!', '='], ['1', '1', '1', '1', '?', '9'], ['(', ')', '#', '%', '5', '4'], ['(', '6', '#', '4', '5', '-']], [['!', '2', '$'], ['6', '!', '9'], ['+', '!', '-']], [['1', '1', '1'], ['2', '2', '2'], ['3', '3', '3']], ] for i, input_matrix in enumerate(test_cases): # Create deep copy of input matrix original_input_matrix = [row[:] for row in input_matrix] try: output = solution(input_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`input_matrix`: {original_input_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message # Create expected result by reversing each row expected_output = [row[::-1] for row in original_input_matrix] if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`input_matrix`: {original_input_matrix}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(input_matrix: List[List[str]]) -> List[List[str]]: """ Transform the input matrix based on the pattern shown in the figure Parameters: input_matrix (List[List[str]]): Input matrix as a 2d array. Returns: output_matrix (List[List[str]]): Output matrix as a 2d array. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": [ "Mirror Symmetry", "Mirror Reflection" ], "Geometric Objects": [ "Line", "Grid", "Arrow" ], "Mathematical Operations": null, "Spatial Transformations": [ "Rotation", "Flipping" ], "Topological Relations": [ "Boundary", "Adjacency" ] }
Transformation
q12-3
from typing import List def solution(input_matrix: List[List[str]]) -> List[List[str]]: """ Transform the input matrix based on the pattern shown in the figure Parameters: input_matrix (List[List[str]]): Input matrix as a 2d array. Returns: output_matrix (List[List[str]]): Output matrix as a 2d array. """ new_matrix = input_matrix[::-1] return new_matrix
Let me analyze your problem: # Problem Description The problem requires implementing a matrix transformation function that takes a NxN input matrix and produces a NxN output matrix. The transformation appears to be a horizontal flip or reflection around a horizontal axis that runs through the middle of the matrix. # Visual Facts 1. Matrix Properties: - Both input and output matrices are 4x4 - Two example cases are shown - A green curved arrow indicates horizontal flipping - Black arrows show the transformation direction 2. First Example: - Input Matrix rows: * [A, B, C, D] * [+, -, *, /] * [D, C, B, A] * [/, *, -, +] - Output Matrix rows: * [/, *, -, +] * [D, C, B, A] * [+, -, *, /] * [A, B, C, D] 3. Second Example: - Input Matrix rows: * [4, @, 1, 8] * [#, a, Q, E] * [9, ?, 6, &] * [b, $, F, t] - Output Matrix rows: * [b, $, F, t] * [9, ?, 6, &] * [#, a, Q, E] * [4, @, 1, 8] # Visual Patterns 1. Transformation Rules: - The matrix is flipped vertically (upside down) - Each row maintains its elements in the same order - Rows swap positions: first↔last, second↔third 2. Mathematical Properties: - For any element at position (i,j) in the input matrix, its new position in the output matrix is (n-1-i, j) where n is the matrix size (4) - The transformation applies consistently regardless of the character type (letters, numbers, or symbols)
def test(): test_cases = [ [['1', '2', '3'], ['4', '#', '6'], ['D', '8', 'a']], [['1', 'a'], ['3', '#']], [['4', '@', '1', '8'], ['#', 'a', 'Q', '&'], ['9', '?', '&', '%'], ['b', '$', 'F', 't']], [['6', '@', '2', '1'], ['9', '#', 'Q', '1'], ['9', '4', '5', '4'], ['1', '1', '1', '1']], [['4', '2'], ['6', '9']], [['7', '8', '9'], ['+', '#', '_'], [')', '8', '$']], [['6', '@', '2', '1', '&'], ['9', '#', 'Q', '1', '@'], ['9', '4', '5', '4', '!'], ['1', '1', '1', '1', '?'], ['(', ')', '#', '%', '5']], [['6', '@', '2', '1', '&', ']'], ['9', '#', 'Q', '1', '@', '['], ['9', '4', '5', '4', '!', '='], ['1', '1', '1', '1', '?', '9'], ['(', ')', '#', '%', '5', '4'], ['(', '6', '#', '4', '5', '-']], [['!', '2', '$'], ['6', '!', '9'], ['+', '!', '-']], [['1', '1', '1'], ['2', '2', '2'], ['3', '3', '3']], ] for i, input_matrix in enumerate(test_cases): # Create deep copy of input matrix original_input_matrix = [row[:] for row in input_matrix] try: output = solution(input_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`input_matrix`: {original_input_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message # Create expected result by reversing the rows order expected_output = original_input_matrix[::-1] if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`input_matrix`: {original_input_matrix}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(input_matrix: List[List[str]]) -> List[List[str]]: """ Transform the input matrix based on the pattern shown in the figure Parameters: input_matrix (List[List[str]]): Input matrix as a 2d array. Returns: output_matrix (List[List[str]]): Output matrix as a 2d array. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": [ "Mirror Symmetry", "Mirror Reflection" ], "Geometric Objects": [ "Line", "Grid", "Arrow" ], "Mathematical Operations": null, "Spatial Transformations": [ "Rotation", "Flipping" ], "Topological Relations": [ "Boundary", "Adjacency" ] }
Transformation
q13
import heapq def solution(nodes: dict, edges: list, start: str, end: str) -> int: """ Given the nodes and edges of a graph, determine the minimum path cost from a given starting node to an ending node. Please observe the example graph in the image to deduce the pattern calculating the path cost between two nodes. Input: - nodes: A dictionary where each key represents a node, and its associated value is the node's value. Example: {'A': 10, 'B': 20} indicates that node A has a value of 10, and node B has a value of 20. - edges: A list of tuples, each containing two nodes that are directly connected. Example: [('A', 'B'), ('B', 'C')] means node A is connected to node B, and node B is connected to node C. - start: The starting node where the path begins. - end: The ending node where the path terminates. Output: - Return the minimum cost required to travel from the start node to the end node. Return -1 if no path exists. """ graph = {node: {} for node in nodes} for node1, node2 in edges: if node1 in graph and node2 in graph: graph[node1][node2] = abs(nodes[node1]) + abs(nodes[node2]) graph[node2][node1] = abs(nodes[node1]) + abs(nodes[node2]) pq = [(0, start)] visited = set() min_cost = {node: float('inf') for node in nodes} min_cost[start] = 0 while pq: current_cost, current_node = heapq.heappop(pq) if current_node in visited: continue visited.add(current_node) if current_node == end: return current_cost for neighbor, weight in graph[current_node].items(): if neighbor not in visited: new_cost = current_cost + weight if new_cost < min_cost[neighbor]: min_cost[neighbor] = new_cost heapq.heappush(pq, (new_cost, neighbor)) return -1
# Problem Description This is a graph pathfinding problem where we need to: - Find the minimum cost path between two given nodes in an undirected weighted graph - Each node has an associated value - Each edge has a cost - The total path cost must follow a specific pattern based on the nodes' values and edge costs - We need to find the optimal (minimum cost) path from start to end node # Visual Facts 1. Graph Structure: - 6 nodes labeled A through F - 5 edges connecting these nodes - Graph is undirected (no arrows on edges) 2. Node Values: - A: 12 - B: 3 - C: -2 - D: -8 - E: -6 - F: 4 3. Edge Costs: - A-B: 15 - B-C: 5 - B-D: 11 - D-E: 14 - D-F: 12 # Visual Patterns Cost Calculation Pattern: Looking at adjacent nodes and their edge costs: - the cost of each edge is the sum of the two nodes' absolute values - for example, the cost of edge A-B is |12| + |3| = 15 - the cost of edge D-E is |-8| + |-6| = 14
def test(): nodes = {'A': 10, 'B': 3, 'C': -2, 'D': -8, 'E': -6, 'F': 4} connections = [('A', 'B'), ('B', 'C'), ('B', 'D'), ('D', 'E'), ('D', 'F')] pairs = [('A', 'C'), ('B', 'E'), ('A', 'F'), ('A', 'D'), ('A', 'E'), ('B', 'F')] expected_results = [18, 25, 36, 24, 38, 23] for index, (start, end) in enumerate(pairs): try: output = solution(nodes, connections, start, end) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`nodes`: {nodes}\n" f"`connections`: {connections}\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_results[index]: error_message = ( f"The following Test Case failed:\n" f"`nodes`: {nodes}\n" f"`connections`: {connections}\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_results[index]}" ) assert False, error_message nodes = {'A': 1, 'B': -2, 'C': 3, 'D': -4, 'E': 5, 'F': -6} connections = [('A', 'D'), ('D', 'E'), ('E', 'F'), ('E', 'B'), ('F', 'C'), ('D', 'B')] pairs = [('A', 'C'), ('B', 'E'), ('A', 'F'), ('C', 'D'), ('A', 'B')] expected_results = [34, 7, 25, 29, 11] for index, (start, end) in enumerate(pairs): try: output = solution(nodes, connections, start, end) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`nodes`: {nodes}\n" f"`connections`: {connections}\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_results[index]: error_message = ( f"The following Test Case failed:\n" f"`nodes`: {nodes}\n" f"`connections`: {connections}\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_results[index]}" ) assert False, error_message test()
def solution(nodes: dict, edges: list, start: str, end: str) -> int: """ Given the nodes and edges of a graph, determine the minimum path cost from a given starting node to an ending node. Please observe the example graph in the image to deduce the pattern calculating the path cost between two nodes. Input: - nodes: A dictionary where each key represents a node, and its associated value is the node's value. Example: {'A': 10, 'B': 20} indicates that node A has a value of 10, and node B has a value of 20. - edges: A list of tuples, each containing two nodes that are directly connected. Example: [('A', 'B'), ('B', 'C')] means node A is connected to node B, and node B is connected to node C. - start: The starting node where the path begins. - end: The ending node where the path terminates. Output: - Return the minimum cost required to travel from the start node to the end node """
{ "Common Sense": null, "Data Structures": [ "Undirected Graph", "Path" ], "Dynamic Patterns": null, "Geometric Objects": null, "Mathematical Operations": [ "Absolute Value", "Basic Arithmetic" ], "Spatial Transformations": null, "Topological Relations": [ "Adjacency", "Connection", "Connectivity" ] }
Direct Calculation
q13-2
import heapq def solution(nodes: dict, edges: list, start: str, end: str) -> int: """ Given the nodes and edges of a graph, determine the minimum path cost from a given starting node to an ending node. Please observe the example graph in the image to deduce the pattern calculating the path cost between two nodes. Input: - nodes: A dictionary where each key represents a node, and its associated value is the node's value. Example: {'A': 10, 'B': 20} indicates that node A has a value of 10, and node B has a value of 20. - edges: A list of tuples, each containing two nodes that are directly connected. Example: [('A', 'B'), ('B', 'C')] means node A is connected to node B, and node B is connected to node C. - start: The starting node where the path begins. - end: The ending node where the path terminates. Output: - Return the minimum cost required to travel from the start node to the end node. Return -1 if no path exists. """ graph = {node: {} for node in nodes} for node1, node2 in edges: if node1 in graph and node2 in graph: graph[node1][node2] = abs(nodes[node1]) * abs(nodes[node2]) graph[node2][node1] = abs(nodes[node1]) * abs(nodes[node2]) pq = [(0, start)] visited = set() min_cost = {node: float('inf') for node in nodes} min_cost[start] = 0 while pq: current_cost, current_node = heapq.heappop(pq) if current_node in visited: continue visited.add(current_node) if current_node == end: return current_cost for neighbor, weight in graph[current_node].items(): if neighbor not in visited: new_cost = current_cost + weight if new_cost < min_cost[neighbor]: min_cost[neighbor] = new_cost heapq.heappush(pq, (new_cost, neighbor)) return -1
# Problem Description This problem involves finding the minimum cost path between two nodes in an undirected weighted graph. Each node has an associated value, and each edge has a cost. The goal is to determine the minimum cost required to travel from a given starting node to an ending node, following a specific pattern for calculating the path cost based on the nodes' values and edge costs. # Visual Facts 1. **Graph Structure**: - The graph consists of 6 nodes labeled A through F. - There are 5 edges connecting these nodes. - The graph is undirected (no arrows on edges). 2. **Node Values**: - Node A has a value of 12. - Node B has a value of 3. - Node C has a value of -2. - Node D has a value of -8. - Node E has a value of -6. - Node F has a value of 4. 3. **Edge Costs**: - The edge between A and B has a cost of 36. - The edge between B and C has a cost of 6. - The edge between B and D has a cost of 24. - The edge between D and E has a cost of 48. - The edge between D and F has a cost of 32. # Visual Patterns 1. **Cost Calculation Pattern**: - The cost of each edge appears to be the product of the absolute values of the two nodes it connects. - For example: - The cost of edge A-B is |12| * |3| = 36. - The cost of edge B-C is |3| * |-2| = 6. - The cost of edge B-D is |3| * |-8| = 24. - The cost of edge D-E is |-8| * |-6| = 48. - The cost of edge D-F is |-8| * |4| = 32. 2. **Graph Connectivity**: - Node A is connected to Node B. - Node B is connected to Nodes A, C, and D. - Node C is connected to Node B. - Node D is connected to Nodes B, E, and F. - Node E is connected to Node D. - Node F is connected to Node D.
def test(): nodes = {'A': 10, 'B': 3, 'C': -2, 'D': -8, 'E': -6, 'F': 4} connections = [('A', 'B'), ('B', 'C'), ('B', 'D'), ('D', 'E'), ('D', 'F')] pairs = [('A', 'C'), ('B', 'E'), ('A', 'F'), ('A', 'D'), ('A', 'E'), ('B', 'F')] expected_results = [36, 72, 86, 54, 102, 56] for index, (start, end) in enumerate(pairs): try: output = solution(nodes, connections, start, end) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`nodes`: {nodes}\n" f"`edges`: {connections}\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_results[index]: error_message = ( f"The following Test Case failed:\n" f"`nodes`: {nodes}\n" f"`edges`: {connections}\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_results[index]}" ) assert False, error_message nodes = {'A': 1, 'B': -2, 'C': 3, 'D': -4, 'E': 5, 'F': -6} connections = [('A', 'D'), ('D', 'E'), ('E', 'F'), ('E', 'B'), ('F', 'C'), ('D', 'B')] pairs = [('A', 'C'), ('B', 'E'), ('A', 'F'), ('C', 'D'), ('A', 'B')] expected_results = [70, 10, 52, 66, 12] for index, (start, end) in enumerate(pairs): try: output = solution(nodes, connections, start, end) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`nodes`: {nodes}\n" f"`edges`: {connections}\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_results[index]: error_message = ( f"The following Test Case failed:\n" f"`nodes`: {nodes}\n" f"`edges`: {connections}\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_results[index]}" ) assert False, error_message test()
def solution(nodes: dict, edges: list, start: str, end: str) -> int: """ Given the nodes and edges of a graph, determine the minimum path cost from a given starting node to an ending node. Please observe the example graph in the image to deduce the pattern calculating the path cost between two nodes. Input: - nodes: A dictionary where each key represents a node, and its associated value is the node's value. Example: {'A': 10, 'B': 20} indicates that node A has a value of 10, and node B has a value of 20. - edges: A list of tuples, each containing two nodes that are directly connected. Example: [('A', 'B'), ('B', 'C')] means node A is connected to node B, and node B is connected to node C. - start: The starting node where the path begins. - end: The ending node where the path terminates. Output: - Return the minimum cost required to travel from the start node to the end node """
{ "Common Sense": null, "Data Structures": [ "Undirected Graph", "Path" ], "Dynamic Patterns": null, "Geometric Objects": null, "Mathematical Operations": [ "Absolute Value", "Basic Arithmetic" ], "Spatial Transformations": null, "Topological Relations": [ "Adjacency", "Connection", "Connectivity" ] }
Direct Calculation
q13-3
import heapq def solution(nodes: dict, edges: list, start: str, end: str) -> int: """ Given the nodes and edges of a graph, determine the minimum path cost from a given starting node to an ending node. Please observe the example graph in the image to deduce the pattern calculating the path cost between two nodes. Input: - nodes: A dictionary where each key represents a node, and its associated value is the node's value. Example: {'A': 10, 'B': 20} indicates that node A has a value of 10, and node B has a value of 20. - edges: A list of tuples, each containing two nodes that are directly connected. Example: [('A', 'B'), ('B', 'C')] means node A is connected to node B, and node B is connected to node C. - start: The starting node where the path begins. - end: The ending node where the path terminates. Output: - Return the minimum cost required to travel from the start node to the end node. Return -1 if no path exists. """ graph = {node: {} for node in nodes} for node1, node2 in edges: if node1 in graph and node2 in graph: graph[node1][node2] = abs(nodes[node1] - nodes[node2]) graph[node2][node1] = abs(nodes[node1] - nodes[node2]) pq = [(0, start)] visited = set() min_cost = {node: float('inf') for node in nodes} min_cost[start] = 0 while pq: current_cost, current_node = heapq.heappop(pq) if current_node in visited: continue visited.add(current_node) if current_node == end: return current_cost for neighbor, weight in graph[current_node].items(): if neighbor not in visited: new_cost = current_cost + weight if new_cost < min_cost[neighbor]: min_cost[neighbor] = new_cost heapq.heappush(pq, (new_cost, neighbor)) return -1
# Problem Description This is a graph pathfinding problem where we need to: - Find the minimum cost path between two given nodes in an undirected weighted graph. - Each node has an associated value. - Each edge has a cost. - The total path cost must follow a specific pattern based on the nodes' values and edge costs. - We need to find the optimal (minimum cost) path from start to end node. # Visual Facts 1. Graph Structure: - 6 nodes labeled A through F. - 5 edges connecting these nodes. - Graph is undirected (no arrows on edges). 2. Node Values: - A: 12 - B: 3 - C: -2 - D: -8 - E: -6 - F: 4 3. Edge Costs: - A-B: 9 - B-C: 5 - B-D: 11 - D-E: 2 - D-F: 12 # Visual Patterns 1. **Cost Calculation Pattern**: - The cost of each edge appears to be the absolute value of the difference between two nodes - For example: - The cost of edge A-B is |12 - 3| = 9. - The cost of edge B-C is |3 - (-2)| = 5. - The cost of edge B-D is |3 - (-8)| = 11. - The cost of edge D-E is |-8 - (-6)| = 2. - The cost of edge D-F is |-8 - 4| = 12.
def test(): nodes = {'A': 10, 'B': 3, 'C': -2, 'D': -8, 'E': -6, 'F': 4} connections = [('A', 'B'), ('B', 'C'), ('B', 'D'), ('D', 'E'), ('D', 'F')] pairs = [('A', 'C'), ('B', 'E'), ('A', 'F'), ('A', 'D'), ('A', 'E'), ('B', 'F')] expected_results = [12, 13, 30, 18, 20, 23] for index, (start, end) in enumerate(pairs): try: output = solution(nodes, connections, start, end) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`nodes`: {nodes}\n" f"`edges`: {connections}\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_results[index]: error_message = ( f"The following Test Case failed:\n" f"`nodes`: {nodes}\n" f"`edges`: {connections}\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_results[index]}" ) assert False, error_message nodes = {'A': 1, 'B': -2, 'C': 3, 'D': -4, 'E': 5, 'F': -6} connections = [('A', 'D'), ('D', 'E'), ('E', 'F'), ('E', 'B'), ('F', 'C'), ('D', 'B')] pairs = [('A', 'C'), ('B', 'E'), ('A', 'F'), ('C', 'D'), ('A', 'B')] expected_results = [34, 7, 25, 29, 7] for index, (start, end) in enumerate(pairs): try: output = solution(nodes, connections, start, end) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`nodes`: {nodes}\n" f"`edges`: {connections}\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_results[index]: error_message = ( f"The following Test Case failed:\n" f"`nodes`: {nodes}\n" f"`edges`: {connections}\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_results[index]}" ) assert False, error_message test()
def solution(nodes: dict, edges: list, start: str, end: str) -> int: """ Given the nodes and edges of a graph, determine the minimum path cost from a given starting node to an ending node. Please observe the example graph in the image to deduce the pattern calculating the path cost between two nodes. Input: - nodes: A dictionary where each key represents a node, and its associated value is the node's value. Example: {'A': 10, 'B': 20} indicates that node A has a value of 10, and node B has a value of 20. - edges: A list of tuples, each containing two nodes that are directly connected. Example: [('A', 'B'), ('B', 'C')] means node A is connected to node B, and node B is connected to node C. - start: The starting node where the path begins. - end: The ending node where the path terminates. Output: - Return the minimum cost required to travel from the start node to the end node """
{ "Common Sense": null, "Data Structures": [ "Undirected Graph", "Path" ], "Dynamic Patterns": null, "Geometric Objects": null, "Mathematical Operations": [ "Basic Arithmetic", "Value Comparison" ], "Spatial Transformations": null, "Topological Relations": [ "Adjacency", "Connection", "Connectivity" ] }
Direct Calculation
q14
def solution(start: tuple[int, int], target: tuple[int, int], direction: tuple[int, int]) -> bool: """ Determines whether the ball can reach the target. Parameters: - start: Tuple[int, int], represents the initial position of the ball (x, y). - target: Tuple[int, int], represents the position of the target. - direction: Tuple[int, int], represents the initial direction of the ball (dx, dy). dx and dy are integers that can be either -1, 0, or 1. Returns: - bool: True if the ball can reach the target, False otherwise. """ x, y = start tx, ty = target dx, dy = direction while True: x += dx y += dy if (x, y) == (tx, ty): return True if x == 0 or x == 10: dx = -dx if y == 0 or y == 10: dy = -dy if (x, y) == start and (dx, dy) == direction: return False
# Problem Description This is a ball trajectory problem where we need to determine if a ball starting from a given position with an initial direction can reach a target position after bouncing off the boundaries of a 10x10 grid. The ball follows the law of reflection (angle of incidence equals angle of reflection) when it hits the boundaries. # Visual Facts 1. The coordinate system is a 10x10 grid (from 0 to 10 on both axes) 2. The grid has clear boundaries at x=0, x=10, y=0, and y=10 3. Start point (green circle) is located around (8, 7) 4. Target point (orange circle) is located around (6, 9) 5. The path is shown with blue dotted lines 6. Blue arrows indicate the direction of movement 7. The path shows multiple bounces off the boundaries 8. The path eventually reaches the target point 9. The path follows straight lines between bounces # Visual Patterns 1. Bouncing Pattern: - When the ball hits a boundary, it reflects with equal angles - The angle of reflection equals the angle of incidence - The ball maintains constant direction between bounces 2. Movement Constraints: - Movement is continuous along straight lines(x += dx,y += dy) - Direction changes only occur at boundaries - The path never passes through the same point with the same direction twice (suggests a termination condition) 3. Geometric Properties: - The trajectory forms a series of connected line segments - Each bounce preserves the angle but reverses one component of the direction vector - For example, if the original direction (dx, dy) is (1, 1), and the x boundary is encountered (x == 0 or x == 10), then dx = -dx, and the new direction becomes (-1, 1). - For example, if the original direction (dx, dy) is (1, 1), and the y boundary is encountered (y == 0 or y == 10), then dy = -dy, and the new direction becomes (1, -1). - The path remains within the 10x10 grid boundaries at all times 4. Solution Pattern: - To reach the target, the ball must follow a valid sequence of bounces - A valid solution exists if there's a path connecting start to target following reflection rules
def test(): test_cases = [ [(8, 7), (6, 9), (1, -1), True], [(8, 7), (6, 10), (1, -1), False], [(8, 7), (9, 6), (1, -1), True], [(0, 0), (1, 1), (1, 0), False], [(0, 0), (2, 2), (1, 1), True], [(0, 0), (0, 1), (0, 1), True], [(2, 1), (6, 10), (-1, -1), False], [(2, 1), (1, 0), (-1, -1), True], [(10, 1), (1, 0), (-1, 1), False], [(10, 1), (9, 2), (-1, 1), True], ] for test_case in test_cases: start, target, direction, expected_output = test_case try: output = solution(start, target, direction) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`start`: {start}\n" f"`target`: {target}\n" f"`direction`: {direction}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`start`: {start}\n" f"`target`: {target}\n" f"`direction`: {direction}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(start: tuple[int, int], target: tuple[int, int], direction: tuple[int, int]) -> bool: """ Determines whether the ball can reach the target. Parameters: - start: Tuple[int, int], represents the initial position of the ball (x, y). - target: Tuple[int, int], represents the position of the target. - direction: Tuple[int, int], represents the initial direction of the ball (dx, dy). dx and dy are integers that can be either -1, 0, or 1. Returns: - bool: True if the ball can reach the target, False otherwise. """
{ "Common Sense": null, "Data Structures": [ "Path" ], "Dynamic Patterns": [ "Bouncing" ], "Geometric Objects": [ "Grid", "Arrow", "Point", "Line", "Coordinate System" ], "Mathematical Operations": null, "Spatial Transformations": null, "Topological Relations": [ "Intersection", "Boundary" ] }
Validation
q14-2
def solution(start_1: tuple[int, int], start_2: tuple[int, int], direction_1: tuple[int, int], direction_2: tuple[int, int]) -> bool: """ Determines whether the two balls will collide. Parameters: - start_1: Tuple[int, int], represents the initial position of ball 1 (x, y). - start_2: Tuple[int, int], represents the initial position of ball 2 (x, y). - direction_1: Tuple[int, int], represents the initial direction of ball 1 (dx, dy). dx and dy are integers that can be either -1, 0, or 1. - direction_2: Tuple[int, int], represents the initial direction of ball 2 (dx, dy). dx and dy are integers that can be either -1, 0, or 1. Returns: - bool: True if the balls can collide, False otherwise. """ x_1, y_1 = start_1 x_2, y_2 = start_2 dx_1, dy_1 = direction_1 dx_2, dy_2 = direction_2 while True: x_1 += dx_1 y_1 += dy_1 x_2 += dx_2 y_2 += dy_2 if (x_1, y_1) == (x_2, y_2): return True if (x_1 + 0.5 * dx_1, y_1 + 0.5 * dy_1) == (x_2 + 0.5 * dx_2, y_2 + 0.5 * dy_2): return True if x_1 == 0 or x_1 == 10: dx_1 = -dx_1 if x_2 == 0 or x_2 == 10: dx_2 = -dx_2 if y_1 == 0 or y_1 == 10: dy_1 = -dy_1 if y_2 == 0 or y_2 == 10: dy_2 = -dy_2 if (x_1, y_1) == start_1 and (x_2, y_2) == start_2 and (dx_1, dy_1) == direction_1 and (dx_2, dy_2) == direction_2: return False
# Problem Description This problem involves determining whether two balls, starting from different positions and moving in specified directions, will collide on a 10x10 grid. The balls bounce off the boundaries of the grid according to the law of reflection (angle of incidence equals angle of reflection). The task is to simulate the movement of the balls and check if they will collide at any point. # Visual Facts 1. The coordinate system is a 10x10 grid (from 0 to 10 on both axes). 2. Ball 1 starts at position (6, 9) and moves in the direction (-1, 1). 3. Ball 2 starts at position (9, 6) and moves in the direction (1, -1). 4. The paths of both balls are shown with dotted lines. 5. The paths indicate multiple bounces off the boundaries. 6. The collision point is marked at (2.5, 2.5). 7. The paths are straight lines between bounces. 8. The balls change direction upon hitting the boundaries. 9. The grid has clear boundaries at x=0, x=10, y=0, and y=10 # Visual Patterns 1. **Bouncing Pattern**: - When a ball hits a boundary, it reflects with equal angles. - The angle of reflection equals the angle of incidence. - The ball maintains a constant direction between bounces. 2. **Movement Constraints**: - Movement is continuous along straight lines. - Direction changes only occur at boundaries. - The balls follow predictable paths based on their initial directions and the grid boundaries. - The path never passes through the same point with the same direction twice (suggests a termination condition) 3. **Geometric Properties**: - The trajectory forms a series of connected line segments. - Each bounce preserves the angle but reverses one component of the direction vector. - The paths remain within the 10x10 grid boundaries at all times. 4. **Collision Detection**: - A collision occurs if both balls occupy the same position at the same time. - The paths of the balls can be simulated to check for intersections.
def test(): test_cases = [ [(8, 7), (6, 9), (1, -1), (1, 1), False], [(8, 7), (6, 9), (1, -1), (-1, 1), True], [(8, 7), (6, 9), (-1, 1), (1, -1), True], [(8, 7), (9, 6), (1, -1), (1, -1), False], [(0, 0), (1, 1), (1, 0), (1, 1), False], [(0, 0), (0, 3), (1, 0), (1, -1), True], [(0, 0), (2, 2), (1, 1), (0, 1), False], [(0, 0), (2, 2), (1, 1), (-1, -1), True], [(0, 0), (0, 1), (0, 1), (1, -1), False], [(2, 1), (1, 0), (-1, -1), (0, 1), False], [(10, 1), (1, 0), (-1, 1), (1, 0), False], [(10, 1), (9, 2), (-1, 1), (-1, 1), False], [(3, 4), (3, 6), (1, 1), (1, -1), True], ] for test_case in test_cases: start_1, start_2, direction_1, direction_2, expected_output = test_case try: output = solution(start_1, start_2, direction_1, direction_2) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`start_1`: {start_1}\n" f"`start_2`: {start_2}\n" f"`direction_1`: {direction_1}\n" f"`direction_2`: {direction_2}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`start_1`: {start_1}\n" f"`start_2`: {start_2}\n" f"`direction_1`: {direction_1}\n" f"`direction_2`: {direction_2}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(start_1: tuple[int, int], start_2: tuple[int, int], direction_1: tuple[int, int], direction_2: tuple[int, int]) -> bool: """ Determines whether the two balls will collide. Parameters: - start_1: Tuple[int, int], represents the initial position of ball 1 (x, y). - start_2: Tuple[int, int], represents the initial position of ball 2 (x, y). - direction_1: Tuple[int, int], represents the initial direction of ball 1 (dx, dy). dx and dy are integers that can be either -1, 0, or 1. - direction_2: Tuple[int, int], represents the initial direction of ball 2 (dx, dy). dx and dy are integers that can be either -1, 0, or 1. Returns: - bool: True if the balls can collide, False otherwise. """
{ "Common Sense": null, "Data Structures": [ "Path" ], "Dynamic Patterns": [ "Bouncing" ], "Geometric Objects": [ "Grid", "Arrow", "Point", "Line", "Coordinate System" ], "Mathematical Operations": null, "Spatial Transformations": null, "Topological Relations": [ "Intersection", "Boundary" ] }
Validation
q14-3
def solution(start: tuple[int, int], direction: tuple[int, int]) -> bool: """ Determines whether the ball can go into the hole Parameters: - start: Tuple[int, int], represents the initial position of the ball (x, y). - direction: Tuple[int, int], represents the initial direction of the ball (dx, dy). dx and dy are integers that can be either -1, 0, or 1. Returns: - bool: True if the ball can go into the hole, False otherwise. """ x, y = start tx1, ty1 = (2, 2) tx2, ty2 = (2, 8) dx, dy = direction while True: x += dx y += dy if (x, y) == (tx1, ty1) or (x, y) == (tx2, ty2): return True if x == 0 or x == 10: dx = -dx if y == 0 or y == 10: dy = -dy if (x, y) == start and (dx, dy) == direction: return False
# Problem Description This problem involves determining if a ball starting from a given position with an initial direction can reach any of the holes on a 10x10 grid. The ball follows the law of reflection when it hits the boundaries of the grid. The task is to simulate the ball's movement and check if it eventually falls into one of the holes. # Visual Facts 1. The coordinate system is a 10x10 grid (from 0 to 10 on both axes). 2. The grid has clear boundaries at x=0, x=10, y=0, and y=10. 3. The start point (green circle) is located at (8, 8). 4. There are two holes (black circles) located at (2, 2) and (2, 8). 5. The path is shown with blue dotted lines. 6. Blue arrows indicate the direction of movement. 7. The path shows multiple bounces off the boundaries. 8. The path eventually reaches one of the holes. 9. The path follows straight lines between bounces. # Visual Patterns 1. **Bouncing Pattern**: - When the ball hits a boundary, it reflects with equal angles. - The angle of reflection equals the angle of incidence. - The ball maintains a constant direction between bounces. 2. **Movement Constraints**: - Movement is continuous along straight lines.(x += dx,y += dy) - Direction changes only occur at boundaries. - The ball's direction vector components (dx, dy) can be -1, 0, or 1. - The path never passes through the same point with the same direction twice (suggests a termination condition) 3. **Geometric Properties**: - The trajectory forms a series of connected line segments - Each bounce preserves the angle but reverses one component of the direction vector - For example, if the original direction (dx, dy) is (1, 1), and the x boundary is encountered (x == 0 or x == 10), then dx = -dx, and the new direction becomes (-1, 1). - For example, if the original direction (dx, dy) is (1, 1), and the y boundary is encountered (y == 0 or y == 10), then dy = -dy, and the new direction becomes (1, -1). - The path remains within the 10x10 grid boundaries at all times 4. **Solution Pattern**: - To reach a hole, the ball must follow a valid sequence of bounces. - A valid solution exists if there's a path connecting the start to any hole following reflection rules. - The ball's movement can be simulated step-by-step to check if it reaches a hole. 5. **Step to solve**: 1. First, determine the positions of the two holes: (2, 2) and (2, 8). 2. Then, enter a loop to simulate the ball's movement in the grid. 3. In each iteration, update the ball's position: x += dx, y += dy. 4. If the current ball's position (x, y) is either (2, 2) or (2, 8), exit the loop, as the ball has entered a hole. 5. If the ball encounters a boundary where x == 0 or x == 10, then set dx = -dx. 6. If the ball encounters a boundary where y == 0 or y == 10, then set dy = -dy. 7. Exit the loop when the ball returns to the starting point and the direction is the same as the initial direction.
def test(): test_cases = [ [(8, 7), (1, -1), False], [(8, 7), (-1, -1), False], [(8, 8), (1, -1), True], [(0, 0), (1, 0), False], [(0, 0), (1, 1), True], [(0, 0), (0, 1), False], [(2, 1), (-1, -1), False], [(2, 1), (0, 1), True], [(10, 1), (-1, 1), False], [(7, 1), (1, 1), True], ] for test_case in test_cases: start, direction, expected_output = test_case try: output = solution(start, direction) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`start`: {start}\n" f"`direction`: {direction}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`start`: {start}\n" f"`direction`: {direction}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(start: tuple[int, int], direction: tuple[int, int]) -> bool: """ Determines whether the ball can go into the hole Parameters: - start: Tuple[int, int], represents the initial position of the ball (x, y). - direction: Tuple[int, int], represents the initial direction of the ball (dx, dy). dx and dy are integers that can be either -1, 0, or 1. Returns: - bool: True if the ball can go into the hole, False otherwise. """
{ "Common Sense": null, "Data Structures": [ "Path" ], "Dynamic Patterns": [ "Bouncing" ], "Geometric Objects": [ "Grid", "Arrow", "Point", "Line", "Coordinate System" ], "Mathematical Operations": null, "Spatial Transformations": null, "Topological Relations": [ "Intersection", "Boundary" ] }
Validation
q15
def solution(end_time: int) -> int: """ Calculate how many layers of cups have been full-filled by the given end time. Input: - end_time: the given end time. Output: - the total numbers of full-filled layers. """ layers_filled = 0 total_time = 0 while True: time_for_next_layer = 8 * 2 ** layers_filled total_time += time_for_next_layer if total_time > end_time: break layers_filled += 1 return layers_filled
# Problem Description This is a water flow simulation problem in a pyramid-like cup structure. Water is poured continuously from the top, and when a cup is full, it overflows equally to the two cups below it. The task is to calculate how many layers of cups are completely filled at a given time point. # Visual Facts 1. Cup Arrangement: - Cups are arranged in a pyramid structure - Each layer has more cups than the one above it - Each cup can overflow into two cups below it 2. Time Snapshots: - t=0: Initial state, 0 full cups - t=8: 1 cup full (top layer cup) - t=24: 3 cups full (top cup + 2 second-layer cups) - t=56: 6 cups full (top cup + 2 second-layer cups + 3 third-layer cups) # Visual Patterns 1. Flow Pattern: - Water starts from the top cup - When a cup is full, it splits water equally to cups below - Cups fill gradually and maintain their filled state 2. Mathematical Patterns: - Fill rate appears to be constant (8 time units for filling one cup) - Each layer takes progressively longer to fill (8, 16, 32, ...) - The time consumed on each layer follows the formula: time = 8 * 2 ** (layer_idx - 1), where layer_idx is the index of the layer (starting from 1).
def test(): test_cases = [ (1*8, 1), (2*8, 1), (3*8, 2), (4*8, 2), (5*8, 2), (7*8, 3), (9*8, 3), (25*8, 4), (30*8, 4), (50*8, 5), (70*8, 6), (100*8, 6), ] for i, (end_time, expected_output) in enumerate(test_cases): try: output = solution(end_time) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`end_time`: {end_time}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`end_time`: {end_time}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(end_time: int) -> int: """ Calculate how many layers of cups have been full-filled by the given end time. Input: - end_time: the given end time. Output: - the total numbers of full-filled layers. """
{ "Common Sense": [ "Flow of Water", "Capacity" ], "Data Structures": null, "Dynamic Patterns": [ "Layered Structure", "Propagation" ], "Geometric Objects": null, "Mathematical Operations": null, "Spatial Transformations": null, "Topological Relations": [ "Connectivity", "Connection" ] }
Iterative Calculation
q16
def solution(grid: list[int]) -> int: """ Calculate the number of communities according to the image. Input: - grid: A list representing the initial grid, each str element is a row of the grid. The 'x' indicates a gray square and '.' indicates a white square. Output: - An integer representing the number of communities. """ if not grid or not grid[0]: return 0 def dfs(i, j): # Stack for DFS stack = [(i, j)] while stack: x, y = stack.pop() if (x, y) in visited: continue visited.add((x, y)) # Check all 8 possible directions (including diagonals) for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (-1, 1), (1, -1), (1, 1)]: nx, ny = x + dx, y + dy if 0 <= nx < len(grid) and 0 <= ny < len(grid[0]) and grid[nx][ny] == '.' and (nx, ny) not in visited: stack.append((nx, ny)) visited = set() communities = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == '.' and (i, j) not in visited: dfs(i, j) communities += 1 return communities
# Problem Description This is a grid-based problem where we need to count the number of "communities" in a given grid. A community appears to be a group of connected white squares (represented by '.') in a grid where some squares are gray (represented by 'x'). The goal is to return the total count of distinct communities in the grid. # Visual Facts 1. The image shows two different grid examples 2. First grid example has 3 communities, second has 4 communities 3. Each grid is an 7x3 rectangular matrix 4. Squares are either white (empty) or gray (filled) 5. White squares within the same community are labeled with the same number label 6. White squares are considered connected if they share a common edge or corner # Visual Patterns 1. Community Definition: - A community is formed by adjacent white squares that are connected horizontally or vertically - White squares that only touch diagonally are also considered part of the same community 2. Counting Pattern: - The actual numbers assigned to communities don't matter, only the count of distinct communities is important 3. Boundary Rules: - A community can be as small as one white square - Communities can have irregular shapes as long as squares are connected properly
def test(): test_cases = [ ([".x.x", "xxxx"], 2), (["....", "..xx"], 1), ([".xxxx....", "..xxx.xxx"], 2), (["xxx..", "...x."], 1), (["xxx..xx", "...xx.."], 1), (["x.x..x", ".x...x", "..x.xx", "x.x..."], 1), (["....x..", "xx.x.x.", ".xx..x.", "x.xxxx."], 2) ] for grid, expected_output in test_cases: try: output = solution(grid) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`grid`:\n" f"{'\n'.join(grid)}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`grid`:\n" f"{'\n'.join(grid)}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(grid: list[int]) -> int: """ Calculate the number of communities according to the image. Input: - grid: A list representing the initial grid, each str element is a row of the grid. The 'x' indicates a gray square and '.' indicates a white square. Output: - An integer representing the number of communities. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": null, "Geometric Objects": [ "Grid", "Square" ], "Mathematical Operations": null, "Spatial Transformations": [ "Clustering", "Grouping" ], "Topological Relations": [ "Connectivity", "Adjacency" ] }
Aggregation
q17
def solution(matrix: list[list[int]]) -> list[list[int]]: """ Refer to the example cases illustrated in the figure, identify and implement the pooling operation on the matrix. Input: - matrix: A 2d list representing the initial matrix. For example, [[1,3,4,2], [2,1,1,3], [1,2,2,4], [3,2,1,0]] Output: - A 2d list representing the resulting matrix after the pooling operation. """ rows = len(matrix) cols = len(matrix[0]) pooled_matrix = [] for i in range(0, rows, 2): pooled_row = [] for j in range(0, cols, 2): block = [ matrix[i][j], matrix[i][j + 1] if j + 1 < cols else float('inf'), matrix[i + 1][j] if i + 1 < rows else float('inf'), matrix[i + 1][j + 1] if i + 1 < rows and j + 1 < cols else float('inf') ] min_value = min(block) pooled_row.append(min_value) pooled_matrix.append(pooled_row) return pooled_matrix
# Problem Description This is a matrix pooling operation problem where a larger input matrix needs to be transformed into a smaller output matrix using specific rules. The pooling operation appears to reduce the size of the input matrix by processing 2×2 regions into single values in the output matrix. The goal is to implement this transformation according to the pattern shown in the examples. # Visual Facts 1. Example 1: - Input: 2×2 matrix - Output: 1×1 matrix - Value 1 is selected from upper-left position 2. Example 2: - Input: 4×4 matrix - Output: 2×2 matrix - Each 2×2 section in input maps to one value in output - Output values [1,4,2,0] come from specific positions in input 3. Example 3: - Input: 6×6 matrix - Output: 3×3 matrix - Each 2×2 section maps to one output value - Output matrix contains [1,2,0, 2,3,0, 2,4,2] # Visual Patterns 1. Size Reduction Pattern: - Output matrix size is always half of input matrix in each dimension - Input dimensions must be even numbers - Input n×n matrix → Output (n/2)×(n/2) matrix 2. Value Selection Pattern: - Each 2×2 block in input maps to single value in output - The selected value appears to be the minimum value from each 2×2 block - For any 2×2 block: ``` [a b] → min(a,b,c,d) [c d] ``` 3. Scanning Pattern: - Matrix is scanned from left to right, top to bottom - Each 2×2 non-overlapping block is processed independently - No blocks overlap or share elements 4. General Rule: - For input matrix of size n×n - Output[i][j] = min(Input[2i][2j], Input[2i][2j+1], Input[2i+1][2j], Input[2i+1][2j+1]) where i and j are indices in the output matrix
def test(): test_cases = [ { "input":[ [1,2], [3,4] ], "expected":[ [1] ] }, { "input": [ [1, 3, 4, 2], [2, 1, 1, 3], [1, 2, 2, 4], [3, 2, 1, 0] ], "expected": [ [1, 1], [1, 0] ] }, { "input": [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ], "expected": [ [1, 3], [9, 11] ] }, { "input": [ [1, 1], [1, 10] ], "expected": [ [1] ] }, { "input": [ [1, 2, 3, 4, 5, 6], [12, 11, 10, 9, 8, 7], [13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24], [30, 29, 28, 27, 26, 25], [31, 32, 33, 34, 35, 36] ], "expected": [ [1, 3, 5], [13, 15, 17], [29, 27, 25] ] } ] for i, test_case in enumerate(test_cases): matrix = test_case["input"] expected_output = test_case["expected"] try: output = solution(matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`matrix`: {matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`matrix`: {matrix}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(matrix: list[list[int]]) -> list[list[int]]: """ Refer to the example cases illustrated in the figure, identify and implement the pooling operation on the matrix. Input: - matrix: A 2d list representing the initial matrix. For example, [[1,3,4,2], [2,1,1,3], [1,2,2,4], [3,2,1,0]] Output: - A 2d list representing the resulting matrix after the pooling operation. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": null, "Geometric Objects": null, "Mathematical Operations": [ "Value Comparison", "Aggregation" ], "Spatial Transformations": [ "Grouping", "Scaling", "Filtering" ], "Topological Relations": [ "Adjacency" ] }
Aggregation
q17-2
def solution(matrix: list[list[int]]) -> list[list[int]]: """ Refer to the example cases illustrated in the figure, identify and implement the pooling operation on the matrix. Input: - matrix: A 2d list representing the initial matrix. For example, [[1,3,4,2], [2,1,1,3], [1,2,2,4], [3,2,1,0]] Output: - A 2d list representing the resulting matrix after the pooling operation. """ rows = len(matrix) cols = len(matrix[0]) pooled_matrix = [] for i in range(0, rows, 2): pooled_row = [] for j in range(0, cols, 2): block = [ matrix[i][j], matrix[i][j + 1] if j + 1 < cols else 0, matrix[i + 1][j] if i + 1 < rows else 0, matrix[i + 1][j + 1] if i + 1 < rows and j + 1 < cols else 0 ] max_value = max(abs(num) for num in block) pooled_row.append(max_value if max_value in block else -max_value) pooled_matrix.append(pooled_row) return pooled_matrix
# Problem Description This problem involves performing a pooling operation on a given 2D matrix. The pooling operation reduces the size of the matrix by processing 2x2 regions into single values in the output matrix. The goal is to implement this transformation according to the pattern shown in the examples. # Visual Facts 1. Example Case 1: - Input: 2x2 matrix - Output: 1x1 matrix - The value in the output matrix is the value with the maximum absolute value from the input matrix. 2. Example Case 2: - Input: 4x4 matrix - Output: 2x2 matrix - Each 2x2 section in the input matrix maps to one value in the output matrix. - The values in the output matrix are the value with the maximum absolute values from the corresponding 2x2 sections in the input matrix. 3. Example Case 3: - Input: 6x6 matrix - Output: 3x3 matrix - Each 2x2 section in the input matrix maps to one value in the output matrix. - The values in the output matrix are the value with the maximum absolute values from the corresponding 2x2 sections in the input matrix. # Visual Patterns 1. Size Reduction Pattern: - The output matrix size is always half of the input matrix in each dimension. - The input dimensions must be even numbers. - For an input matrix of size n×n, the output matrix will be of size (n/2)×(n/2). 2. Value Selection Pattern: - Each 2x2 block in the input matrix maps to a single value in the output matrix. - The selected value is the maximum absolute value from each 2x2 block. - For any 2x2 block: ``` [a b] [c d] ``` The output absolute value is max(|a|, |b|, |c|, |d|), and the sign of the output should remain the same as the original value's sign. For example, if |b| has the largest absolute value and b is negative, the output will be -|b|. 3. Scanning Pattern: - The matrix is scanned from left to right, top to bottom. - Each 2x2 non-overlapping block is processed independently. - No blocks overlap or share elements. 4. General Rule: - For an input matrix of size n×n: - |Output[i][j]| = max(|Input[2i][2j]|, |Input[2i][2j+1]|, |Input[2i+1][2j]|, |Input[2i+1][2j+1]|) - The sign of the output is determined by the sign of the value with the largest absolute value in the 2x2 block. where i and j are indices in the output matrix.
def test(): test_cases = [ { "input": [ [1, -2], [3, 4] ], "expected": [ [4] ] }, { "input": [ [1, 3, 4, 2], [2, 1, 1, 3], [1, 2, 2, 4], [3, 2, 1, 0] ], "expected": [ [3, 4], [3, 4] ] }, { "input": [ [1, 2, 3, 4], [5, -6, 7, -8], [-9, -10, -11, 12], [13, 14, 15, -16] ], "expected": [ [-6, -8], [14, -16] ] }, { "input": [ [1, 1], [1, 10] ], "expected": [ [10] ] }, { "input": [ [1, -2, 3, 4, 5, -6], [12, 11, -10, 9, 8, 7], [13, 14, 15, 16, -17, 18], [-19, 20, 21, 22, 23, 24], [-30, -29, 28, 27, 26, 25], [31, 32, 33, -34, 35, -36] ], "expected": [ [12, -10, 8], [20, 22, 24], [32, -34, -36] ] } ] for i, test_case in enumerate(test_cases): matrix = test_case["input"] expected_output = test_case["expected"] try: output = solution(matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`matrix`:\n" ) # Print matrix row by row for better readability for row in matrix: error_message += f"{row}\n" error_message += f"\nException: '{str(e)}'" assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`matrix`:\n" ) # Print matrix row by row for better readability for row in matrix: error_message += f"{row}\n" error_message += ( f"\nActual Output:\n" ) for row in output: error_message += f"{row}\n" error_message += ( f"\nExpected Output:\n" ) for row in expected_output: error_message += f"{row}\n" assert False, error_message test()
def solution(matrix: list[list[int]]) -> list[list[int]]: """ Refer to the example cases illustrated in the figure, identify and implement the pooling operation on the matrix. Input: - matrix: A 2d list representing the initial matrix. For example, [[1,3,4,2], [2,1,1,3], [1,2,2,4], [3,2,1,0]] Output: - A 2d list representing the resulting matrix after the pooling operation. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": null, "Geometric Objects": null, "Mathematical Operations": [ "Value Comparison", "Aggregation", "Absolute Value" ], "Spatial Transformations": [ "Grouping", "Scaling", "Filtering" ], "Topological Relations": [ "Adjacency" ] }
Aggregation
q17-3
def solution(matrix: list[list[int]]) -> list[list[int]]: """ Refer to the example cases illustrated in the figure, identify and implement the pooling operation on the matrix. Input: - matrix: A 2d list representing the initial matrix. For example, [[1,3,4], [2,1,1], [1,2,2]] Output: - A 2d list representing the resulting matrix after the pooling operation. """ rows = len(matrix) cols = len(matrix[0]) pooled_matrix = [] for i in range(0, rows, 3): pooled_row = [] for j in range(0, cols, 3): block = [ matrix[i][j], matrix[i][j + 1] if j + 1 < cols else float('inf'), matrix[i][j + 2] if j + 2 < cols else float('inf'), matrix[i + 1][j] if i + 1 < rows else float('inf'), matrix[i + 2][j] if i + 2 < rows else float('inf'), matrix[i + 1][j + 1] if i + 1 < rows and j + 1 < cols else float('inf'), matrix[i + 2][j + 2] if i + 2 < rows and j + 2 < cols else float('inf'), matrix[i + 1][j + 2] if i + 1 < rows and j + 2 < cols else float('inf'), matrix[i + 2][j + 1] if i + 2 < rows and j + 1 < cols else float('inf'), ] min_value = min(block) pooled_row.append(min_value) pooled_matrix.append(pooled_row) return pooled_matrix
# Problem Description This problem involves performing a pooling operation on a given matrix. The pooling operation reduces the size of the matrix by selecting specific elements from sub-regions of the original matrix. The goal is to implement this transformation according to the patterns shown in the examples. # Visual Facts 1. Example Case 1: - Input: 3×3 matrix - Output: 1×1 matrix - The value 1 is selected from the upper-left position of the input matrix. 2. Example Case 2: - Input: 6×6 matrix - Output: 2×2 matrix - Each 3×3 section in the input matrix maps to one value in the output matrix. - The output values [1, 0, 2, 3] come from specific positions in the input matrix. 3. Example Case 3: - Input: 9×9 matrix - Output: 3×3 matrix - Each 3×3 section in the input matrix maps to one value in the output matrix. - The output matrix contains [1, 3, 4, 0, 0, 5, 2, 2, 3]. # Visual Patterns 1. Size Reduction Pattern: - The output matrix size is reduced by a factor of 3 in each dimension. - Input dimensions must be multiples of 3. - An input matrix of size n×n results in an output matrix of size (n/3)×(n/3). 2. Value Selection Pattern: - Each 3×3 block in the input matrix maps to a single value in the output matrix. - The selected value is the minimum value from each 3×3 block. - For any 3×3 block: ``` [a b c] [d e f] → min(a, b, c, d, e, f, g, h, i) [g h i] ``` 3. Scanning Pattern: - The matrix is scanned from left to right, top to bottom. - Each 3×3 non-overlapping block is processed independently. - No blocks overlap or share elements. 4. General Rule: - For an input matrix of size n×n: - Output[i][j] = min(Input[3i][3j], Input[3i][3j+1], Input[3i][3j+2], Input[3i+1][3j], Input[3i+1][3j+1], Input[3i+1][3j+2], Input[3i+2][3j], Input[3i+2][3j+1], Input[3i+2][3j+2]) - Where i and j are indices in the output matrix.
def test(): test_cases = [ { "input": [ [1, 2, 6], [3, 4, 3], [8, 7, 9], ], "expected": [ [1] ] }, { "input": [ [1, 3, 4, 2, 0, 3], [2, 1, 1, 3, 2, 6], [1, 2, 2, 4, 4, 7], [3, 2, 1, 0, 1, 0], [1, 7, 5, 2, 2, 0], [2, 9, 1, 2, 3, 1], ], "expected": [ [1, 0], [1, 0] ] }, { "input": [ [1, 2, 3, 4, 3, 4], [5, 6, 7, 8, 1, 0], [9, 10, 11, 12, 2, 9], [13, 14, 15, 16, 0, 1], [1, 6, 3, 8, 9, 7], [0, 4, 3, 3, 0, 2], ], "expected": [ [1, 0], [0, 0] ] }, { "input": [ [1, 1, 4], [1, 10, 3], [2, 1, 2], ], "expected": [ [1] ] }, { "input": [ [1, 2, 3, 4, 5, 6, 4, 5, 1], [12, 11, 10, 9, 8, 7, 0, 3, 4], [13, 14, 15, 16, 17, 18, 2, 9, 7], [19, 20, 21, 22, 23, 24, 4, 8, 6], [30, 29, 28, 27, 26, 25, 2, 2, 4], [31, 32, 33, 34, 35, 36, 7, 7, 8], [43, 44, 12, 22, 45, 46, 65, 23, 25], [56, 45, 23, 27, 32, 35, 36, 57, 64], [54, 34, 43, 34, 23, 33, 45, 43, 54], ], "expected": [ [1, 4, 0], [19, 22, 2], [12, 22, 23] ] } ] for i, test_case in enumerate(test_cases): matrix = test_case["input"] expected_output = test_case["expected"] try: output = solution(matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`matrix`: {matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`matrix`: {matrix}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(matrix: list[list[int]]) -> list[list[int]]: """ Refer to the example cases illustrated in the figure, identify and implement the pooling operation on the matrix. Input: - matrix: A 2d list representing the initial matrix. For example, [[1,3,4], [2,1,1], [1,2,2]] Output: - A 2d list representing the resulting matrix after the pooling operation. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": null, "Geometric Objects": null, "Mathematical Operations": [ "Value Comparison", "Aggregation" ], "Spatial Transformations": [ "Grouping", "Scaling", "Filtering" ], "Topological Relations": [ "Adjacency" ] }
Aggregation
q18
from typing import List def solution(matrix: List[List[int]]) -> List[int]: """ Given an M x N 2D matrix, traverse the matrix according to the spiral pattern shown in the figure Parameters: matrix (List[List[int]]): A 2D list of integers representing the matrix. Returns: List[int]: A list of integers representing the elements of the matrix in the order as shown in the picture. """ result = [] top, bottom = 0, len(matrix) - 1 left, right = 0, len(matrix[0]) - 1 while top <= bottom and left <= right: # Traverse from right to left for i in range(right, left - 1, -1): result.append(matrix[top][i]) top += 1 # Traverse from top to bottom for i in range(top, bottom + 1): result.append(matrix[i][left]) left += 1 if top <= bottom: # Traverse from left to right for i in range(left, right + 1): result.append(matrix[bottom][i]) bottom -= 1 if left <= right: # Traverse from bottom to top for i in range(bottom, top - 1, -1): result.append(matrix[i][right]) right -= 1 return result
# Problem Description This is a matrix traversal problem where we need to: - Start from the top-right corner of a given matrix - Follow a specific spiral pattern in counter-clockwise direction - Collect all elements in the order of traversal - The traversal pattern should work for matrices of different sizes (MxN) # Visual Facts 1. Four example matrices are shown with different dimensions: - 4x1 (top-right) - 4x2 (top-left) - 4x3 (bottom-left) - 4x4 (bottom-right) 2. Each matrix is numbered sequentially from 1 to maximum cells (N×M) 3. Arrows indicate the direction of traversal 4. Starting point is always at position (0, N-1) (top-right corner) 5. Initial movement is always leftward # Visual Patterns 1. Movement Direction Pattern: - Follows a consistent sequence: Left → Down → Right → Up → Left → ... - Arrows show the traversal direction changes at boundaries or visited cells 2. Traversal Rules: - First move: Always move left along the top row - Each cell is visited exactly once - When can't move in current direction, rotate counter-clockwise - Forms a spiral pattern inward - Continue until all cells are visited
def test(): test_cases = [ ([[1, 2]], [2, 1]), ([[1, 2], [3, 4]], [2, 1, 3, 4]), ([[1, 2, 3], [4, 5, 6], [7, 8 , 9]], [3, 2, 1, 4, 7, 8, 9, 6, 5]), ([[1,2,3,4], [5,6,7,8], [9,10,11,12]], [4, 3, 2, 1, 5, 9, 10, 11, 12, 8, 7, 6]), ([[1, 3, 5, 6, 2], [43, 23, 19, 22, 33], [12, 11, 6, 8, 4]], [2, 6, 5, 3, 1, 43, 12, 11, 6, 8, 4, 33, 22, 19, 23]), ([[1, 2], [3, 4], [5, 6], [7, 8]], [2, 1, 3, 5, 7, 8, 6, 4]), ([[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14]], [7, 6, 5, 4, 3, 2, 1, 8, 9, 10, 11, 12, 13, 14]), ([[1, 2, 3, 4, 5, 6, 7, 8], [13, 24, 32, 41, 54, 65, 76, 87], [43, 2, 87, 5, 4, 66, 13, 94], [0, 12, 87, 43, 56, 36, 92, 44], [32, 33, 34, 55, 56, 72, 73, 77]], [8, 7, 6, 5, 4, 3, 2, 1, 13, 43, 0, 32, 33, 34, 55, 56, 72, 73, 77, 44, 94, 87, 76, 65, 54, 41, 32, 24, 2, 12, 87, 43, 56, 36, 92, 13, 66, 4, 5, 87]), ([[1, 3, 5], [7, 9, 11], [2, 4, 6], [8, 10, 14]], [5, 3, 1, 7, 2, 8, 10, 14, 6, 11, 9, 4]), ([[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 17], [13, 15, 16, 19, 20, 91]], [6, 5, 4, 3, 2, 1, 7, 13, 15, 16, 19, 20, 91, 17, 11, 10, 9, 8]), ] for i, (matrix, expected_output) in enumerate(test_cases): original_matrix = [row.copy() for row in matrix] try: output = solution(matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`matrix`: {original_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`matrix`: {original_matrix}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(matrix: List[List[int]]) -> List[int]: """ Given an M x N 2D matrix, traverse the matrix according to the spiral pattern shown in the figure Parameters: matrix (List[List[int]]): A 2D list of integers representing the matrix. Returns: List[int]: A list of integers representing the elements of the matrix in the order as shown in the picture. """
{ "Common Sense": null, "Data Structures": [ "Path", "Matrix", "Directed Graph" ], "Dynamic Patterns": [ "Cyclic Motion", "Spiral" ], "Geometric Objects": [ "Grid", "Arrow" ], "Mathematical Operations": null, "Spatial Transformations": null, "Topological Relations": [ "Connection", "Adjacency" ] }
Transformation
q18-2
from typing import List def solution(matrix: List[List[int]]) -> List[int]: """ Given an M x N 2D matrix, traverse the matrix according to the spiral pattern shown in the figure Parameters: matrix (List[List[int]]): A 2D list of integers representing the matrix. Returns: List[int]: A list of integers representing the elements of the matrix in the order as shown in the picture. """ result = [] top, bottom = 0, len(matrix) - 1 left, right = 0, len(matrix[0]) - 1 while bottom >= top and left <= right: # Traverse from right to left for i in range(right, left - 1, -1): result.append(matrix[bottom][i]) bottom -= 1 # Traverse from bottom to top for i in range(bottom, top - 1, -1): result.append(matrix[i][left]) left += 1 if bottom >= top: # Traverse from left to right for i in range(left, right + 1): result.append(matrix[top][i]) top += 1 if left <= right: # Traverse from top to bottom for i in range(top, bottom + 1): result.append(matrix[i][right]) right -= 1 return result
# Problem Description The problem requires implementing a matrix traversal function that follows a specific spiral pattern. Given a matrix of M x N dimensions, we need to return the elements in a specific order that follows a spiral path starting from the bottom-right corner, moving initially leftward, and then following a clockwise spiral pattern towards the inside of the matrix. # Visual Facts 1. The image shows 4 different matrix examples: - 4x1 matrix (top-right) - 4x2 matrix (top-left) - 4x3 matrix (bottom-left) - 4x4 matrix (bottom-right) 2. Each matrix is numbered sequentially from 1 to its size (4, 8, 12, or 16) 3. Arrows indicate the direction of traversal 4. All examples start from the bottom-right corner # Visual Patterns 1. Movement Direction Pattern: - Follows a consistent sequence: Left → Up → Right → Down → Left → ... - Arrows show the traversal direction changes at boundaries or visited cells 2. Traversal Rules: - First move: Always move left along the bottom row - Each cell is visited exactly once - When can't move in current direction, rotate clockwise - Forms a spiral pattern inward - Continue until all cells are visited
def test(): test_cases = [ ([[1, 2]], [2, 1]), ([[1, 2], [3, 4]], [4, 3, 1, 2]), ([[1, 2, 3], [4, 5, 6], [7, 8 , 9]], [9, 8, 7, 4, 1, 2, 3, 6, 5]), ([[1,2,3,4], [5,6,7,8], [9,10,11,12]], [12, 11, 10, 9, 5, 1, 2, 3, 4, 8, 7, 6]), ([[1, 3, 5, 6, 2], [43, 23, 19, 22, 33], [12, 11, 6, 8, 4]], [4, 8, 6, 11, 12, 43, 1, 3, 5, 6, 2, 33, 22, 19, 23]), ([[1, 2], [3, 4], [5, 6], [7, 8]], [8, 7, 5, 3, 1, 2, 4, 6]), ([[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14]], [14, 13, 12, 11, 10, 9, 8, 1, 2, 3, 4, 5, 6, 7]), ([[1, 2, 3, 4, 5, 6, 7, 8], [13, 24, 32, 41, 54, 65, 76, 87], [43, 2, 87, 5, 4, 66, 13, 94], [0, 12, 87, 43, 56, 36, 92, 44], [32, 33, 34, 55, 56, 72, 73, 77]], [77, 73, 72, 56, 55, 34, 33, 32, 0, 43, 13, 1, 2, 3, 4, 5, 6, 7, 8, 87, 94, 44, 92, 36, 56, 43, 87, 12, 2, 24, 32, 41, 54, 65, 76, 13, 66, 4, 5, 87]), ([[1, 3, 5], [7, 9, 11], [2, 4, 6], [8, 10, 14]], [14, 10, 8, 2, 7, 1, 3, 5, 11, 6, 4, 9]), ([[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 17], [13, 15, 16, 19, 20, 91]], [91, 20, 19, 16, 15, 13, 7, 1, 2, 3, 4, 5, 6, 17, 11, 10, 9, 8]), ] for i, (matrix, expected_output) in enumerate(test_cases): original_matrix = [row.copy() for row in matrix] try: output = solution(matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`matrix`: {original_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`matrix`: {original_matrix}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(matrix: List[List[int]]) -> List[int]: """ Given an M x N 2D matrix, traverse the matrix according to the spiral pattern shown in the figure Parameters: matrix (List[List[int]]): A 2D list of integers representing the matrix. Returns: List[int]: A list of integers representing the elements of the matrix in the order as shown in the picture. """
{ "Common Sense": null, "Data Structures": [ "Path", "Matrix", "Directed Graph" ], "Dynamic Patterns": [ "Cyclic Motion", "Spiral" ], "Geometric Objects": [ "Grid", "Arrow" ], "Mathematical Operations": null, "Spatial Transformations": null, "Topological Relations": [ "Connection", "Adjacency" ] }
Transformation
q18-3
from typing import List def solution(matrix: List[List[int]]) -> List[int]: """ Given an M x N 2D matrix, traverse the matrix according to the spiral pattern shown in the figure Parameters: matrix (List[List[int]]): A 2D list of integers representing the matrix. Returns: List[int]: A list of integers representing the elements of the matrix in the order as shown in the picture. """ result = [] top, bottom = 0, len(matrix) - 1 left, right = 0, len(matrix[0]) - 1 while top <= bottom and left <= right: # Traverse from left to right for i in range(left, right + 1): result.append(matrix[bottom][i]) bottom -= 1 # Traverse from bottom to top for i in range(bottom, top - 1, -1): result.append(matrix[i][right]) right -= 1 if top <= bottom: # Traverse from right to left for i in range(right, left - 1, -1): result.append(matrix[top][i]) top += 1 if left <= right: # Traverse from top to bottom for i in range(top, bottom + 1): result.append(matrix[i][left]) left += 1 return result
# Problem Description The problem requires implementing a matrix traversal function that follows a specific spiral pattern. Given a matrix of M x N dimensions, we need to return the elements in a specific order that follows a spiral path starting from the bottom-left corner, moving initially rightward, and then following a counter-clockwise spiral pattern towards the inside of the matrix. # Visual Facts 1. The image shows 4 different matrix examples: - 4x1 matrix (top-right) - 4x2 matrix (top-left) - 4x3 matrix (bottom-left) - 4x4 matrix (bottom-right) 2. Each matrix is numbered sequentially from 1 to its size (4, 8, 12, or 16) 3. Arrows indicate the direction of traversal 4. All examples start from the bottom-left corner # Visual Patterns 1. Movement Direction Pattern: - Follows a consistent sequence: Right → Up → Left → Down → Right → ... - Arrows show the traversal direction changes at boundaries or visited cells 2. Traversal Rules: - First move: Always move right along the bottom row - Each cell is visited exactly once - When can't move in current direction, rotate counter-clockwise - Forms a spiral pattern inward - Continue until all cells are visited
def test(): test_cases = [ ([[1, 2]], [1, 2]), ([[1, 2], [3, 4]], [3, 4, 2, 1]), ([[1, 2, 3], [4, 5, 6], [7, 8 , 9]], [7, 8, 9, 6, 3, 2, 1, 4, 5]), ([[1,2,3,4], [5,6,7,8], [9,10,11,12]], [9, 10, 11, 12, 8, 4, 3, 2, 1, 5, 6, 7]), ([[1, 3, 5, 6, 2], [43, 23, 19, 22, 33], [12, 11, 6, 8, 4]], [12, 11, 6, 8, 4, 33, 2, 6, 5, 3, 1, 43, 23, 19, 22]), ([[1, 2], [3, 4], [5, 6], [7, 8]], [7, 8, 6, 4, 2, 1, 3, 5]), ([[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14]], [8, 9, 10, 11, 12, 13, 14, 7, 6, 5, 4, 3, 2, 1]), ([[1, 2, 3, 4, 5, 6, 7, 8], [13, 24, 32, 41, 54, 65, 76, 87], [43, 2, 87, 5, 4, 66, 13, 94], [0, 12, 87, 43, 56, 36, 92, 44], [32, 33, 34, 55, 56, 72, 73, 77]], [32, 33, 34, 55, 56, 72, 73, 77, 44, 94, 87, 8, 7, 6, 5, 4, 3, 2, 1, 13, 43, 0, 12, 87, 43, 56, 36, 92, 13, 76, 65, 54, 41, 32, 24, 2, 87, 5, 4, 66]), ([[1, 3, 5], [7, 9, 11], [2, 4, 6], [8, 10, 14]], [8, 10, 14, 6, 11, 5, 3, 1, 7, 2, 4, 9]), ([[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 17], [13, 15, 16, 19, 20, 91]], [13, 15, 16, 19, 20, 91, 17, 6, 5, 4, 3, 2, 1, 7, 8, 9, 10, 11]), ] for i, (matrix, expected_output) in enumerate(test_cases): try: output = solution(matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`matrix`: {matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`matrix`: {matrix}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(matrix: List[List[int]]) -> List[int]: """ Given an M x N 2D matrix, traverse the matrix according to the spiral pattern shown in the figure Parameters: matrix (List[List[int]]): A 2D list of integers representing the matrix. Returns: List[int]: A list of integers representing the elements of the matrix in the order as shown in the picture. """
{ "Common Sense": null, "Data Structures": [ "Path", "Matrix", "Directed Graph" ], "Dynamic Patterns": [ "Cyclic Motion", "Spiral" ], "Geometric Objects": [ "Grid", "Arrow" ], "Mathematical Operations": null, "Spatial Transformations": null, "Topological Relations": [ "Connection", "Adjacency" ] }
Transformation
q19
def solution(dragon_life: float, player_life: float, dragon_attack_point: float, player_attack_point: float) -> int: """ Build the dragon slaying game as shown in the diagram, and calculate how many life points the winner has left. Parameters: dragon_life (float): The life points of the dragon. player_life (float): The life points of the player. dragon_attack_point (float): The base attack points of the dragon. player_attack_point (float): The base attack points of the player. Returns: int: The life points of the winner (rounded down). """ status = 1 while True: dragon_life -= player_attack_point if dragon_life <= 0: return int(player_life) if dragon_life < 60 and status == 1: status = 2 player_attack_point *= 1.2 dragon_attack_point *= 0.8 player_life -= dragon_attack_point if player_life <= 0: return int(dragon_life)
# Problem Description This is a turn-based battle game simulation between a player and a dragon. The game has two distinct status phases with different attack patterns. The goal is to calculate the remaining life points of whoever wins the battle (either dragon or player). The battle follows specific rules for attack power modifications and status transitions. # Visual Facts Status 1: - Player attacks the dragon with 100% attack power. - Check dragon's life: - If life > 0, continue. - If life ≤ 0, game over. - If dragon's life < 60, shift to Status 2. - Otherwise, Dragon attacks the player with 100% attack power. - Check player's life: - If life > 0, return to player's attack. - If life ≤ 0, game over. Status 2: - Dragon attacks the player with 80% attack power. - Check player's life: - If life > 0, continue. - If life ≤ 0, game over. - Player attacks the dragon with 120% attack power. - Check dragon's life: - If life > 0, continue. - If life ≤ 0, game over. # Visual Patterns 1. Critical Thresholds: - Dragon life < 60 triggers status change from Status 1 to Status 2 - Life points ≤ 0 triggers game over 2. Turn Order Pattern: - Status 1: Player attack → check status shifting → Dragon attack → Player attack → ... - Status 2: Dragon attack → Player attack → Dragon attack → ...
def test(): test_cases = [ (100, 90, 10, 5, 49), (59.9, 78, 60, 26.6, 1), (1000.1, 100.79, 8.54, 50.3, 396), (63, 100, 100, 1, 62), (1000.34, 10, 11, 1001, 10), (150.33, 176.24, 23.5, 26.8, 68), (92.3, 11.1, 1, 32.3, 9), (12384.4, 13323.9, 10.1, 11.1, 2080), (11111111.223, 11847382.68, 3.3, 4.4, 3514065), (1321137281.11, 837272819.23, 55.9, 666, 726384604), ] for i, (dragon_life, player_life, dragon_attack_point, player_attack_point, expected_output) in enumerate(test_cases): try: output = solution(dragon_life, player_life, dragon_attack_point, player_attack_point) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`dragon_life`: {dragon_life}\n" f"`player_life`: {player_life}\n" f"`dragon_attack_point`: {dragon_attack_point}\n" f"`player_attack_point`: {player_attack_point}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`dragon_life`: {dragon_life}\n" f"`player_life`: {player_life}\n" f"`dragon_attack_point`: {dragon_attack_point}\n" f"`player_attack_point`: {player_attack_point}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(dragon_life: float, player_life: float, dragon_attack_point: float, player_attack_point: float) -> int: """ Build the dragon slaying game as shown in the diagram, and calculate how many life points the winner has left. Parameters: dragon_life (float): The life points of the dragon. player_life (float): The life points of the player. dragon_attack_point (float): The base attack points of the dragon. player_attack_point (float): The base attack points of the player. Returns: int: The life points of the winner (rounded down). """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": null, "Geometric Objects": [ "Arrow" ], "Mathematical Operations": [ "Flowcharting", "Conditional Branching", "Value Comparison" ], "Spatial Transformations": null, "Topological Relations": [ "Connectivity", "Connection" ] }
Direct Calculation
q19-2
def solution(dragon_life: float, player_life: float, dragon_attack_point: float, player_attack_point: float) -> int: """ Build the dragon slaying game as shown in the diagram, and calculate how many life points the winner has left. Parameters: dragon_life (float): The life points of the dragon. player_life (float): The life points of the player. dragon_attack_point (float): The base attack points of the dragon. player_attack_point (float): The base attack points of the player. Returns: int: The life points of the winner (rounded down). """ status = 1 while True: dragon_life -= player_attack_point if dragon_life <= 0: return int(player_life) if dragon_life < 40 and status == 1: status = 2 player_attack_point *= 1.35 dragon_attack_point *= 0.65 player_life -= dragon_attack_point if player_life <= 0: return int(dragon_life)
# Problem Description This is a turn-based battle game simulation between a player and a dragon. The game has two distinct status phases with different attack patterns. The goal is to calculate the remaining life points of whoever wins the battle (either dragon or player). The battle follows specific rules for attack power modifications and status transitions. # Visual Facts Status 1: - Player attacks the dragon with 100% attack power. - Check dragon's life: - If life > 0, continue. - If life ≤ 0, game over. - If dragon's life < 40, shift to Status 2. - Otherwise, Dragon attacks the player with 100% attack power. - Check player's life: - If life > 0, return to player's attack. - If life ≤ 0, game over. Status 2: - Dragon attacks the player with 65% attack power. - Check player's life: - If life > 0, continue. - If life ≤ 0, game over. - Player attacks the dragon with 135% attack power. - Check dragon's life: - If life > 0, continue. - If life ≤ 0, game over. # Visual Patterns 1. Critical Thresholds: - Dragon life < 40 triggers status change from Status 1 to Status 2 - Life points ≤ 0 triggers game over 2. Turn Order Pattern: - Status 1: Player attack → check status shifting → Dragon attack → Player attack → ... - Status 2: Dragon attack → Player attack → Dragon attack → ...
def test(): test_cases = [ (100, 90, 10, 5, 55), (59.9, 78, 60, 26.6, 39), (1000.1, 100.79, 8.54, 50.3, 396), (63, 100, 100, 1, 62), (1000.34, 10, 11, 1001, 10), (150.33, 176.24, 23.5, 26.8, 66), (92.3, 11.1, 1, 32.3, 9), (12384.4, 13323.9, 10.1, 11.1, 2073), (11111111.223, 11847382.68, 3.3, 4.4, 3514065), (1321137281.11, 837272819.23, 55.9, 666, 726384604), ] for i, (dragon_life, player_life, dragon_attack_point, player_attack_point, expected_output) in enumerate(test_cases): try: output = solution(dragon_life, player_life, dragon_attack_point, player_attack_point) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`dragon_life`: {dragon_life}\n" f"`player_life`: {player_life}\n" f"`dragon_attack_point`: {dragon_attack_point}\n" f"`player_attack_point`: {player_attack_point}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`dragon_life`: {dragon_life}\n" f"`player_life`: {player_life}\n" f"`dragon_attack_point`: {dragon_attack_point}\n" f"`player_attack_point`: {player_attack_point}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(dragon_life: float, player_life: float, dragon_attack_point: float, player_attack_point: float) -> int: """ Build the dragon slaying game as shown in the diagram, and calculate how many life points the winner has left. Parameters: dragon_life (float): The life points of the dragon. player_life (float): The life points of the player. dragon_attack_point (float): The base attack points of the dragon. player_attack_point (float): The base attack points of the player. Returns: int: The life points of the winner (rounded down). """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": null, "Geometric Objects": [ "Arrow" ], "Mathematical Operations": [ "Flowcharting", "Conditional Branching", "Value Comparison" ], "Spatial Transformations": null, "Topological Relations": [ "Connectivity", "Connection" ] }
Direct Calculation
q19-3
def solution(dragon_life: float, player_life: float, dragon_attack_point: float, player_attack_point: float) -> int: """ Build the dragon slaying game as shown in the diagram, and calculate how many life points the winner has left. Parameters: dragon_life (float): The life points of the dragon. player_life (float): The life points of the player. dragon_attack_point (float): The base attack points of the dragon. player_attack_point (float): The base attack points of the player. Returns: int: The life points of the winner (rounded down). """ status = 1 while True: player_life -= dragon_attack_point if player_life <= 0: return int(dragon_life) if player_life < 60 and status == 1: status = 2 dragon_attack_point *= 1.2 player_attack_point *= 0.8 dragon_life -= player_attack_point if dragon_life <= 0: return int(player_life)
# Problem Description This is a turn-based battle game simulation between a player and a dragon. The game has two distinct status phases with different attack patterns. The goal is to calculate the remaining life points of whoever wins the battle (either dragon or player). The battle follows specific rules for attack power modifications and status transitions. # Visual Facts Status 1: - Dragon attacks the player with 100% attack point. - Check player's life: - If life > 0, continue. - If life ≤ 0, game over. - If player's life < 60, shift to Status 2. - Otherwise, Player attacks the dragon with 100% attack point. - Check dragon's life: - If life > 0, continue. - If life ≤ 0, game over. Status 2: - Player attacks the dragon with 80% attack point. - Check dragon's life: - If life > 0, continue. - If life ≤ 0, game over. - Dragon attacks the player with 120% attack point. - Check player's life: - If life > 0, continue. - If life ≤ 0, game over. # Visual Patterns Critical Thresholds: - In Status 1, each time the player is attacked by the dragon, we need to check if the player's life is below 60. If it is, the game will directly switch to Status 2, and the player will attack the dragon with 80% of their attack points. - Player life < 60 triggers status change from Status 1 to Status 2 - Life points ≤ 0 triggers game over - When the dragon's life is ≤ 0, return the player's life. - When the player's life is ≤ 0, return the dragon's life.
def test(): test_cases = [ (90, 100, 5, 10, 49), (78, 59.9, 26.6, 60, 1), (100.79, 1000.1, 50.3, 8.54, 396), (100, 63, 1, 100, 62), (10, 1000.34, 1001, 11, 10), (176.24, 150.33, 26.8, 23.5, 68), (11.1, 92.3, 32.3, 1, 9), (13323.9, 12384.4, 11.1, 10.1, 2080), (11847382.68, 11111111.223, 4.4, 3.3, 3514065), (837272819.23, 1321137281.11, 666, 55.9, 726384604), ] for i, (dragon_life, player_life, dragon_attack_point, player_attack_point, expected_output) in enumerate(test_cases): try: output = solution(dragon_life, player_life, dragon_attack_point, player_attack_point) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`dragon_life`: {dragon_life}\n" f"`player_life`: {player_life}\n" f"`dragon_attack_point`: {dragon_attack_point}\n" f"`player_attack_point`: {player_attack_point}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`dragon_life`: {dragon_life}\n" f"`player_life`: {player_life}\n" f"`dragon_attack_point`: {dragon_attack_point}\n" f"`player_attack_point`: {player_attack_point}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(dragon_life: float, player_life: float, dragon_attack_point: float, player_attack_point: float) -> int: """ Build the dragon slaying game as shown in the diagram, and calculate how many life points the winner has left. Parameters: dragon_life (float): The life points of the dragon. player_life (float): The life points of the player. dragon_attack_point (float): The base attack points of the dragon. player_attack_point (float): The base attack points of the player. Returns: int: The life points of the winner (rounded down). """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": null, "Geometric Objects": [ "Arrow" ], "Mathematical Operations": [ "Flowcharting", "Conditional Branching", "Value Comparison" ], "Spatial Transformations": null, "Topological Relations": [ "Connectivity", "Connection" ] }
Direct Calculation
q2
from typing import List import numpy as np def solution() -> List[List[float]]: """ generate a set of 1000 data points that match the distribution shown in the figure Returns: List[List[float]]: A 2D array of shape (1000, 2), where each row contains the x and y coordinates of a point. """ num_points = 1000 points = np.zeros((num_points, 2)) # Initialize array to hold points center_x, center_y = 0.5, 0.5 radius = 0.25 count = 0 while count < num_points: x, y = np.random.rand(2) # Generate random x, y coordinates # Check if the point is outside the circle if (x - center_x)**2 + (y - center_y)**2 >= radius**2: points[count] = [x, y] count += 1 return points.tolist()
# Problem Description The task is to generate a dataset of 1000 2D points that follows a specific distribution pattern shown in the figure. The points should be distributed within a 1x1 square area with special constraints around a circular region. The output should be a 2D array of shape (1000, 2) where each row represents the (x,y) coordinates of a point. # Visual Facts 1. The plot shows a square coordinate system with both x and y axes ranging from 0.0 to 1.0 2. Blue dots are scattered throughout the square area 3. There's an orange dashed line labeled "R=0.25" indicating a radius 4. The plot appears to have approximately 1000 points 5. Points appear to be more sparse in a circular region around (0.5, 0.5) 6. The density of points outside this circular region appears uniform # Visual Patterns 1. Distribution Pattern: - The points appear to avoid a circular region centered at (0.5, 0.5) - The circular region has a radius of 0.25 (as indicated by "R=0.25") - Outside this circular region, points appear to be uniformly distributed 2. Mathematical Constraints: - For any point (x,y), 0 ≤ x ≤ 1 and 0 ≤ y ≤ 1 (square boundary) - Points are less likely to appear within: (x-0.5)² + (y-0.5)² ≤ 0.25² - The distribution appears to be uniform random outside this circular region 3. Generation Rules: - Generate random points uniformly in the 1x1 square - Reject points that fall within the circle defined by (x-0.5)² + (y-0.5)² ≤ 0.25² - Continue generating points until 1000 valid points are obtained
import numpy as np def quartile_test(points): x_quartiles = np.percentile(points[:, 0], [25, 50, 75]) y_quartiles = np.percentile(points[:, 1], [25, 50, 75]) theoretical_quartiles = [0.2, 0.5, 0.8] x_check = np.allclose(x_quartiles, theoretical_quartiles, atol=0.1) y_check = np.allclose(y_quartiles, theoretical_quartiles, atol=0.1) return x_check and y_check def test(): try: points = solution() points = np.array(points) except Exception as e: error_message = ( f"An exception occurred while running the solution function:\n" f"Exception: '{str(e)}'" ) assert False, error_message # Test shape of output if points.shape != (1000, 2): error_message = ( f"The following Test Case failed:\n" f"`points.shape`: {points.shape}\n" f"Expected Output: (1000, 2)" ) assert False, error_message # Test exclusion zone center_x, center_y = 0.5, 0.5 radius = 0.25 distances = np.sqrt((points[:, 0] - center_x)**2 + (points[:, 1] - center_y)**2) if not np.all(distances >= radius): error_message = ( f"The following Test Case failed:\n" f"`center_point`: ({center_x}, {center_y})\n" f"`radius`: {radius}\n" f"`min_distance`: {np.min(distances)}\n" f"Points detected inside the exclusion zone" ) assert False, error_message # Test distribution uniformity if not quartile_test(points): error_message = ( f"The following Test Case failed:\n" f"`x_quartiles`: {np.percentile(points[:, 0], [25, 50, 75])}\n" f"`y_quartiles`: {np.percentile(points[:, 1], [25, 50, 75])}\n" f"`expected_quartiles`: [0.2, 0.5, 0.8]\n" f"Points distribution does not match expected uniformity" ) assert False, error_message test()
from typing import List def solution() -> List[List[float]]: """ generate a set of 1000 data points that match the distribution shown in the figure Returns: List[List[float]]: A 2D array of shape (1000, 2), where each row contains the x and y coordinates of a point. """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": [ "Concentric Arrangement" ], "Geometric Objects": [ "Point", "Coordinate System", "Circle" ], "Mathematical Operations": [ "Random Distribution" ], "Spatial Transformations": [ "Clustering" ], "Topological Relations": [ "Boundary" ] }
Direct Calculation
q2-2
from typing import List import numpy as np def solution() -> List[List[float]]: """ generate a set of 1000 data points that match the distribution shown in the figure Returns: List[List[float]]: A 2D array of shape (1000, 2), where each row contains the x and y coordinates of a point. """ num_points = 1000 points = np.zeros((num_points, 2)) # Initialize array to hold points center_x, center_y = 0.5, 0.5 radius = 0.25 count = 0 while count < num_points: x, y = np.random.rand(2) # Generate random x, y coordinates # Check if the point is inside the circle if (x - center_x)**2 + (y - center_y)**2 <= radius**2: points[count] = [x, y] count += 1 return points.tolist()
# Problem Description The task is to generate a dataset of 1000 2D points that follows a specific distribution pattern shown in the figure. The points should be distributed within a circular area with a radius of 0.25. The output should be a 2D array of shape (1000, 2) where each row represents the (x,y) coordinates of a point. # Visual Facts 1. The plot shows a square coordinate system with both x and y axes ranging from 0.0 to 1.0. 2. Blue dots are scattered throughout the square area. 3. There's an orange dashed line labeled "R=0.25" indicating a radius. 4. The plot appears to have approximately 1000 points. 5. Points are densely packed within a circular region centered at (0.5, 0.5). 6. The circular region has a radius of 0.25 (as indicated by "R=0.25"). # Visual Patterns 1. Distribution Pattern: - The points are densely packed within a circular region centered at (0.5, 0.5). - The circular region has a radius of 0.25 (as indicated by "R=0.25"). - Outside this circular region, points are non-existent. 2. Mathematical Constraints: - For any point (x,y), 0 ≤ x ≤ 1 and 0 ≤ y ≤ 1 (square boundary). - Points are more likely to appear within: (x-0.5)² + (y-0.5)² ≤ 0.25². - The distribution appears to be dense within this circular region. 3. Generation Rules: - Generate random points uniformly in the 1x1 square. - Accept points that fall within the circle defined by (x-0.5)² + (y-0.5)² ≤ 0.25². - Continue generating points until 1000 valid points are obtained.
import numpy as np def quartile_test(points): x_quartiles = np.percentile(points[:, 0], [25, 50, 75]) y_quartiles = np.percentile(points[:, 1], [25, 50, 75]) theoretical_quartiles = [0.4, 0.5, 0.6] x_check = np.allclose(x_quartiles, theoretical_quartiles, atol=0.1) y_check = np.allclose(y_quartiles, theoretical_quartiles, atol=0.1) return x_check and y_check def test(): try: points = np.array(solution()) except Exception as e: error_message = ( f"An exception occurred while running solution():\n" f"Exception: '{str(e)}'" ) assert False, error_message # Test shape of output if points.shape != (1000, 2): error_message = ( f"The following Test Case failed:\n" f"`points.shape`: {points.shape}\n" f"Expected Output: (1000, 2)" ) assert False, error_message # Test points are outside exclusion zone center_x, center_y = 0.5, 0.5 radius = 0.25 distances = np.sqrt((points[:, 0] - center_x)**2 + (points[:, 1] - center_y)**2) if not np.all(distances <= radius): invalid_points = points[distances > radius] error_message = ( f"The following Test Case failed:\n" f"`points`: Points found inside exclusion zone\n" f"Invalid points coordinates: {invalid_points}\n" f"Center: ({center_x}, {center_y}), Radius: {radius}" ) assert False, error_message # Test uniform distribution via quartiles if not quartile_test(points): x_quartiles = np.percentile(points[:, 0], [25, 50, 75]) y_quartiles = np.percentile(points[:, 1], [25, 50, 75]) theoretical_quartiles = [0.4, 0.5, 0.6] error_message = ( f"The following Test Case failed:\n" f"`points`: Distribution not uniform\n" f"Actual x quartiles: {x_quartiles}\n" f"Actual y quartiles: {y_quartiles}\n" f"Expected quartiles: {theoretical_quartiles}" ) assert False, error_message test()
from typing import List def solution() -> List[List[float]]: """ generate a set of 1000 data points that match the distribution shown in the figure Returns: List[List[float]]: A 2D array of shape (1000, 2), where each row contains the x and y coordinates of a point. """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": [ "Concentric Arrangement" ], "Geometric Objects": [ "Point", "Coordinate System", "Circle" ], "Mathematical Operations": [ "Random Distribution" ], "Spatial Transformations": [ "Clustering" ], "Topological Relations": [ "Boundary" ] }
Direct Calculation
q2-3
from typing import List import numpy as np def solution() -> List[List[float]]: """ generate a set of 1000 data points that match the distribution shown in the figure Returns: List[List[float]]: A 2D array of shape (1000, 2), where each row contains the x and y coordinates of a point. """ num_points = 1000 points = np.zeros((num_points, 2)) # Initialize array to hold points center_x, center_y = 0.5, 0.5 width = 0.5 # Width of the ellipse height = 0.25 # Height of the ellipse count = 0 while count < num_points: x, y = np.random.rand(2) # Generate random x, y coordinates # Check if the point is outside the ellipse if ((x - center_x)**2 / (width / 2)**2 + (y - center_y)**2 / (height / 2)**2) >= 1: points[count] = [x, y] count += 1 return points.tolist()
# Problem Description The task is to generate a dataset of 1000 2D points that follows a specific distribution pattern shown in the figure. The points should be distributed within a 1x1 square area with special constraints around an elliptical region. The output should be a 2D array of shape (1000, 2) where each row represents the (x,y) coordinates of a point. # Visual Facts 1. The plot shows a square coordinate system with both x and y axes ranging from 0.0 to 1.0. 2. Blue dots are scattered throughout the square area. 3. There's an orange dashed ellipse centered at (0.5, 0.5). 4. The major axis of the ellipse is 0.25, and the minor axis is 0.125. 5. The plot appears to have approximately 1000 points. 6. Points are non-existent within the elliptical region around (0.5, 0.5). 7. The density of points outside this elliptical region appears uniform. # Visual Patterns 1. Distribution Pattern: - The points appear to avoid an elliptical region centered at (0.5, 0.5). - The elliptical region has a major axis of 0.25 and a minor axis of 0.125. - Outside this elliptical region, points appear to be uniformly distributed. 2. Mathematical Constraints: - For any point (x,y), 0 ≤ x ≤ 1 and 0 ≤ y ≤ 1 (square boundary). - Points are less likely to appear within the ellipse defined by the equation: \[ \left(\frac{x-0.5}{0.25}\right)^2 + \left(\frac{y-0.5}{0.125}\right)^2 \leq 1 \] - The distribution appears to be uniform random outside this elliptical region. 3. Generation Rules: - Generate random points uniformly in the 1x1 square. - Reject points that fall within the ellipse defined by the equation above. - Continue generating points until 1000 valid points are obtained.
import numpy as np def quartile_test(points): x_quartiles = np.percentile(points[:, 0], [25, 50, 75]) y_quartiles = np.percentile(points[:, 1], [25, 50, 75]) theoretical_x_quartiles = [0.2, 0.5, 0.8] theoretical_y_quartiles = [0.2, 0.5, 0.8] x_check = np.allclose(x_quartiles, theoretical_x_quartiles, atol=0.1) y_check = np.allclose(y_quartiles, theoretical_y_quartiles, atol=0.1) return x_check and y_check def test(): try: points = np.array(solution()) except Exception as e: error_message = ( f"An exception occurred while generating points:\n" f"Exception: '{str(e)}'" ) assert False, error_message # Shape test if points.shape != (1000, 2): error_message = ( f"Generated points have incorrect shape:\n" f"Actual shape: {points.shape}\n" f"Expected shape: (1000, 2)" ) assert False, error_message # Exclusion zone test center_x, center_y = 0.5, 0.5 width = 0.5 # Width of the ellipse height = 0.25 # Height of the ellipse inside_points = points[((points[:, 0] - center_x)**2 / (width / 2)**2 + (points[:, 1] - center_y)**2 / (height / 2)**2) < 1] if len(inside_points) > 0: error_message = ( f"Found points inside the exclusion zone (ellipse):\n" f"Points inside exclusion zone: {inside_points}\n" f"Ellipse parameters:\n" f"Center: ({center_x}, {center_y})\n" f"Width: {width}\n" f"Height: {height}" ) assert False, error_message # Distribution test if not quartile_test(points): x_quartiles = np.percentile(points[:, 0], [25, 50, 75]) y_quartiles = np.percentile(points[:, 1], [25, 50, 75]) error_message = ( f"Points are not uniformly distributed:\n" f"Actual x quartiles: {x_quartiles}\n" f"Expected x quartiles: [0.2, 0.5, 0.8]\n" f"Actual y quartiles: {y_quartiles}\n" f"Expected y quartiles: [0.2, 0.5, 0.8]" ) assert False, error_message test()
from typing import List def solution() -> List[List[float]]: """ generate a set of 1000 data points that match the distribution shown in the figure Returns: List[List[float]]: A 2D array of shape (1000, 2), where each row contains the x and y coordinates of a point. """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": [ "Concentric Arrangement" ], "Geometric Objects": [ "Point", "Coordinate System", "Ellipse" ], "Mathematical Operations": [ "Random Distribution" ], "Spatial Transformations": [ "Clustering" ], "Topological Relations": [ "Boundary" ] }
Direct Calculation
q20
from typing import List def solution(swaps: List[str], initial_position: int) -> int: """ Determine the final position of the ball after a series of swaps. Parameters: swaps (List[str]): A list of operation ids ('A', 'B', 'C', 'D', 'E', or 'F') representing the sequence of cup swap operations. initial_position (int): The index of the cup where the ball is initially placed. (1-indexed) Returns: int: The index of the cup where the ball is finally located. (1-indexed) """ swap_operations = { 'A': (1, 2), 'B': (1, 3), 'C': (2, 3), 'D': (2, 4), 'E': (3, 4), 'F': (1, 4) } position = initial_position for swap in swaps: if swap in swap_operations: cup1, cup2 = swap_operations[swap] if position == cup1: position = cup2 elif position == cup2: position = cup1 return position
# Problem Description This is a cup-swapping puzzle where: - There are 4 cups indexed from 1 to 4 - A red ball is placed under one of the cups initially - A sequence of swap operations (A through F) is performed - We need to track the final position of the ball after all swaps are completed - Each swap operation has a predefined pattern of which cups exchange positions # Visual Facts 1. There are 6 different swap operations labeled A through F 2. Each operation involves swapping exactly two cups 3. The cups are indexed 1, 2, 3, and 4 from left to right 4. A red ball appears in different positions to show movement 5. Black arrows indicate the swap directions 6. The specific swaps are: - A: swaps cups 1↔2 - B: swaps cups 1↔3 - C: swaps cups 2↔3 - D: swaps cups 2↔4 - E: swaps cups 3↔4 - F: swaps cups 1↔4 # Visual Patterns 1. Position Pattern: - The ball moves with its cup during a swap - Each swap only affects two cups at a time - The other two cups remain in their positions during each swap 2. Operation Properties: - Each operation is reversible (doing the same swap twice returns to original state) - Multiple swaps can be chained together - The ball's final position depends on both: * Its initial position * The sequence of swaps performed
def test(): test_cases = [ (['A'], 1, 2), (['A'], 3, 3), (['B'], 3, 1), (['A', 'B', 'C'], 2, 2), (['D', 'E', 'A', 'C', 'B'], 4, 3), (['E', 'C', 'A', 'B', 'C', 'E', 'D'], 3, 3), (['A', 'C', 'E', 'D'], 1, 2), (['A', 'E', 'D', 'A', 'C', 'A', 'D', 'E', 'B'], 2, 4), (['B', 'E', 'A', 'C', 'D', 'A', 'C'], 4, 4), (['A', 'B', 'C', 'D', 'E', 'C', 'A'], 1, 4), (['B', 'E', 'A', 'C', 'D', 'A', 'C', 'A', 'C', 'E', 'B', 'A', 'D'], 4, 4), ] for i, (swaps, initial_position, expected_output) in enumerate(test_cases): original_swaps = swaps[:] try: output = solution(swaps, initial_position) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`swaps`: {original_swaps}\n" f"`initial_position`: {initial_position}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`swaps`: {original_swaps}\n" f"`initial_position`: {initial_position}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(swaps: List[str], initial_position: int) -> int: """ Determine the final position of the ball after a series of swaps. Parameters: swaps (List[str]): A list of operation ids ('A', 'B', 'C', 'D', 'E', or 'F') representing the sequence of cup swap operations. initial_position (int): The index of the cup where the ball is initially placed. (1-indexed) Returns: int: The index of the cup where the ball is finally located. (1-indexed) """
{ "Common Sense": null, "Data Structures": [ "Sequence" ], "Dynamic Patterns": null, "Geometric Objects": [ "Arrow" ], "Mathematical Operations": null, "Spatial Transformations": [ "Swapping" ], "Topological Relations": [ "Adjacency", "Connection" ] }
Iterative Calculation
q20-2
from typing import List def solution(swaps: List[str], initial_position: int) -> int: """ Determine the final position of the ball after a series of swaps. Parameters: swaps (List[str]): A list of operation ids ('A', 'B', 'C') representing the sequence of cup swap operations. initial_position (int): The index of the cup where the ball is initially placed. (1-indexed) Returns: int: The index of the cup where the ball is finally located. (1-indexed) """ swap_operations = { 'A': (1, 2), 'B': (3, 4), 'C': (2, 3), } position = initial_position for swap in swaps: if swap in swap_operations: cup1, cup2 = swap_operations[swap] if position == cup1: position = cup2 elif position == cup2: position = cup1 return position
# Problem Description This is a cup-swapping puzzle where: - There are 4 cups numbered from 1 to 4 - A red ball is placed under one of the cups initially - Three possible swap operations (A, B, C) can be performed in sequence - We need to track and return the final position of the ball after all swaps - Each operation represents a specific pair of cups exchanging positions - Positions are 1-indexed (1 to 4) # Visual Facts 1. There are exactly 3 different swap operations (A, B, C) 2. Each operation swaps exactly two adjacent cups 3. Cups are indexed 1, 2, 3, and 4 from left to right 4. A red ball appears under different cups to demonstrate movement 5. Curved arrows show the direction of swaps 6. The specific swaps are: - A: swaps cups 1↔2 - B: swaps cups 3↔4 - C: swaps cups 2↔3 # Visual Patterns 1. Position Pattern: - The ball always moves with its cup during a swap - Each swap only affects two adjacent cups - The unaffected cups remain stationary during each swap - All swaps are between adjacent positions only 2. Operation Properties: - Each swap operation is reversible (performing same swap twice restores original positions) - Swaps can be performed in sequence - The ball's final position depends on: * Its initial position (1-4) * The sequence of swaps performed (A, B, or C) 3. Mathematical Patterns: - A swap operation changes the ball's position only if it's in one of the cups being swapped - If the ball is in an unaffected cup, its position remains unchanged
def test(): test_cases = [ (['A'], 1, 2), (['A'], 3, 3), (['B'], 3, 4), (['A', 'B', 'C'], 2, 1), (['C', 'A', 'A', 'C', 'B'], 4, 3), (['B', 'C', 'A', 'B', 'C', 'B', 'A'], 3, 1), (['A', 'C', 'B', 'C'], 1, 4), (['A', 'B', 'B', 'C', 'C', 'B', 'A', 'C', 'B'], 2, 4), (['B', 'A', 'A', 'C', 'B', 'C', 'A'], 4, 3), (['A', 'B', 'C', 'B', 'A', 'C', 'B'], 1, 3), (['B', 'A', 'B', 'C', 'A', 'C', 'B', 'A', 'C', 'A', 'B', 'A', 'C'], 4, 3), ] for i, (swaps, initial_position, expected_output) in enumerate(test_cases): original_swaps = swaps[:] try: # Create a copy of swaps to preserve original input output = solution(swaps, initial_position) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`swaps`: {original_swaps}\n" f"`initial_position`: {initial_position}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`swaps`: {original_swaps}\n" f"`initial_position`: {initial_position}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(swaps: List[str], initial_position: int) -> int: """ Determine the final position of the ball after a series of swaps. Parameters: swaps (List[str]): A list of operation ids ('A', 'B', 'C') representing the sequence of cup swap operations. initial_position (int): The index of the cup where the ball is initially placed. (1-indexed) Returns: int: The index of the cup where the ball is finally located. (1-indexed) """
{ "Common Sense": null, "Data Structures": [ "Sequence" ], "Dynamic Patterns": null, "Geometric Objects": [ "Arrow" ], "Mathematical Operations": null, "Spatial Transformations": [ "Swapping" ], "Topological Relations": [ "Adjacency", "Connection" ] }
Iterative Calculation
q20-3
from typing import List def solution(swaps: List[str], initial_position: int) -> int: """ Determine the final position of the ball after a series of swaps. Parameters: swaps (List[str]): A list of operation ids ('A', 'B', 'C', 'D') representing the sequence of cup swap operations. initial_position (int): The index of the cup where the ball is initially placed. (1-indexed) Returns: int: The index of the cup where the ball is finally located. (1-indexed) """ swap_operations = { 'A': (1, 2), 'B': (1, 3), 'C': (2, 3), 'D': (3, 4) } position = initial_position for swap in swaps: if swap in swap_operations: cup1, cup2 = swap_operations[swap] if position == cup1: position = cup2 elif position == cup2: position = cup1 return position
# Problem Description This is a cup-swapping puzzle where: - There are 4 cups numbered 1 to 4 arranged in a row - A red ball is placed under one of the cups initially - A sequence of swap operations (A through D) is performed - We need to track and return the final position of the ball - Each operation represents a specific pair of cups being swapped - The positions are 1-indexed (1 through 4) # Visual Facts 1. There are 4 different swap operations labeled A through D 2. Each operation involves swapping exactly two adjacent or non-adjacent cups 3. The cups are numbered 1, 2, 3, and 4 from left to right 4. Curved arrows show which cups are swapped in each operation 5. The specific swaps shown are: - A: swaps cups 1↔2 - B: swaps cups 1↔3 - C: swaps cups 2↔3 - D: swaps cups 3↔4 6. A red ball is used to demonstrate the movement # Visual Patterns 1. Ball Movement Pattern: - The ball always moves with its cup during a swap - Only the two cups involved in the swap can change positions - Other cups remain stationary during each swap 2. Operation Properties: - Each swap operation is symmetric (reversible) - The same swap performed twice returns cups to their original positions - The ball's final position depends on: * Its initial position * The sequence of swaps performed
def test(): test_cases = [ (['A'], 1, 2), (['A'], 3, 3), (['B'], 3, 1), (['A', 'B', 'D', 'C'], 2, 4), (['C', 'A', 'A', 'C', 'B'], 1, 3), (['B', 'C', 'A', 'B', 'D', 'C', 'B', 'A'], 3, 2), (['A', 'C', 'B', 'C'], 1, 1), (['A', 'B', 'B', 'C', 'C', 'B', 'A', 'C', 'B'], 2, 2), (['B', 'A', 'A', 'D', 'C', 'B', 'C', 'A'], 3, 1), (['A', 'B', 'C', 'B', 'D', 'A', 'C', 'B'], 1, 1), (['B', 'A', 'B', 'C', 'A', 'C', 'D', 'B', 'A', 'C', 'A', 'D', 'B', 'A', 'C'], 2, 2), ] for i, (swaps, initial_position, expected_output) in enumerate(test_cases): try: output = solution(swaps, initial_position) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`swaps`: {swaps}\n" f"`initial_position`: {initial_position}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`swaps`: {swaps}\n" f"`initial_position`: {initial_position}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(swaps: List[str], initial_position: int) -> int: """ Determine the final position of the ball after a series of swaps. Parameters: swaps (List[str]): A list of operation ids ('A', 'B', 'C', 'D') representing the sequence of cup swap operations. initial_position (int): The index of the cup where the ball is initially placed. (1-indexed) Returns: int: The index of the cup where the ball is finally located. (1-indexed) """
{ "Common Sense": null, "Data Structures": [ "Sequence" ], "Dynamic Patterns": null, "Geometric Objects": [ "Arrow" ], "Mathematical Operations": null, "Spatial Transformations": [ "Swapping" ], "Topological Relations": [ "Adjacency", "Connection" ] }
Iterative Calculation
q21
from math import gcd def solution(x: int, y: int) -> str: """ Determine the first laser receiver encountered by the laser in the square area Parameters: x (int): The length of x. y (int): The length of y. Returns: str: The identifier of the first laser receiver encountered by the laser. ('A', 'B', or, 'C') """ g = gcd(x, y) x = (x / g) % 2 y = (y / g) % 2 return 'B' if x and y else 'A' if x else 'C'
# Problem Description This is a laser path prediction problem in a square grid where: - A laser emitter shoots a beam from the bottom-left corner - The beam reflects off the walls following the law of reflection - There are three receivers (A, B, C) at different corners - We need to determine which receiver the laser will hit first based on given x and y coordinates - The coordinates (x,y) define the initial trajectory angle of the laser beam # Visual Facts 1. Physical Layout: - Square-shaped area with reflective boundaries (marked by diagonal lines) - Laser emitter at bottom-left corner - Receiver A at bottom-right corner - Receiver B at top-right corner - Receiver C at top-left corner 2. Path Visualization: - Green arrows show the laser path - Orange line marked 'x' along bottom - Blue line marked 'y' along right side - Laser follows a zigzag pattern - Path reflects off boundaries maintaining equal angles # Visual Patterns 1. Mathematical Properties: - The ratio y/x determines the initial angle of the laser - The laser path forms a repeating pattern based on x and y values - GCD reduction pattern: (x,y) can be reduced to lowest terms 2. Path Determination Rules: - When x is even and y is odd: Laser reaches receiver C - When x is odd and y is even: Laser reaches receiver A - When both x and y are odd: Laser reaches receiver B - When both x and y are even: Laser reaches receiver C (after GCD reduction) 3. Geometric Patterns: - Each reflection maintains the same angle with the boundary - The path forms a regular pattern that depends on the parity of x and y - The final destination is determined by how many reflections occur before hitting a corner - The GCD reduction doesn't change the final destination but simplifies the calculation
def test(): test_cases = [ (2, 1, 'C'), (3, 1, 'B'), (3, 2, 'A'), (3, 3, 'B'), (4, 1, 'C'), (4, 2, 'C'), (4, 3, 'C'), (4, 4, 'B'), (5, 1, 'B'), (5, 2, 'A'), ] for i, (x, y, expected_output) in enumerate(test_cases): try: output = solution(x, y) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`x`: {x}\n" f"`y`: {y}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`x`: {x}\n" f"`y`: {y}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(x: int, y: int) -> str: """ Determine the first laser receiver encountered by the laser in the square area Parameters: x (int): The length of x. y (int): The length of y. Returns: str: The identifier of the first laser receiver encountered by the laser. ('A', 'B', or, 'C') """
{ "Common Sense": null, "Data Structures": [ "Path" ], "Dynamic Patterns": [ "Zigzag", "Mirror Reflection" ], "Geometric Objects": [ "Point", "Arrow", "Square", "Line Segment", "Line" ], "Mathematical Operations": null, "Spatial Transformations": null, "Topological Relations": [ "Boundary", "Intersection" ] }
Validation
q21-2
from math import gcd def solution(x: int, y: int) -> str: """ Determine the first laser receiver encountered by the laser in the square area Parameters: x (int): The length of x. y (int): The length of y. Returns: str: The identifier of the first laser receiver encountered by the laser. ('A', 'B', or, 'C') """ g = gcd(x, y) x = (x / g) % 2 y = (y / g) % 2 return 'A' if x and y else 'B' if x else 'C'
# Problem Description This is a laser path prediction problem in a square grid where: - A laser emitter shoots a beam from the top-left corner - The beam reflects off the walls following the law of reflection - There are three receivers (A, B, C) at different corners - We need to determine which receiver the laser will hit first based on given x and y coordinates - The coordinates (x,y) define the initial trajectory angle of the laser beam # Visual Facts 1. Physical Layout: - Square-shaped area with reflective boundaries (marked by diagonal lines) - Laser emitter at top-left corner - Receiver A at bottom-right corner - Receiver B at top-right corner - Receiver C at top-left corner 2. Path Visualization: - Green arrows show the laser path - Orange line marked 'x' along top - Blue line marked 'y' along right side - Laser follows a zigzag pattern - Path reflects off boundaries maintaining equal angles # Visual Patterns 1. Mathematical Properties: - The ratio y/x determines the initial angle of the laser - The laser path forms a repeating pattern based on x and y values - GCD reduction pattern: (x,y) can be reduced to lowest terms 2. Path Determination Rules: - When x is even and y is odd: Laser reaches receiver C - When x is odd and y is even: Laser reaches receiver B - When both x and y are odd: Laser reaches receiver A - When both x and y are even: Laser reaches receiver C (after GCD reduction) 3. Geometric Patterns: - Each reflection maintains the same angle with the boundary - The path forms a regular pattern that depends on the parity of x and y - The final destination is determined by how many reflections occur before hitting a corner - The GCD reduction doesn't change the final destination but simplifies the calculation
def test(): test_cases = [ (2, 1, 'C'), (3, 1, 'A'), (3, 2, 'B'), (3, 3, 'A'), (4, 1, 'C'), (4, 2, 'C'), (4, 3, 'C'), (4, 4, 'A'), (5, 1, 'A'), (5, 2, 'B'), ] for i, (x, y, expected_output) in enumerate(test_cases): try: output = solution(x, y) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`x`: {x}\n" f"`y`: {y}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`x`: {x}\n" f"`y`: {y}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(x: int, y: int) -> str: """ Determine the first laser receiver encountered by the laser in the square area Parameters: x (int): The length of x. y (int): The length of y. Returns: str: The identifier of the first laser receiver encountered by the laser. ('A', 'B', or, 'C') """
{ "Common Sense": null, "Data Structures": [ "Path" ], "Dynamic Patterns": [ "Zigzag", "Mirror Reflection" ], "Geometric Objects": [ "Point", "Arrow", "Square", "Line Segment", "Line" ], "Mathematical Operations": null, "Spatial Transformations": null, "Topological Relations": [ "Boundary", "Intersection" ] }
Validation
q22
def solution(numbers: list[int]) -> int: """ Based on the visual examples provided, calculate the total distance required to perform the operations Input: - numbers: A list of integers representing a sequence of numbers. (len(numbers) >= 1) Output: - An integer representing the total distance required to perform the operations """ steps = 0 current_position = numbers.index(min(numbers)) for num in range(1, len(numbers) + 1): index = numbers.index(num) steps += abs(index - current_position) current_position = index return steps
# Problem Description This is a card stacking problem where we need to: 1. Take a sequence of numbered cards arranged horizontally 2. Stack them vertically in descending order (largest number on top) 3. Calculate the total "distance" cost of all moves required to achieve this arrangement 4. Each move involves taking a stack (single card or multiple cards) and moving it to combine with another card/stack # Visual Facts 1. Input is represented as horizontal sequence of numbered cards 2. Final output is always a vertical stack with numbers in descending order (largest to smallest) 3. Distance starts at 0 4. Cards can be moved individually or as stacks 5. Each move adds to the total distance 6. In both examples, the final arrangement is identical (4,3,2,1 from top to bottom) 7. First example starts with [2,3,1,4] and ends with distance=5 8. Second example starts with [4,3,2,1] and ends with distance=3 9. Distance increments differ between examples (Example 1: +2,+1,+2; Example 2: +1,+1,+1) 10. Example 1: Initial sequence: [2] [3] [1] [4] Step 1: [2, 1] [3] [] [4] Explanation: The "1" moves below "2", and the distance moved is 2. distance=distance+2=2 Step 2: [] [3, 2, 1] [] [4] Explanation: The stack [2, 1] moves below "3", and the distance moved is 1. distance=distance+1=3 Step 3: [] [] [] [4, 3, 2, 1] Explanation: The stack [3, 2, 1] moves below "4", and the distance moved is 2. distance=distance+2=5 Result: All numbers are stacked vertically in descending order: [4, 3, 2, 1]. The total distance moved is 5. # Visual Patterns 1. Movement Rules: - Cards can only be stacked in descending order (larger numbers on top) - When moving cards, you can move either a single card or an already-formed stack - Each move must result in a valid stack (descending order) - The first card to move is the smallest card(min(cards)). 2. Distance Calculation Rules: - Distance increases based on the horizontal gap between positions - When moving cards/stacks between adjacent positions, distance = 1 - When moving cards/stacks across multiple positions, distance = number of positions crossed - Distance is measured from the source position to destination position 3. Strategy Patterns: - From the card numberd 1, we move it to the card numbered 2, forming a stack [2, 1] - Then we move the stack to the card numbered 3, forming a stack [3, 2, 1], and so on. - For the first example, we move [1] to [2], cost a distance of 2. then [2, 1] to [3], cost a distance of 1. and then [3, 2, 1] to [4], cost a distance of 2. Total distance is 5. 4. Card number pattern. - The card numbers range from 1 to len(cards) - In each round, the number to find is the number found in the previous round plus 1. For example: In the first round, find 2 and move 1 below 2. In the second round, find 3 and move [2, 1] below 3. In the third round, find 4 and move [3, 2, 1] below 4. In the fourth round, find 5 and move [4, 3, 2, 1] below 5. And so on.
def test(): test_cases = [ ([2, 3, 1, 4], 5), ([1, 2, 3, 4], 3), ([4, 3, 2, 1], 3), ([3, 1, 4, 2], 7), ([1], 0), ([2, 1], 1), ([15, 2, 9, 5, 13, 6, 7, 12, 1, 4, 3, 10, 11, 14, 8], 86), ([5, 3, 2, 1, 4, 6], 14), ([15, 2, 9, 5, 4, 6, 7, 12, 1, 13, 3, 10, 11, 14, 8], 80), ] for numbers, expected_output in test_cases: original_numbers = numbers[:] try: output = solution(numbers) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`numbers`: {original_numbers}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`numbers`: {original_numbers}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(numbers: list[int]) -> int: """ Based on the visual examples provided, calculate the total distance required to perform the operations Input: - numbers: A list of integers representing a sequence of numbers. (len(numbers) >= 1) Output: - An integer representing the total distance required to perform the operations """
{ "Common Sense": null, "Data Structures": [ "Sequence" ], "Dynamic Patterns": null, "Geometric Objects": null, "Mathematical Operations": [ "Sorting", "Value Comparison" ], "Spatial Transformations": [ "Translation", "Stacking" ], "Topological Relations": [ "Adjacency" ] }
Iterative Calculation
q22-2
def solution(cards: list[int]) -> int: """ Based on the visual examples provided, calculate the total effort required to sequentially stack the given cards. Input: - cards: A list of integers representing a sequence of cards. (len(cards) >= 1) Output: - An integer representing the total effort required to fully stack the cards in descending order. """ effort = 0 current_position = cards.index(min(cards)) for num in range(1, len(cards) + 1): index = cards.index(num) s = abs(index - current_position) effort += s*(num-1) current_position = index return effort
# Problem Description This problem involves stacking a sequence of numbered cards in descending order (largest number on top) from a given horizontal arrangement. The goal is to calculate the total effort required to achieve this vertical stack. The effort is calculated based on the distance moved and the weight of the stack being moved. # Visual Facts 1. **Initial Setup**: Cards are arranged horizontally in a sequence. 2. **Final Goal**: Cards must be stacked vertically in descending order (largest number on top). 3. **Distance**: The horizontal distance moved by the cards or stacks during each step. 4. **Effort**: Calculated as the product of the weight of the stack being moved and the distance moved. 5. **Weight**: The current step number. 6. **Steps**: Each step involves moving a card or a stack of cards to form a larger stack. 7. **Examples**: Initial sequence: [2] [3] [1] [4] Step 1: [2, 1] [3] [] [4] Explanation: The "1" moves below "2", and the distance moved is 2. weight = step_idx = 1, effort += weight * distance = 1 * 2 = 2 Step 2: [] [3, 2, 1] [] [4] Explanation: The stack [2, 1] moves below "3", and the distance moved is 1. weight = step_idx = 2, effort += weight * distance = 1 * 2 = 4 Step 3: [] [] [] [4, 3, 2, 1] Explanation: The stack [3, 2, 1] moves below "4", and the distance moved is 2. weight = step_idx = 3, effort += weight * distance = 2 * 3 = 10 Result: All numbers are stacked vertically in descending order: [4, 3, 2, 1]. The total effort is 10. # Visual Patterns 1. **Movement Rules**: - Cards can only be stacked in descending order. - Moves can involve a single card or an already-formed stack. - Each move must result in a valid descending order stack. 2. **Distance Calculation**: - Distance is the number of positions crossed horizontally. - The distance is the absolute difference between the current position and the target position index. 3. **Effort Calculation**: - Weight is the current step number. - Effort for each move is calculated as the product of the weight and the distance moved. - For example, if it's the first time moving the cards, the weight is 1; if it's the third time moving the cards, the weight is 3. 4. **Step to solve**: 1. Identify the smallest card,this card will be the first one to move, and its corresponding index is current_position = cards.index(min(cards)). 2. Then, begin iterating through cards, with number in range(1, len(cards) + 1). 3. Find the index of the current card being traversed: index = cards.index(num). 4. Calculate the distance: distance = abs(index - current_position). 5. Add the calculated distance to the total effort: effort += distance * (num-1). 6. Update the current_position to the new position after moving the card: current_position = index.
def test(): test_cases = [ ([2, 3, 1, 4], 10), ([1, 2, 3, 4], 6), ([4, 3, 2, 1], 6), ([3, 1, 4, 2], 14), ([1], 0), ([2, 1], 1), ([15, 2, 9, 5, 13, 6, 7, 12, 1, 4, 3, 10, 11, 14, 8], 701), ([5, 3, 2, 1, 4, 6], 53), ([15, 2, 9, 5, 4, 6, 7, 12, 1, 13, 3, 10, 11, 14, 8], 619), ] for cards, expected_output in test_cases: original_cards = cards[:] # Save original input try: output = solution(cards) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`cards`: {original_cards}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`cards`: {original_cards}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(cards: list[int]) -> int: """ Based on the visual examples provided, calculate the total effort required to sequentially stack the given cards. Input: - cards: A list of integers representing a sequence of cards. (len(cards) >= 1) Output: - An integer representing the total effort required to fully stack the cards in descending order. """
{ "Common Sense": null, "Data Structures": [ "Sequence" ], "Dynamic Patterns": null, "Geometric Objects": null, "Mathematical Operations": [ "Sorting", "Value Comparison" ], "Spatial Transformations": [ "Translation", "Stacking" ], "Topological Relations": [ "Adjacency" ] }
Iterative Calculation
q22-3
def solution(cards: list[int]) -> int: """ Based on the visual examples provided, calculate the total distance required to sequentially stack the given cards. Input: - cards: A list of integers representing a sequence of cards. (len(cards) >= 1) Output: - An integer representing the total distance required to fully stack the cards in descending order. """ steps = 0 position = cards.index(min(cards)) for num in range(len(cards), 0, -1): index = cards.index(num) steps += abs(index - position) return steps
# Problem Description This is a card stacking problem where we need to: 1. Take a sequence of numbered cards arranged horizontally 2. Stack them vertically in ascending order (smallest number on top) 3. Calculate the total "distance" cost of all moves required to achieve this arrangement 4. Each move involves taking a card and moving it to combine with another card/stack # Visual Facts 1. Input is represented as horizontal sequence of numbered cards 2. Final output is always a vertical stack with numbers in ascending order (smallest to largest) 3. Distance starts at 0 4. Each move adds to the total distance 5. Example 1: Initial sequence: [2] [3] [1] [4] Step 1: [] [3] [1, 2] [4] Explanation: The "2" moves below "1", and the distance moved is 2. distance=distance+2=2 Step 2: [] [] [1, 2, 3] [4] Explanation: The "3" moves below stack [1, 2], and the distance moved is 1. distance=distance+1=3 Step 3: [] [] [1, 2, 3, 4] [] Explanation: The "4" moves below stack [3, 2, 1] , and the distance moved is 2. distance=distance+2=5 Result: All numbers are stacked vertically in ascending order: [1, 2, 3, 4]. The total distance moved is 5. # Visual Patterns 1. Movement Rules: - Cards can only be stacked in ascending order (smaller numbers on top) - Each step moves only one card. - Each move must result in a valid stack (ascending order) - After determining the position of the smallest card, move the other cards in order to place them below the smallest card. 2. Distance Calculation Rules: - The distance is the absolute difference between the current position and the target position index. 3. Step to solve: 1. First, find the index of the smallest card: min_position = cards.index(min(cards)). After that, all the other cards will be moved to this position. 2. Once the min_position is determined, it will not be changed. 3. Then, begin iterating through cards, with number in range(1, len(cards) + 1). 4. Find the index of the current card being traversed: index = cards.index(num). 5. Calculate the distance: distance += abs(index - min_position).
def test(): test_cases = [ ([2, 3, 1, 4], 4), ([1, 2, 3, 4], 6), ([4, 3, 2, 1], 6), ([3, 1, 4, 2], 4), ([1], 0), ([2, 1], 1), ([15, 2, 9, 5, 13, 6, 7, 12, 1, 4, 3, 10, 11, 14, 8], 57), ([5, 3, 2, 1, 4, 6], 9), ([15, 2, 9, 5, 4, 6, 7, 12, 1, 13, 3, 10, 11, 14, 8], 57), ] for test_case in test_cases: cards = test_case[0][:] # Create a copy of input expected_output = test_case[1] try: output = solution(cards) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`cards`: {test_case[0]}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`cards`: {test_case[0]}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(cards: list[int]) -> int: """ Based on the visual examples provided, calculate the total distance required to sequentially stack the given cards. Input: - cards: A list of integers representing a sequence of cards. (len(cards) >= 1) Output: - An integer representing the total distance required to fully stack the cards in descending order. """
{ "Common Sense": null, "Data Structures": [ "Sequence" ], "Dynamic Patterns": null, "Geometric Objects": null, "Mathematical Operations": [ "Sorting", "Value Comparison" ], "Spatial Transformations": [ "Translation", "Stacking" ], "Topological Relations": [ "Adjacency" ] }
Iterative Calculation
q23
from typing import List def solution(commands: List[str]) -> List[List[int]]: """ Given a series of commands, transform the color of a matrix according to the rules shown in the image. Input: - command: A list of strings, where each string is a command that modifies the matrix. For example: ['A', 'B', 'E']. Output: - A 3x3 matrix of integers, where each integer represents the color of the cell in the matrix. 1 represents white, 0 represents black. """ matrix = [[1] * 3 for _ in range(3)] for command in commands: if command == 'A': for i in range(3): matrix[i][0] = 1 - matrix[i][0] elif command == 'B': for i in range(3): matrix[i][1] = 1 - matrix[i][1] elif command == 'C': for i in range(3): matrix[i][2] = 1 - matrix[i][2] elif command == 'D': for j in range(3): matrix[0][j] = 1 - matrix[0][j] elif command == 'E': for j in range(3): matrix[1][j] = 1 - matrix[1][j] elif command == 'F': for j in range(3): matrix[2][j] = 1 - matrix[2][j] return matrix
# Problem Description This is a matrix transformation problem where: - We have a 3x3 matrix initially filled with white cells (represented as 1) - Commands are given as letters corresponding to rows (D,E,F) or columns (A,B,C) - Each command transforms the matrix according to specific rules - The output should represent black cells as 0 and white cells as 1 # Visual Facts 1. The matrix is 3x3 with columns labeled A,B,C and rows labeled D,E,F 2. Cells can be either white or black 3. Each command is a single letter 4. Initial state is all white cells 5. The state changes after each command 6. The commands shown in sequence are: "B", "E", "C", "D", "B" 7. Each command affects multiple cells simultaneously # Visual Patterns 1. Column Command Pattern (A,B,C): - When a column command is given, it inverts all cells in that column 2. Row Command Pattern (D,E,F): - When a row command is given, it inverts all cells in that row 3. Inversion Rules: - White cells become black and black cells become white when affected 4. Command Independence: - Each command operates on the current state of the matrix - Previous command results affect the starting state for the next command - The order of commands matters
def test(): test_cases = [ { 'input': ['B'], 'expected': [[1, 0, 1], [1, 0, 1], [1, 0, 1]] }, { 'input': ['E'], 'expected': [[1, 1, 1], [0, 0, 0], [1, 1, 1]] }, { 'input': ['A'], 'expected': [[0, 1, 1], [0, 1, 1], [0, 1, 1]] }, { 'input': ['C'], 'expected': [[1, 1, 0], [1, 1, 0], [1, 1, 0]] }, { 'input': ['B', 'E'], 'expected': [[1, 0, 1], [0, 1, 0], [1, 0, 1]] }, { 'input': ['A', 'C', 'F'], 'expected': [[0, 1, 0], [0, 1, 0], [1, 0, 1]] }, { 'input': ['A', 'B', 'C', 'D', 'E', 'F'], 'expected': [[1, 1, 1], [1, 1, 1], [1, 1, 1]] }, { 'input': ['A', 'A'], 'expected': [[1, 1, 1], [1, 1, 1], [1, 1, 1]] }, { 'input': ['A', 'B', 'E', 'C', 'F'], 'expected': [[0, 0, 0], [1, 1, 1], [1, 1, 1]] }, { 'input': ['A', 'B', 'E', 'F'], 'expected': [[0, 0, 1], [1, 1, 0], [1, 1, 0]] } ] for test_case in test_cases: commands = test_case['input'] expected_output = test_case['expected'] try: output = solution(commands) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`commands`: {commands}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`commands`: {commands}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(commands: List[str]) -> List[List[int]]: """ Given a series of commands, transform the color of a matrix according to the rules shown in the image. Input: - command: A list of strings, where each string is a command that modifies the matrix. For example: ['A', 'B', 'E']. Output: - A 3x3 matrix of integers, where each integer represents the color of the cell in the matrix. 1 represents white, 0 represents black. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": null, "Geometric Objects": [ "Grid" ], "Mathematical Operations": [ "Logical Operations" ], "Spatial Transformations": [ "Mapping" ], "Topological Relations": [ "Adjacency" ] }
Iterative Calculation
q23-2
from typing import List def solution(commands: List[str], matrix: List[List[int]]) -> List[List[int]]: """ Given a series of commands, transform the numbers of a matrix according to the rules shown in the image. Input: - command: A list of strings, where each string is a command that modifies the matrix. For example: ['A', 'B', 'E']. Output: - A 2d list of integers. """ # Iterate through each command for command in commands: if command == "A": # Sort the first column in ascending order col = sorted([matrix[i][0] for i in range(3)]) for i in range(3): matrix[i][0] = col[i] elif command == "B": # Sort the second column in ascending order col = sorted([matrix[i][1] for i in range(3)]) for i in range(3): matrix[i][1] = col[i] elif command == "C": # Sort the third column in ascending order col = sorted([matrix[i][2] for i in range(3)]) for i in range(3): matrix[i][2] = col[i] elif command == "D": # Sort the first row in ascending order matrix[0] = sorted(matrix[0]) elif command == "E": # Sort the second row in ascending order matrix[1] = sorted(matrix[1]) elif command == "F": # Sort the third row in ascending order matrix[2] = sorted(matrix[2]) return matrix
# Problem Description This is a matrix transformation problem where: - We have a 3x3 matrix with initial numbers - Commands are given as letters corresponding to rows (D,E,F) or columns (A,B,C) - Each command rearranges numbers within the specified row or column - The goal is to transform the matrix according to the rules shown in the sequence # Visual Facts 1. The matrix is 3x3 with columns labeled A,B,C and rows labeled D,E,F 2. Initial matrix contains numbers 1-9 3. Each command is a single letter 4. Commands shown are: "B", "E", "C", "D", "B" 5. Each command affects either an entire row or column 6. Affected cells are highlighted in green after each transformation 7. Numbers only move within their designated row or column # Visual Patterns 1. Column Command Pattern (A,B,C): - When a column command is given, numbers in that column are sorted in ascending order from top to bottom - Example: Command "B" transforms column B from [6,5,7] to [5,6,7] 2. Row Command Pattern (D,E,F): - When a row command is given, numbers in that row are sorted in ascending order from left to right - Example: Command "E" transforms row E from [3,6,4] to [3,4,6] 3. Sorting Rules: - Sorting is always in ascending order - For columns: top to bottom ascending - For rows: left to right ascending 4. Operation Rules: - Each command operates independently - Numbers only move within their assigned row or column - Original positions of unaffected cells remain unchanged - The order of commands matters as each transformation builds on the previous state
def test(): test_cases = [ { 'commands': ['B'], 'matrix': [[7, 1, 8],[1, 1, 3],[7, 5, 9]], 'expected': [[7, 1, 8], [1, 1, 3], [7, 5, 9]] }, { 'commands': ['E'], 'matrix': [[3, 7, 2],[6, 9, 7],[4, 7, 8]], 'expected': [[3, 7, 2], [6, 7, 9], [4, 7, 8]] }, { 'commands': ['A'], 'matrix': [[4, 9, 6],[8, 3, 1],[3, 6, 7]], 'expected': [[3, 9, 6], [4, 3, 1], [8, 6, 7]] }, { 'commands': ['C'], 'matrix': [[4, 5, 6],[8, 1, 2],[3, 9, 7]], 'expected': [[4, 5, 2], [8, 1, 6], [3, 9, 7]] }, { 'commands': ['B', 'E'], 'matrix': [[1, 2, 3],[4, 5, 6],[7, 8, 9]], 'expected': [[1, 2, 3], [4, 5, 6], [7, 8, 9]] }, { 'commands': ['A', 'C', 'F'], 'matrix': [[4, 5, 6], [8, 1, 2], [3, 9, 7]], 'expected': [[3, 5, 2], [4, 1, 6], [7, 8, 9]] }, { 'commands': ['A', 'B', 'C', 'D', 'E', 'F'], 'matrix': [[4, 5, 6], [8, 1, 2], [3, 9, 7]], 'expected': [[1, 2, 3], [4, 5, 6], [7, 8, 9]] }, { 'commands': ['A', 'A'], 'matrix': [[4, 5, 6], [8, 1, 2], [3, 9, 7]], 'expected': [[3, 5, 6], [4, 1, 2], [8, 9, 7]] }, { 'commands': ['A', 'B', 'E', 'C', 'F'], 'matrix': [[2, 3, 5], [7, 9, 1], [4, 6, 8]], 'expected': [[2, 3, 5], [1, 4, 6], [7, 8, 9]] }, { 'commands': ['A', 'B', 'E', 'F'], 'matrix': [[2, 3, 5], [7, 9, 1], [4, 6, 8]], 'expected': [[2, 3, 5], [1, 4, 6], [7, 8, 9]] } ] for test_case in test_cases: commands = test_case['commands'] matrix = test_case['matrix'] expected_output = test_case['expected'] try: output = solution(commands, matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`commands`: {commands}\n" f"`matrix`: {matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`commands`: {commands}\n" f"`matrix`: {matrix}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(commands: List[str], matrix: List[List[int]]) -> List[List[int]]: """ Given a series of commands, transform the numbers of a matrix according to the rules shown in the image. Input: - command: A list of strings, where each string is a command that modifies the matrix. For example: ['A', 'B', 'E']. Output: - A 2d list of integers. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": null, "Geometric Objects": [ "Grid" ], "Mathematical Operations": [ "Value Comparison", "Sorting" ], "Spatial Transformations": [ "Shifting" ], "Topological Relations": [ "Adjacency" ] }
Iterative Calculation
q23-3
from typing import List def solution(commands: List[str], matrix: List[List[int]]) -> List[List[int]]: """ Given a series of commands, transform the numbers of a matrix according to the rules shown in the image. Input: - command: A list of strings, where each string is a command that modifies the matrix. For example: ['A', 'B', 'E']. Output: - A 2d list of integers. """ # Iterate through each command for command in commands: if command == "A": # Convert the first column numbers to their opposites for i in range(3): matrix[i][0] = -matrix[i][0] elif command == "B": # Convert the second column numbers to their opposites for i in range(3): matrix[i][1] = -matrix[i][1] elif command == "C": # Convert the third column numbers to their opposites for i in range(3): matrix[i][2] = -matrix[i][2] elif command == "D": # Convert the first row numbers to their opposites matrix[0] = [-x for x in matrix[0]] elif command == "E": # Convert the second row numbers to their opposites matrix[1] = [-x for x in matrix[1]] elif command == "F": # Convert the third row numbers to their opposites matrix[2] = [-x for x in matrix[2]] return matrix
# Problem Description This is a matrix transformation problem where: - We have a 3x3 matrix with initial numbers - Commands are given as letters corresponding to rows (D,E,F) or columns (A,B,C) - Each command negates (multiplies by -1) the numbers in the specified row or column - The goal is to calculate the final state of the matrix after applying all commands sequentially # Visual Facts 1. The matrix is 3x3 with columns labeled A,B,C and rows labeled D,E,F 2. Initial matrix contains these numbers: ``` 8 6 1 3 5 4 9 7 2 ``` 3. Each command is a single letter 4. Commands shown are: "B", "E", "C", "D", "B" 5. Each command affects either an entire row or column 6. Affected cells are highlighted in pink/red after each transformation 7. Only the signs of numbers change, their absolute values remain the same # Visual Patterns 1. Column Command Pattern (A,B,C): - When a column command is given, all numbers in that column are negated - Example: Command "B" changes [6,5,7] to [-6,-5,-7] 2. Row Command Pattern (D,E,F): - When a row command is given, all numbers in that row are negated - Example: Command "E" changes [3,5,4] to [-3,5,-4] 3. Sign Change Rules: - Each command toggles the signs of numbers in the affected row/column - If a number is positive, it becomes negative - If a number is negative, it becomes positive - Multiple operations on the same cell can cancel each other out
def test(): test_cases = [ { 'commands': ['B'], 'matrix': [[7, 1, 8],[1, 1, 3],[7, 5, 9]], 'expected': [[7, -1, 8], [1, -1, 3], [7, -5, 9]] }, { 'commands': ['E'], 'matrix': [[3, 7, 2],[6, 9, 7],[4, 7, 8]], 'expected': [[3, 7, 2], [-6, -9, -7], [4, 7, 8]] }, { 'commands': ['A'], 'matrix': [[4, 9, 6],[8, 3, 1],[3, 6, 7]], 'expected': [[-4, 9, 6], [-8, 3, 1], [-3, 6, 7]] }, { 'commands': ['C'], 'matrix': [[4, 5, 6],[8, 1, 2],[3, 9, 7]], 'expected': [[4, 5, -6], [8, 1, -2], [3, 9, -7]] }, { 'commands': ['B', 'E'], 'matrix': [[1, 2, 3],[4, 5, 6],[7, 8, 9]], 'expected': [[1, -2, 3], [-4, 5, -6], [7, -8, 9]] }, { 'commands': ['A', 'C', 'F'], 'matrix': [[4, 5, 6], [8, 1, 2], [3, 9, 7]], 'expected': [[-4, 5, -6], [-8, 1, -2], [3, -9, 7]] }, { 'commands': ['A', 'B', 'C', 'D', 'E', 'F'], 'matrix': [[4, 5, 6], [8, 1, 2], [3, 9, 7]], 'expected': [[4, 5, 6], [8, 1, 2], [3, 9, 7]] }, { 'commands': ['A', 'A'], 'matrix': [[4, 5, 6], [8, 1, 2], [3, 9, 7]], 'expected': [[4, 5, 6], [8, 1, 2], [3, 9, 7]] }, { 'commands': ['A', 'B', 'E', 'C', 'F'], 'matrix': [[2, 3, 5], [7, 9, 1], [4, 6, 8]], 'expected': [[-2, -3, -5], [7, 9, 1], [4, 6, 8]] }, { 'commands': ['A', 'B', 'E', 'F'], 'matrix': [[2, 3, 5], [7, 9, 1], [4, 6, 8]], 'expected': [[-2, -3, 5], [7, 9, -1], [4, 6, -8]] } ] for test_case in test_cases: try: output = solution(test_case['commands'], test_case['matrix']) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`commands`: {test_case['commands']}\n" f"`matrix`: {test_case['matrix']}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != test_case['expected']: error_message = ( f"The following Test Case failed:\n" f"`commands`: {test_case['commands']}\n" f"`matrix`: {test_case['matrix']}\n\n" f"Actual Output: {output}\n" f"Expected Output: {test_case['expected']}" ) assert False, error_message test()
from typing import List def solution(commands: List[str], matrix: List[List[int]]) -> List[List[int]]: """ Given a series of commands, transform the numbers of a matrix according to the rules shown in the image. Input: - command: A list of strings, where each string is a command that modifies the matrix. For example: ['A', 'B', 'E']. Output: - A 2d list of integers. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": null, "Geometric Objects": [ "Grid" ], "Mathematical Operations": [ "Basic Arithmetic" ], "Spatial Transformations": null, "Topological Relations": [ "Adjacency" ] }
Iterative Calculation
q24
from typing import List def solution(arrangement: List[List[int]]) -> bool: """ Determine whether the arrangement of the given puzzle pieces is valid. Input: - arrangement: A 2D list of integers, where each element represents the rotation angle for the corresponding puzzle piece. Possible angles are 0, 90, 180, or -90. Output: - A boolean value, where True indicates that the arrangement is valid and False indicates that the arrangement is invalid. """ def get_edges(angle): """ Returns the edges as a tuple (T, R, B, L) after rotating the piece by a given angle. """ edges = { 0: { 'T': 1, 'R': 1, 'B': 0, 'L': 1 }, 90: { 'T': 1, 'R': 1, 'B': 1, 'L': 0 }, 180: { 'T': 0, 'R': 1, 'B': 1, 'L': 1 }, -90: { 'T': 1, 'R': 0, 'B': 1, 'L': 1 } } return edges[angle] rows = len(arrangement) cols = len(arrangement[0]) for i in range(rows): for j in range(cols): if j < cols - 1: current_piece_edges = get_edges(arrangement[i][j]) right_piece_edges = get_edges(arrangement[i][j + 1]) if current_piece_edges['R'] == right_piece_edges['L']: return False if i < rows - 1: current_piece_edges = get_edges(arrangement[i][j]) bottom_piece_edges = get_edges(arrangement[i + 1][j]) if current_piece_edges['B'] == bottom_piece_edges['T']: return False return True
# Problem Description This is a puzzle validation problem where we need to determine if a given arrangement of puzzle pieces is valid. Each piece: - Has a rotation angle (0°, 90°, 180°, or -90°) - Has sides with either protrusions or indents - Must properly connect with adjacent pieces (protrusion must match with indent) The goal is to verify if all pieces in the arrangement fit together properly based on their rotations. # Visual Facts 1. Piece Structure: - Each puzzle piece is square-shaped with special edges - Each edge has either a protrusion or an indent - The initial piece is labeled 0 and has a specific edge configuration, where the bottom edge has an indent, and the other three edges have protrusions - Pieces can be rotated in 90-degree increments 2. Rotation Examples: - A piece with value 0 when rotated 90° becomes a piece with value 90 - Rotation values shown: 0, 90, 180, -90 3. Arrangements Shown: - 1×2 arrangement: [0, 90] - 2×2 arrangement: [[-90, 0], [180, 90]] 4. Edge Matching: - Adjacent pieces must have complementary edges (protrusion meets indent) - The sample arrangements shown are all valid configurations - Every puzzle has one indent side and three protrusion sides.For deferent rotations of puzzle, the indent side is at: 0: bottom side, 90: left side, 180: top side, -90: right side, - To sum up, let 1 to be protrusion and 0 to be indent, the status of all kind of puzzles can be defined as(T:top,R:right, B:bottom, L:left): edges = { 0: { 'T': 1, 'R': 1, 'B': 0, 'L': 1 }, 90: { 'T': 1, 'R': 1, 'B': 1, 'L': 0 }, 180: { 'T': 0, 'R': 1, 'B': 1, 'L': 1 }, -90: { 'T': 1, 'R': 0, 'B': 1, 'L': 1 } } # Visual Patterns 1. Rotation Rules: - Rotations are always in multiples of 90 degrees - The number in each piece represents its rotation from the base position 2. Connection Rules: - When two pieces are adjacent, their connecting edges must be complementary - A protrusion on one piece must meet an indent on the adjacent piece - This rule applies both horizontally and vertically 3. Validation Pattern: - Check evrey puzzle's protrusion sides whether they are adjacent with another puzzle's indent side or not adjacent with other puzzles.(e.g., [0, 90], the first puzzle's right side(for puzzle 0, the indent side is at bottom so the the other sides is protrusion) is adjacent with the second puzzle(90) and the second puzzle's left side is indent, therefore this combination is legal.)
def test(): test_cases = [ ([[-90, 0], [180, 90]], True), ([[0, 90, 90]], True), ([[90,90,90]], True), ([[180, 90, 90]], True), ([[0, 90, 90, 90, 90]], True), ([[90, 90, 90, 90, 90]], True), ([[180, 90, 90, 90, 90]], True), ([[0], [90], [180]], True), ([[90],[180],[180]], True), ([[-90],[180],[180]], True), ([[0], [-90], [180]], True), ([[180], [180], [180]], True), ([[0], [180], [180]], False), ([[0], [0]], True), ([[0, 0]], False) ] for i, (arrangement, expected_output) in enumerate(test_cases): try: output = solution(arrangement) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`arrangement`: {arrangement}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`arrangement`: {arrangement}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(arrangement: List[List[int]]) -> bool: """ Determine whether the arrangement of the given puzzle pieces is valid. Input: - arrangement: A 2D list of integers, where each element represents the rotation angle for the corresponding puzzle piece. Possible angles are 0, 90, 180, or -90. Output: - A boolean value, where True indicates that the arrangement is valid and False indicates that the arrangement is invalid. """
{ "Common Sense": [ "Puzzle" ], "Data Structures": null, "Dynamic Patterns": [ "Circular Motion" ], "Geometric Objects": [ "Angle" ], "Mathematical Operations": null, "Spatial Transformations": [ "Rotation" ], "Topological Relations": [ "Adjacency", "Connection" ] }
Validation
q24-2
from typing import List def solution(arrangement: List[List[int]]) -> bool: """ Determine whether the arrangement of the given puzzle pieces is valid. Input: - arrangement: A 2D list of integers, where each element represents the rotation angle for the corresponding puzzle piece. Possible angles are 0, 90, 180, or -90. Output: - A boolean value, where True indicates that the arrangement is valid and False indicates that the arrangement is invalid. """ def get_edges(angle): """ Returns the edges as a tuple (T, R, B, L) after rotating the piece by a given angle. """ edges = { 0: { 'T': 1, 'R': 0, 'B': 1, 'L': 1 }, 90: { 'T': 1, 'R': 1, 'B': 0, 'L': 1 }, 180: { 'T': 1, 'R': 1, 'B': 1, 'L': 0 }, -90: { 'T': 0, 'R': 1, 'B': 1, 'L': 1 } } return edges[angle] rows = len(arrangement) cols = len(arrangement[0]) for i in range(rows): for j in range(cols): if j < cols - 1: current_piece_edges = get_edges(arrangement[i][j]) right_piece_edges = get_edges(arrangement[i][j + 1]) if current_piece_edges['R'] == right_piece_edges['L']: return False if i < rows - 1: current_piece_edges = get_edges(arrangement[i][j]) bottom_piece_edges = get_edges(arrangement[i + 1][j]) if current_piece_edges['B'] == bottom_piece_edges['T']: return False return True
# Problem Description This is a puzzle piece validation problem where we need to check if a given arrangement of rotated puzzle pieces forms a valid configuration. Each puzzle piece: - Has a rotation angle (0°, 90°, 180°, or -90°) - Contains protrusions and indents on its edges - Must properly connect with adjacent pieces (protrusion must match indent) The function should return true if the arrangement creates valid connections between all adjacent pieces. # Visual Facts 1. Piece Base Configuration: - Base piece (0°) has one indent on the right side - Base piece has protrusions on top, left, and bottom sides - Each piece can be rotated in 90° increments 2. Rotations Demonstrated: - When 0° piece rotates 90° clockwise, it becomes labeled as 90 - Available rotation angles: 0°, 90°, 180°, -90° 3. Example Arrangements: - 1×2 puzzle shows [90, 180] - 2×2 puzzle shows [[0, 90], [-90, 180]] 4. Edge Configurations: - Each edge must either be a protrusion or indent - Edges must complement each other where pieces meet - All shown arrangements demonstrate valid connections # Visual Patterns 1. Rotation Effects: - 90° rotation shifts all edges clockwise - -90° rotation shifts all edges counterclockwise - 180° rotation flips both horizontal and vertical edges 2. Connection Rules: - Adjacent pieces must have complementary edges where they meet - A protrusion must connect with an indent - This applies to both horizontal and vertical adjacencies
def test(): test_cases = [ ([[-90, 0], [180, 90]], False), ([[0, 90], [-90, 180]], True), ([[90, 180, 180]], True), ([[180, 180, 180]], True), ([[-90, 180, 180]], True), ([[90, 180, 180, 180, 180]], True), ([[180, 180, 180, 180]], True), ([[-90, 180, 180, 180, 180]], True), ([[90], [180], [-90]], True), ([[180],[-90],[-90]], True), ([[0],[-90],[-90]], True), ([[0], [-90], [180]], False), ([[-90], [-90], [-90]], True), ([[90], [-90], [-90]], False), ([[90], [90]], True), ([[90, 90]], False) ] for i, (arrangement, expected_output) in enumerate(test_cases): try: output = solution(arrangement) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`arrangement`: {arrangement}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`arrangement`: {arrangement}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(arrangement: List[List[int]]) -> bool: """ Determine whether the arrangement of the given puzzle pieces is valid. Input: - arrangement: A 2D list of integers, where each element represents the rotation angle for the corresponding puzzle piece. Possible angles are 0, 90, 180, or -90. Output: - A boolean value, where True indicates that the arrangement is valid and False indicates that the arrangement is invalid. """
{ "Common Sense": [ "Puzzle" ], "Data Structures": null, "Dynamic Patterns": [ "Circular Motion" ], "Geometric Objects": [ "Angle" ], "Mathematical Operations": null, "Spatial Transformations": [ "Rotation" ], "Topological Relations": [ "Adjacency", "Connection" ] }
Validation
q24-3
from typing import List def solution(arrangement: List[List[int]]) -> bool: """ Determine whether the arrangement of the given puzzle pieces is valid. Input: - arrangement: A 2D list of integers, where each element represents the rotation angle for the corresponding puzzle piece. Possible angles are 0, 90, 180, or -90. Output: - A boolean value, where True indicates that the arrangement is valid and False indicates that the arrangement is invalid. """ def get_edges(angle): """ Returns the edges as a tuple (T, R, B, L) after rotating the piece by a given angle. """ edges = { 0: { 'T': 1, 'R': 0, 'B': 0, 'L': 1 }, 90: { 'T': 1, 'R': 1, 'B': 0, 'L': 0 }, 180: { 'T': 0, 'R': 1, 'B': 1, 'L': 0 }, -90: { 'T': 0, 'R': 0, 'B': 1, 'L': 1 } } return edges[angle] rows = len(arrangement) cols = len(arrangement[0]) for i in range(rows): for j in range(cols): if j < cols - 1: current_piece_edges = get_edges(arrangement[i][j]) right_piece_edges = get_edges(arrangement[i][j + 1]) if current_piece_edges['R'] == right_piece_edges['L']: return False if i < rows - 1: current_piece_edges = get_edges(arrangement[i][j]) bottom_piece_edges = get_edges(arrangement[i + 1][j]) if current_piece_edges['B'] == bottom_piece_edges['T']: return False return True
# Problem Description This is a puzzle validation problem where we need to check if a given arrangement of puzzle pieces forms a valid configuration. Each piece: - Has a numerical label representing its rotation (0°, 90°, 180°, or -90°) - Contains interlocking edges (protrusions and indents) - Must properly connect with adjacent pieces for a valid arrangement The solution must verify if all pieces fit together correctly considering their rotations. # Visual Facts 1. Single Piece Properties: - Base piece (0°) has specific edge configuration: * Top: Protrusion * Right: Indent * Bottom: Indent * Left: Protrusion - Pieces can be rotated in 90° increments 2. Demonstrated Arrangements: - 1×2 puzzle: Two pieces both labeled 0 - 2×2 puzzle: Top row [0,0], bottom row [90,90] 3. Edge Configurations: - Each edge must be either protrusion or indent - Connected edges must be complementary (protrusion-to-indent) - Edge pattern changes with rotation # Visual Patterns 1. Rotation Effects: - 90° rotation shifts all edges clockwise - -90° rotation shifts all edges counterclockwise - 180° rotation flips both horizontal and vertical edges 2. Matching Rules: - Adjacent pieces must have complementary connecting edges - Horizontal connections: right edge of left piece must match left edge of right piece - Vertical connections: bottom edge of top piece must match top edge of bottom piece 3. Validation Requirements: - Each internal edge (shared between pieces) must form valid connections - All pieces must be properly oriented based on their rotation values - The entire arrangement must form a complete, interlocking structure - Edge types (protrusion/indent) must align correctly after rotation
def test(): test_cases = [ ([[0, 0], [90, 90]], True), ([[0, 0], [0, 0]], True), ([[0, 0, 0]], True), ([[0, -90, -90]], True), ([[0, -90, 0, -90, 0]], True), ([[-90, -90, -90, -90, -90]], True), ([[180, 90, 90, 90, 90]], True), ([[0], [90], [0]], True), ([[90],[0],[90]], True), ([[-90],[180],[180]], True), ([[180], [-90], [180]], True), ([[180], [180], [180]], True), ([[0], [180], [180]], False), ([[0], [0]], True), ([[0, 180]], False) ] for i, (arrangement, expected_output) in enumerate(test_cases): try: output = solution(arrangement) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`arrangement`: {arrangement}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`arrangement`: {arrangement}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(arrangement: List[List[int]]) -> bool: """ Determine whether the arrangement of the given puzzle pieces is valid. Input: - arrangement: A 2D list of integers, where each element represents the rotation angle for the corresponding puzzle piece. Possible angles are 0, 90, 180, or -90. Output: - A boolean value, where True indicates that the arrangement is valid and False indicates that the arrangement is invalid. """
{ "Common Sense": [ "Puzzle" ], "Data Structures": null, "Dynamic Patterns": [ "Circular Motion" ], "Geometric Objects": [ "Angle" ], "Mathematical Operations": null, "Spatial Transformations": [ "Rotation" ], "Topological Relations": [ "Adjacency", "Connection" ] }
Validation
q25
from typing import Dict, List, Tuple def solution(rectangles: Dict[int, List[Tuple[int, int]]], rectangle_id: int) -> int: """ Calculate the trimmed area of a specified rectangle within a grid. Args: rectangles: A dictionary mapping rectangle IDs (int) to their corner coordinates. Each value is a list containing two (column, row) tuples representing the bottom-left and top-right corners respectively. Example: {1: [(0, 0), (2, 2)], 2: [(2, 0), (4, 2)]} rectangle_id: The ID of the target rectangle to calculate the trimmed area for. Returns: The trimmed area of the specified rectangle. """ # Sort rectangles by their ID (lower ID = higher priority) sorted_rectangles = sorted(rectangles.items(), key=lambda x: x[0]) # Initialize a 3x7 grid to track coverage grid = [[0] * 7 for _ in range(3)] # Fill the grid based on rectangle priority for rect_id, coords in sorted_rectangles: bottom_left, top_right = coords x1, y1 = bottom_left x2, y2 = top_right for x in range(x1, x2): for y in range(y1, y2): # Only fill the cell if it hasn't been covered by a higher-priority rectangle if grid[y][x] == 0: grid[y][x] = rect_id # Calculate the trimmed area for the given rectangle_id trimmed_area = sum(1 for y in range(3) for x in range(7) if grid[y][x] == rectangle_id) return trimmed_area
# Problem Description: - The problem involves a 3x7 grid containing rectangles that may overlap. Each rectangle has an associated priority. Higher-priority rectangles take precedence over lower-priority rectangles, and the overlapping regions are "trimmed" such that only the highest-priority rectangle occupies the overlapping cells. Given the coordinates of multiple rectangles and their respective priorities, the task is to compute the trimmed area of a specific rectangle after resolving overlaps based on priority. # Visual Facts: 1. Grid Dimensions: The grid has dimensions of 3 rows and 7 columns (3x7 grid). 2. Rectangles and IDs: Rectangles are represented as contiguous rectangular regions in the grid. Each rectangle is associated with an ID (e.g., 1, 2, 3, 4). 3. Priority Order: Each rectangle has a priority level, and a smaller id has a higher priority (e.g., 1 > 2 > 3 > 4). Higher-priority rectangles take precedence and "trim" lower-priority rectangles in overlapping regions. 4. Examples in the Image: - Example 1: Priority: 1 > 2. Rectangle 1 occupies cells (0,0) to (3,2). Rectangle 2 occupies cells (2,0) to (5,2). Trimming results in Rectangle 1 maintaining its original area, while Rectangle 2 is trimmed to exclude overlapping cells with Rectangle 1. - Example 2: Priority: 1 > 2 > 3. Rectangle 1 occupies cells (0,0) to (3,3). Rectangle 2 occupies cells (2,0) to (5,2). Rectangle 3 occupies cells (3,1) to (5,3). Trimming resolves overlaps, and each rectangle retains only the non-overlapping cells. - Example 3: Priority: 1 > 2 > 3 > 4. Four rectangles are shown, with overlapping areas resolved based on priority. Higher-priority rectangles trim overlapping areas from lower-priority ones. 5. Output Goal: The goal is to calculate the trimmed area of a specific rectangle (based on the given rectangle_id). # Visual Patterns: - Priority Resolves Overlaps: Overlaps are resolved by trimming lower-priority rectangles to exclude overlapping cells with higher-priority rectangles. - Trimming Mechanism: The area of a rectangle is reduced if its cells overlap with higher-priority rectangles. The trimmed cells are removed entirely from the lower-priority rectangle's area. - Rectangles Defined by Coordinates: Each rectangle is defined by its bottom-left and top-right coordinates in the grid. These coordinates determine the rectangular area before trimming. - Calculation of Trimmed Area: The trimmed area of a rectangle is the count of grid cells it occupies after resolving overlaps.
def test(): test_cases = [ ({1: [(0, 1), (3, 3)], 2: [(0, 0), (4, 2)], 3: [(3, 1), (5, 3)], 4: [(4, 0), (7, 2)]}, 1, 6), ({1: [(0, 1), (3, 3)], 2: [(0, 0), (4, 2)], 3: [(3, 1), (5, 3)], 4: [(4, 0), (7, 2)]}, 2, 5), ({1: [(0, 1), (3, 3)], 2: [(0, 0), (4, 2)], 3: [(3, 1), (5, 3)], 4: [(4, 0), (7, 2)]}, 3, 3), ({1: [(0, 1), (3, 3)], 2: [(0, 0), (4, 2)], 3: [(3, 1), (5, 3)], 4: [(4, 0), (7, 2)]}, 4, 5), ({1: [(0, 0), (3, 2)], 2: [(2, 0), (5, 2)]}, 1, 6), ({1: [(0, 0), (3, 2)], 2: [(2, 0), (5, 2)]}, 2, 4), ({1: [(0, 0), (3, 3)], 2: [(2, 0), (5, 2)], 3: [(3, 1), (5, 3)]}, 1, 9), ({1: [(0, 0), (3, 3)], 2: [(2, 0), (5, 2)], 3: [(3, 1), (5, 3)]}, 2, 4), ({1: [(0, 0), (3, 3)], 2: [(2, 0), (5, 2)], 3: [(3, 1), (5, 3)]}, 3, 2), ({1: [(0, 0), (3, 3)], 2: [(3, 0), (5, 2)], 3: [(5, 1), (7, 3)]}, 3, 4) ] for i, (rectangles, rectangle_id, expected_output) in enumerate(test_cases): try: output = solution(rectangles, rectangle_id) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`rectangles`: {rectangles}\n" f"`rectangle_id`: {rectangle_id}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`rectangles`: {rectangles}\n" f"`rectangle_id`: {rectangle_id}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import Dict, List, Tuple def solution(rectangles: Dict[int, List[Tuple[int, int]]], rectangle_id: int) -> int: """ Calculate the trimmed area of a specified rectangle within a grid. Args: rectangles: A dictionary mapping rectangle IDs (int) to their corner coordinates. Each value is a list containing two (column, row) tuples representing the bottom-left and top-right corners respectively. Example: {1: [(0, 0), (2, 2)], 2: [(2, 0), (4, 2)]} rectangle_id: The ID of the target rectangle to calculate the trimmed area for. Returns: The trimmed area of the specified rectangle. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": null, "Geometric Objects": [ "Rectangle", "Grid" ], "Mathematical Operations": [ "Value Comparison" ], "Spatial Transformations": [ "Truncation", "Filtering" ], "Topological Relations": [ "Overlap", "Boundary" ] }
Aggregation
q25-2
from typing import Dict, List, Tuple def solution(rectangles: Dict[int, List[Tuple[int, int]]], rectangle_id: int) -> int: """ Calculate the trimmed area of a specified rectangle within a grid. Args: rectangles: A dictionary mapping rectangle IDs (int) to their corner coordinates. Each value is a list containing two (column, row) tuples representing the bottom-left and top-right corners respectively. Example: {1: [(0, 0), (2, 2)], 2: [(2, 0), (4, 2)]} rectangle_id: The ID of the target rectangle to calculate the trimmed area for. Returns: The trimmed area of the specified rectangle. """ # Sort rectangles by their ID (higher ID = higher priority) sorted_rectangles = sorted(rectangles.items(), key=lambda x: -x[0]) # Initialize a 3x7 grid to track coverage grid = [[0] * 7 for _ in range(3)] # Fill the grid based on rectangle priority for rect_id, coords in sorted_rectangles: bottom_left, top_right = coords x1, y1 = bottom_left x2, y2 = top_right for x in range(x1, x2): for y in range(y1, y2): # Only fill the cell if it hasn't been covered by a higher-priority rectangle if grid[y][x] == 0: grid[y][x] = rect_id # Calculate the trimmed area for the given rectangle_id trimmed_area = sum(1 for y in range(3) for x in range(7) if grid[y][x] == rectangle_id) return trimmed_area
# Problem Description: - The problem involves a grid containing rectangles that may overlap. Each rectangle has an associated priority. Higher-priority rectangles take precedence over lower-priority rectangles, and the overlapping regions are "trimmed" such that only the highest-priority rectangle occupies the overlapping cells. Given the coordinates of multiple rectangles and their respective priorities, the task is to compute the trimmed area of a specific rectangle after resolving overlaps based on priority. # Visual Facts: 1. Rectangles and IDs: Rectangles are represented as contiguous rectangular regions in the grid. Each rectangle is associated with an ID (e.g., 1, 2, 3, 4). 2. Priority Order: Each rectangle has a priority level, and a higher id has a higher priority (e.g., 4 > 3 > 2 > 1). Higher-priority rectangles take precedence and "trim" lower-priority rectangles in overlapping regions. 3. Examples in the Image: - Example 1: Priority: 2 > 1 Rectangle 1 occupies cells (0,0) to (3,2). Rectangle 2 occupies cells (2,0) to (5,2). Trimming results in Rectangle 2 maintaining its original area, while Rectangle 1 is trimmed to exclude overlapping cells with Rectangle 2. - Example 2: Priority: 3 > 2 > 1. Rectangle 1 occupies cells (0,0) to (3,3). Rectangle 2 occupies cells (2,0) to (5,2). Rectangle 3 occupies cells (3,1) to (5,3). Trimming resolves overlaps, and each rectangle retains only the non-overlapping cells. - Example 3: Priority: 4 > 3 > 2 > 1. Four rectangles are shown, with overlapping areas resolved based on priority. Higher-priority rectangles trim overlapping areas from lower-priority ones. 5. Output Goal: The goal is to calculate the trimmed area of a specific rectangle (based on the given rectangle_id). # Visual Patterns: - Priority Rectangle with higher id has a higher priority. - Priority Resolves Overlaps: By keeping the integrity of higher priority rectangle(which means higher id) step by step, trim the overlap area.(e.g., starting from the top priority rectangle, keep its integrity and trim any other overlap area from lower id rectangle and repeat this operation until no overlap area exists.) - Trimming Mechanism: The area of a rectangle is reduced if its cells overlap with higher-priority rectangles. The trimmed cells are removed entirely from the lower-priority rectangle's area. - Rectangles Defined by Coordinates: Each rectangle is defined by its bottom-left and top-right coordinates in the grid. These coordinates determine the rectangular area before trimming. - Calculation of Trimmed Area: The trimmed area of a rectangle is the count of grid cells it occupies after resolving overlaps.
def test(): test_cases = [ ({1: [(0, 1), (3, 3)], 2: [(0, 0), (4, 2)], 3: [(3, 1), (5, 3)], 4: [(4, 0), (7, 2)]}, 1, 3), ({1: [(0, 1), (3, 3)], 2: [(0, 0), (4, 2)], 3: [(3, 1), (5, 3)], 4: [(4, 0), (7, 2)]}, 2, 7), ({1: [(0, 1), (3, 3)], 2: [(0, 0), (4, 2)], 3: [(3, 1), (5, 3)], 4: [(4, 0), (7, 2)]}, 3, 3), ({1: [(0, 1), (3, 3)], 2: [(0, 0), (4, 2)], 3: [(3, 1), (5, 3)], 4: [(4, 0), (7, 2)]}, 4, 6), ({1: [(0, 0), (3, 2)], 2: [(2, 0), (5, 2)]}, 1, 4), ({1: [(0, 0), (3, 2)], 2: [(2, 0), (5, 2)]}, 2, 6), ({1: [(0, 0), (3, 3)], 2: [(2, 0), (5, 2)], 3: [(3, 1), (5, 3)]}, 1, 7), ({1: [(0, 0), (3, 3)], 2: [(2, 0), (5, 2)], 3: [(3, 1), (5, 3)]}, 2, 4), ({1: [(0, 0), (3, 3)], 2: [(2, 0), (5, 2)], 3: [(3, 1), (5, 3)]}, 3, 4), ({1: [(0, 0), (3, 3)], 2: [(3, 0), (5, 2)], 3: [(5, 1), (7, 3)]}, 3, 4) ] for i, (rectangles, rectangle_id, expected_output) in enumerate(test_cases): try: output = solution(rectangles, rectangle_id) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`rectangles`: {rectangles}\n" f"`rectangle_id`: {rectangle_id}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`rectangles`: {rectangles}\n" f"`rectangle_id`: {rectangle_id}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import Dict, List, Tuple def solution(rectangles: Dict[int, List[Tuple[int, int]]], rectangle_id: int) -> int: """ Calculate the trimmed area of a specified rectangle within a grid. Args: rectangles: A dictionary mapping rectangle IDs (int) to their corner coordinates. Each value is a list containing two (column, row) tuples representing the bottom-left and top-right corners respectively. Example: {1: [(0, 0), (2, 2)], 2: [(2, 0), (4, 2)]} rectangle_id: The ID of the target rectangle to calculate the trimmed area for. Returns: The trimmed area of the specified rectangle. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": null, "Geometric Objects": [ "Rectangle", "Grid" ], "Mathematical Operations": [ "Value Comparison" ], "Spatial Transformations": [ "Truncation", "Filtering" ], "Topological Relations": [ "Overlap", "Boundary" ] }
Aggregation
q26
from typing import List def solution(rules: List[List[str]], matrix: List[List[int]]) -> bool: """ Validates whether a given matrix satisfies the specified rules. Args: rules: A 2D list of strings containing 'E' or 'N', representing equality/inequality constraints matrix: A 2D list of integers to be validated against the rules Returns: bool: True if the matrix satisfies all rules, False otherwise """ rows = len(matrix) cols = len(matrix[0]) for i in range(rows): for j in range(cols): if i < rows - 1: if rules[2 * i + 1][j] == 'E': if matrix[i][j] != matrix[i + 1][j]: return False elif rules[2 * i + 1][j] == 'N': if matrix[i][j] == matrix[i + 1][j]: return False if j < cols - 1: if rules[2 * i][j] == 'E': if matrix[i][j] != matrix[i][j + 1]: return False elif rules[2 * i][j] == 'N': if matrix[i][j] == matrix[i][j + 1]: return False return True
# Problem Description - The task involves validating a 2D matrix (matrix) with specific rules (rules). The rules matrix contains two types of constraints: E: Denotes that the elements must be equal in the matrix. N: Denotes that the elements must be not equal in the matrix. - The goal is to check whether the matrix adheres to these constraints as specified by the rules matrix. Inputs: rules: A 2D grid containing 'E' (equal) or 'N' (not equal). matrix: A 2D grid of integers. Output: A boolean indicating whether the matrix satisfies all the constraints in the rules. # Visual Facts From the image, we can observe the following explicit facts: - Example 1: - rules = [[E], [N, N], [E]] - matrix = [[1, 1], [2, 2]] - The combined result satisfies the rules: First Row: 1 and 1: Equal (corresponds to rule E, satisfied). First Column: 1 and 2: Not equal (corresponds to rule N, satisfied). Second Column: 1 and 2: Not equal (corresponds to rule N, satisfied). Second Row: 2 and 2: Equal (corresponds to rule E, satisfied). - The result is Valid. Example 2 (Valid): - rules = [[E, N], [N, N, E], [E, N]] - matrix = [[1, 1, 2], [3, 3, 2]] - The combined result satisfies the rules: First Row: 1 and 1 are E (equal), satisfying the rule. 1 and 2 are N (not equal), satisfying the rule. First Column: 1 and 3 are N (not equal), satisfying the rule. Second Column: 1 and 3 are N (not equal), satisfying the rule. Third Column: 2 and 2 are E (equal), satisfying the rule. Second Row: 3 and 3 are E (equal), satisfying the rule. 3 and 2 are N (not equal), satisfying the rule. - The result is Valid. Example 3 (Invalid): - rules = [[E, N], [N, N, E], [E, N]] - matrix = [[1, 2, 2], [3, 2, 2]] - The combined result violates the rules: First Row: 1 and 2: Not equal (violate rule E). 2 and 2: Equal (violate rule N). First Column: 1 and 3: Not equal (corresponds to rule N, satisfied). Second Column: 2 and 2: Equal, but the rule is N (not equal), violates the rule. Third Column: 2 and 2: Equal (corresponds to rule E, satisfied). Second Row: 3 and 2: Not equal (violate rule E). 2 and 2: Equal (violate rule N). - The result is Invalid. # Visual Patterns 1. Equality Rules (E): If a cell in rules is labeled E, the corresponding cells in matrix must contain the same value. 2. Inequality Rules (N): If a cell in rules is labeled N, the corresponding cells in matrix must contain different values. 3. Correspondence between rules and matrix: Horizontal Relationship: - Rule: rules[2 * i][j] - Constraint: Applies to matrix[i][j] and matrix[i][j + 1]. Vertical Relationship: - Rule: rules[2 * i + 1][j] - Constraint: Applies to matrix[i][j] and matrix[i + 1][j]. 4. The rules and matrix matrices must have consistent dimensions for the validation process. Validation Process: - For each pair of neighboring cells in matrix, check the corresponding entry in rules to validate whether the values satisfy the E or N condition. - Iterate over the entire rules matrix and check all pairs of constrained cells. 5. Invalid Scenarios: - The result is invalid if any single constraint in rules is violated in the matrix.
def test(): # Test case 1 relations = [ ['E'], ['N', 'N'], ['E'] ] filled_matrix = [ [1, 1], [2, 2] ] try: result = solution(relations, filled_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if result != True: error_message = ( f"The following Test Case failed:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Actual Output: {result}\n" f"Expected Output: True" ) assert False, error_message # Test case 2 filled_matrix = [ [1, 1], [1, 2] ] try: result = solution(relations, filled_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if result != False: error_message = ( f"The following Test Case failed:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Actual Output: {result}\n" f"Expected Output: False" ) assert False, error_message # Test case 3 relations = [ ['E'], ['E', 'E'], ['E'] ] filled_matrix = [ [1, 1], [1, 2] ] try: result = solution(relations, filled_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if result != False: error_message = ( f"The following Test Case failed:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Actual Output: {result}\n" f"Expected Output: False" ) assert False, error_message # Test case 4 filled_matrix = [ [1, 1], [1, 1] ] try: result = solution(relations, filled_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if result != True: error_message = ( f"The following Test Case failed:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Actual Output: {result}\n" f"Expected Output: True" ) assert False, error_message # Test case 5 relations = [ ['E', 'N'], ['N', 'N', 'E'], ['E', 'N'] ] filled_matrix = [ [1, 1, 3], [2, 2, 3] ] try: result = solution(relations, filled_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if result != True: error_message = ( f"The following Test Case failed:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Actual Output: {result}\n" f"Expected Output: True" ) assert False, error_message # Test case 6 filled_matrix = [ [1, 1, 3], [2, 2, 2] ] try: result = solution(relations, filled_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if result != False: error_message = ( f"The following Test Case failed:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Actual Output: {result}\n" f"Expected Output: False" ) assert False, error_message # Test case 7 relations = [ ['E', 'N','E'], ['N', 'N', 'E', 'E'], ['N', 'E', 'E'], ['E', 'N', 'E', 'N'], ['E', 'N', 'N'] ] filled_matrix = [ [1, 1, 2, 2], [3, 2, 2, 2], [3, 3, 2, 1], ] try: result = solution(relations, filled_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if result != True: error_message = ( f"The following Test Case failed:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Actual Output: {result}\n" f"Expected Output: True" ) assert False, error_message # Test case 8 filled_matrix = [ [1, 1, 2, 2], [3, 2, 2, 2], [3, 3, 2, 2], ] try: result = solution(relations, filled_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if result != False: error_message = ( f"The following Test Case failed:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Actual Output: {result}\n" f"Expected Output: False" ) assert False, error_message test()
from typing import List def solution(rules: List[List[str]], matrix: List[List[int]]) -> bool: """ Validates whether a given matrix satisfies the specified rules. Args: rules: A 2D list of strings containing 'E' or 'N', representing equality/inequality constraints matrix: A 2D list of integers to be validated against the rules Returns: bool: True if the matrix satisfies all rules, False otherwise """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": null, "Geometric Objects": null, "Mathematical Operations": [ "Value Comparison", "Logical Operations" ], "Spatial Transformations": null, "Topological Relations": [ "Adjacency" ] }
Validation
q26-2
from typing import List def solution(rules: List[List[str]], matrix: List[List[int]]) -> bool: """ Validates whether a given matrix satisfies the specified rules. Args: rules: A 2D list of strings containing 'G' or 'L', representing greater/less constraints matrix: A 2D list of integers to be validated against the rules Returns: bool: True if the matrix satisfies all rules, False otherwise """ rows = len(matrix) cols = len(matrix[0]) for i in range(rows): for j in range(cols): if i < rows - 1: if rules[2 * i + 1][j] == 'L': if matrix[i][j] >= matrix[i + 1][j]: return False elif rules[2 * i + 1][j] == 'G': if matrix[i][j] <= matrix[i + 1][j]: return False if j < cols - 1: if rules[2 * i][j] == 'L': if matrix[i][j] >= matrix[i][j + 1]: return False elif rules[2 * i][j] == 'G': if matrix[i][j] <= matrix[i][j + 1]: return False return True
# Problem Description The task involves validating a 2D matrix (`matrix`) against a set of rules (`rules`). The rules matrix contains two types of constraints: - 'G': Denotes that the element in the matrix must be greater than its adjacent element. - 'L': Denotes that the element in the matrix must be less than its adjacent element. The goal is to check whether the matrix adheres to these constraints as specified by the rules matrix. # Visual Facts From the image, we can observe the following explicit facts: 1. **Example 1**: - `rules = [[G], [L, L], [G]]` - `matrix = [[2, 1], [3, 2]]` - The combined result satisfies the rules: - 2 > 1 (G) - 2 < 3 (L) - 1 < 2 (L) - 3 > 2 (G) - The result is valid. 2. **Example 2**: - `rules = [[G, L], [L, L, G], [G, L]]` - `matrix = [[3, 2, 5], [4, 3, 4]]` - The combined result satisfies the rules: - 3 > 2 (G) - 2 < 5 (L) - 3 < 4 (L) - 2 < 3 (L) - 5 > 4 (G) - 4 > 3 (G) - 3 < 4 (L) - The result is valid. 3. **Example 3**: - `rules = [[G, G], [G, L, G], [L, L]]` - `matrix = [[3, 2, 5], [4, 3, 4]]` - The combined result does not satisfy the rules: - 3 > 2 (G) - 2 > 5 (G) violate rule G - 3 > 4 (G) violate rule G - 2 < 3 (L) - 5 > 4 (G) - 4 < 3 (L) violate rule L - 3 < 4 (L) - The result is invalid. # Visual Patterns 1. Greater Rules (G): If a cell in the rules is labeled "G," the cell to the left must be greater than the cell to the right (if the adjacent cells are in a horizontal relationship), and the cell above must be greater than the cell below (if the adjacent cells are in a vertical relationship). 2. Less Rules (L): If a cell in the rules is labeled "L," the cell to the left must be less than the cell to the right (if the adjacent cells are in a horizontal relationship), and the cell above must be less than the cell below (if the adjacent cells are in a vertical relationship). 3. Correspondence between rules and matrix: Horizontal Relationship: - Rule: rules[2 * i][j] - Constraint: Applies to matrix[i][j] and matrix[i][j + 1], compare whether matrix[i][j] is greater than matrix[i][j + 1] (G rule) or less than matrix[i][j + 1] (L rule). Vertical Relationship: - Rule: rules[2 * i + 1][j] - Constraint: Applies to matrix[i][j] and matrix[i + 1][j], compare whether matrix[i][j] is greater than matrix[i + 1][j] (G rule) or less than matrix[i + 1][j] (L rule).. 4. The rules and matrix matrices must have consistent dimensions for the validation process. Validation Process: - For each pair of neighboring cells in matrix, check the corresponding entry in rules to validate whether the values satisfy the G or L condition. - Iterate over the entire rules matrix and check all pairs of constrained cells. 5. Invalid Scenarios: - The result is invalid if any single constraint in rules is violated in the matrix.
def test(): # Test case 1 relations = [ ['G'], ['L', 'L'], ['G'] ] filled_matrix = [ [2, 1], [3, 2] ] try: output = solution(relations, filled_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != True: error_message = ( f"The following Test Case failed:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Actual Output: {output}\n" f"Expected Output: True" ) assert False, error_message # Test case 2 filled_matrix = [ [4, 2], [5, 3] ] try: output = solution(relations, filled_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != True: error_message = ( f"The following Test Case failed:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Actual Output: {output}\n" f"Expected Output: True" ) assert False, error_message # Test case 3 filled_matrix = [ [4, 5], [5, 3] ] try: output = solution(relations, filled_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != False: error_message = ( f"The following Test Case failed:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Actual Output: {output}\n" f"Expected Output: False" ) assert False, error_message # Test case 4 relations = [ ['L'], ['L', 'L'], ['G'] ] filled_matrix = [ [3, 4], [6, 5] ] try: output = solution(relations, filled_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != True: error_message = ( f"The following Test Case failed:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Actual Output: {output}\n" f"Expected Output: True" ) assert False, error_message # Test case 5 filled_matrix = [ [4, 8], [16, 12] ] try: output = solution(relations, filled_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != True: error_message = ( f"The following Test Case failed:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Actual Output: {output}\n" f"Expected Output: True" ) assert False, error_message # Test case 6 filled_matrix = [ [4, 8], [1, 12] ] try: output = solution(relations, filled_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != False: error_message = ( f"The following Test Case failed:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Actual Output: {output}\n" f"Expected Output: False" ) assert False, error_message # Test case 7 relations = [ ['G', 'L'], ['L', 'L', 'G'], ['G', 'L'] ] filled_matrix = [ [3, 2, 5], [4, 3, 4] ] try: output = solution(relations, filled_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != True: error_message = ( f"The following Test Case failed:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Actual Output: {output}\n" f"Expected Output: True" ) assert False, error_message # Test case 8 filled_matrix = [ [4, 3, 6], [5, 4, 5] ] try: output = solution(relations, filled_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != True: error_message = ( f"The following Test Case failed:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Actual Output: {output}\n" f"Expected Output: True" ) assert False, error_message # Test case 9 filled_matrix = [ [4, 3, 6], [1, 4, 5] ] try: output = solution(relations, filled_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != False: error_message = ( f"The following Test Case failed:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Actual Output: {output}\n" f"Expected Output: False" ) assert False, error_message # Test case 10 relations = [ ['L', 'L', 'L'], ['L', 'L', 'L', 'L'], ['G', 'G', 'G'], ['L', 'L', 'L', 'L'], ['L', 'L', 'L'] ] filled_matrix = [ [3, 4, 5, 6], [10, 9, 8, 7], [11, 12, 13, 14], ] try: output = solution(relations, filled_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != True: error_message = ( f"The following Test Case failed:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Actual Output: {output}\n" f"Expected Output: True" ) assert False, error_message # Test case 11 filled_matrix = [ [1, 2, 3, 4], [8, 7, 6, 5], [9, 10, 11, 12], ] try: output = solution(relations, filled_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != True: error_message = ( f"The following Test Case failed:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Actual Output: {output}\n" f"Expected Output: True" ) assert False, error_message # Test case 12 filled_matrix = [ [1, 2, 3, 0], [8, 7, 6, 5], [9, 1, 11, 12], ] try: output = solution(relations, filled_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != False: error_message = ( f"The following Test Case failed:\n" f"`rules`: {relations}\n" f"`matrix`: {filled_matrix}\n\n" f"Actual Output: {output}\n" f"Expected Output: False" ) assert False, error_message test()
from typing import List def solution(rules: List[List[str]], matrix: List[List[int]]) -> bool: """ Validates whether a given matrix satisfies the specified rules. Args: rules: A 2D list of strings containing 'G' or 'L', representing greater/less constraints matrix: A 2D list of integers to be validated against the rules Returns: bool: True if the matrix satisfies all rules, False otherwise """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": null, "Geometric Objects": null, "Mathematical Operations": [ "Value Comparison", "Logical Operations" ], "Spatial Transformations": null, "Topological Relations": [ "Adjacency" ] }
Validation
q27
from typing import Tuple def solution(n: int, initial_point: Tuple[int, int], day: int) -> int: """ Calculate the area of the blue region. Args: n: The size of the n x n grid. initial_point: A tuple (x, y) representing the starting coordinates of the blue region (1-indexed). day: The given status condition. Returns: The total area of the blue region. """ # Initialize the grid grid = [[0] * n for _ in range(n)] # Convert initial_point to 0-indexed x, y = initial_point[0] - 1, initial_point[1] - 1 # Set the initial infection point grid[x][y] = 1 # Directions for up, down, left, right directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] # Iterate for each day for _ in range(day-1): new_infections = [] for i in range(n): for j in range(n): if grid[i][j] != 1: continue # Spread the infection to adjacent cells for dx, dy in directions: ni, nj = i + dx, j + dy if 0 <= ni < n and 0 <= nj < n and grid[ni][nj] == 0: new_infections.append((ni, nj)) # Mark new infections for ni, nj in new_infections: grid[ni][nj] = 1 # Count the number of infected cells infected_cells = sum(sum(row) for row in grid) return infected_cells
# Problem Description This is a grid infection spread simulation problem. Given an n×n grid with an initial infection point, we need to calculate how many cells will be infected at the given `day`. The infection spreads to adjacent cells (up, down, left, right) each day, but cannot spread beyond the grid boundaries. # Visual Facts 1. The image shows a 6×6 grid over 4 days of infection spread 2. Initial infection point is at coordinate (3, 5) on Day 1 3. White cells represent healthy cells 4. Blue cells represent infected cells 5. Grid coordinates are labeled from 1 to 6 for both rows and columns 6. The number of infected cells per day: - Day 1: 1 cell - Day 2: 5 cells - Day 3: 12 cells - Day 4: 20 cells # Visual Patterns 1. Infection Spread Pattern: - Each infected cell spreads to its four adjacent cells (up, down, left, right) the next day - Diagonal spread is not possible - Already infected cells remain infected - Cells can't spread infection beyond grid boundaries 2. Mathematical Patterns: - Without boundary constraints, the number of newly infected cells would follow: * Day 1: 1 cell * Day 2: 4 new cells (total 5) * Day 3: 8 new cells (total 13) * Day 4: 12 new cells (total 25) - Growth is limited by: * Grid boundaries (if n=6, the coordinates of cells are 1 to 6) * Previously infected cells (can't infect already infected cells)
def test(): test_cases = [ (6, (3, 5), 1, 1), (6, (3, 5), 3, 12), (6, (3, 5), 4, 20), (9, (3, 8), 3, 12), (3, (2, 2), 3, 9), (6, (1, 6), 6, 21), (6, (1, 6), 7, 26), (6, (6, 3), 4, 15), (6, (6, 3), 5, 21), ] for grid_size, initial_point, t, expected_output in test_cases: try: output = solution(grid_size, initial_point, t) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`grid_size`: {grid_size}\n" f"`initial_point`: {initial_point}\n" f"`t`: {t}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`grid_size`: {grid_size}\n" f"`initial_point`: {initial_point}\n" f"`t`: {t}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import Tuple def solution(n: int, initial_point: Tuple[int, int], day: int) -> int: """ Calculate the area of the blue region. Args: n: The size of the n x n grid. initial_point: A tuple (x, y) representing the starting coordinates of the blue region (1-indexed). day: The given status condition. Returns: The total area of the blue region. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": [ "Exponential Increment", "Cross Pattern", "Propagation" ], "Geometric Objects": [ "Coordinate System", "Grid", "Square" ], "Mathematical Operations": [ "Counting" ], "Spatial Transformations": [ "Clustering" ], "Topological Relations": [ "Connectivity", "Adjacency", "Boundary" ] }
Expansion
q27-2
from typing import Tuple def solution(n: int, initial_point: Tuple[int, int], t: int) -> int: """ Calculate the number of infected cells after t days. Input: - n: An integer representing the size of the grid (n x n). - initial_point: A tuple (x, y) representing the coordinates of the initial infection point. (1-indexed) - t: An integer representing the elapsed time in days. Output: - An integer representing the total number of infected cells after t days. """ # Initialize the grid grid = [[0] * n for _ in range(n)] # Convert initial_point to 0-indexed x, y = initial_point[0] - 1, initial_point[1] - 1 # Set the initial infection point grid[x][y] = 1 # Directions for up, down, left, right directions = [(-1, -1), (-1, 1), (1, -1), (1, 1)] # Iterate for each day for day in range(t): new_infections = [] for i in range(n): for j in range(n): if grid[i][j] != 1: continue # Spread the infection to adjacent cells for dx, dy in directions: ni, nj = i + dx, j + dy if 0 <= ni < n and 0 <= nj < n and grid[ni][nj] == 0: new_infections.append((ni, nj)) # Mark new infections for ni, nj in new_infections: grid[ni][nj] = 1 # Count the number of infected cells infected_cells = sum(sum(row) for row in grid) return infected_cells
# Problem Description This is a grid infection spread simulation problem. Given an n×n grid with an initial infection point, we need to calculate how many cells will be infected after t days. The infection spreads following a specific diagonal pattern, unlike traditional adjacent cell spreading. # Visual Facts 1. The image shows a 6×6 grid over 4 days of infection spread 2. Initial infection point is at coordinate (3, 5) on Day 1 3. White squares represent healthy cells 4. Blue squares represent infected cells 5. Grid coordinates are labeled from 1 to 6 for both rows and columns 6. The number of infected cells per day: - Day 1: 1 cell - Day 2: 5 cells - Day 3: 10 cells - Day 4: 15 cells # Visual Patterns 1. Infection Spread Pattern: - Each infected cell spreads to its four diagonally adjacent cells (top-right, top-left, bottom-left, bottom-right) the next day - Already infected cells remain infected - Cells can't spread infection beyond grid boundaries (if n=6, the coordinates of cells are 1 to 6) 2. Mathematical Patterns: - At day 1, there is only 1 infected cell - At day 2, the 1 infected cell spreads to 4 new cells (total 5) - At day 3, the 5 infected cells spread to 5 new cells (total 10) - At day 4, the 10 infected cells spread to 5 new cells (total 15)
def test(): test_cases = [ (6, (3, 5), 0, 1), (6, (3, 5), 2, 10), (6, (3, 5), 3, 15), (9, (3, 8), 2, 10), (3, (2, 2), 2, 5), (6, (1, 6), 5, 18), (6, (1, 6), 6, 18), (6, (6, 3), 3, 12), (6, (6, 3), 4, 15), ] for n, initial_point, t, expected_output in test_cases: try: output = solution(n, initial_point, t) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`n`: {n}\n" f"`initial_point`: {initial_point}\n" f"`t`: {t}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`n`: {n}\n" f"`initial_point`: {initial_point}\n" f"`t`: {t}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import Tuple def solution(n: int, initial_point: Tuple[int, int], t: int) -> int: """ Calculate the number of infected cells after t days. Input: - n: An integer representing the size of the grid (n x n). - initial_point: A tuple (x, y) representing the coordinates of the initial infection point. (1-indexed) - t: An integer representing the elapsed time in days. Output: - An integer representing the total number of infected cells after t days. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": [ "Exponential Increment", "Cross Pattern", "Propagation" ], "Geometric Objects": [ "Coordinate System", "Grid", "Square" ], "Mathematical Operations": [ "Counting" ], "Spatial Transformations": [ "Clustering" ], "Topological Relations": [ "Connectivity", "Adjacency", "Boundary" ] }
Expansion
q27-3
from typing import Tuple def solution(n: int, initial_point: Tuple[int, int], t: int) -> int: """ Calculate the number of infected cells after t days. Input: - n: An integer representing the size of the grid (n x n). - initial_point: A tuple (x, y) representing the coordinates of the initial infection point. (1-indexed) - t: An integer representing the elapsed time in days. Output: - An integer representing the total number of infected cells after t days (day t+1). """ # Initialize the grid grid = [[0] * n for _ in range(n)] # Convert initial_point to 0-indexed x, y = initial_point[0] - 1, initial_point[1] - 1 # Set the initial infection point grid[x][y] = 1 # Directions for up, down, left, right directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] new_latents = [] # Iterate for each day for day in range(t): new_infections = [] if new_latents: for new_latent in new_latents: new_infections.append(new_latent) new_latents = [] else: for i in range(n): for j in range(n): if grid[i][j] != 1: continue # Spread the infection to adjacent cells else: for dx, dy in directions: ni, nj = i + dx, j + dy if 0 <= ni < n and 0 <= nj < n and grid[ni][nj] == 0: new_latents.append((ni, nj)) # Mark new infections for ni, nj in new_infections: grid[ni][nj] = 1 # Count the number of infected cells infected_cells = sum(sum(row) for row in grid) return infected_cells
# Problem Description This is a cellular infection spread simulation on an n×n grid. Given an initial infection point, we need to calculate the total number of infected cells after t days. The infection spreads following a specific pattern with three states: healthy, latent, and infected. This is more complex than a simple infection spread as it includes a latent period before cells become fully infected. # Visual Facts 1. Grid size is 6×6 in the example 2. Initial infection point is at (3, 5) marked on Day 1 3. Cells have three possible states: - Healthy (white) - Latent (striped blue) - Infected (solid blue) 4. Day 1: Single infected cell at (3, 5) 5. Day 2: One infected cell surrounded by latent cells 6. Day 3: Five infected cells in a cross pattern 7. Day 4: Five infected cells with latent cells around them 8. Each day's state is shown in a separate grid # Visual Patterns 1. Infection State Transition: - Healthy cells first become latent before becoming infected - Cells appear to follow a pattern: Healthy → Latent → Infected - The latent period lasts exactly one day before cells become infected 2. Spread Pattern: - Infection spreads in four directions (up, down, left, right) - No diagonal spread - Newly affected cells first enter latent state - Latent cells become infected in the next day - The spread is bounded by grid boundaries (1 to n)
def test(): test_cases = [ (6, (3, 5), 0, 1), (6, (3, 5), 2, 5), (6, (3, 5), 3, 5), (9, (3, 8), 2, 5), (3, (2, 2), 2, 5), (6, (1, 6), 5, 6), (6, (1, 6), 6, 10), (6, (6, 3), 3, 4), (6, (6, 3), 4, 9), ] for n, initial_point, t, expected_output in test_cases: try: output = solution(n, initial_point, t) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`n`: {n}\n" f"`initial_point`: {initial_point}\n" f"`t`: {t}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`n`: {n}\n" f"`initial_point`: {initial_point}\n" f"`t`: {t}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import Tuple def solution(n: int, initial_point: Tuple[int, int], t: int) -> int: """ Calculate the number of infected cells after t days. Input: - n: An integer representing the size of the grid (n x n). - initial_point: A tuple (x, y) representing the coordinates of the initial infection point. (1-indexed) - t: An integer representing the elapsed time in days. Output: - An integer representing the total number of infected cells after t days (day t+1). """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": [ "Exponential Increment", "Cross Pattern", "Propagation" ], "Geometric Objects": [ "Coordinate System", "Grid", "Square" ], "Mathematical Operations": [ "Counting" ], "Spatial Transformations": [ "Clustering" ], "Topological Relations": [ "Connectivity", "Adjacency", "Boundary" ] }
Expansion
q28
from typing import List def solution(terrain: List[int]) -> int: """ Determine the index of the terrain block where pouring water would result in the most area being covered with water. The water will quickly seep into the terrain block and will not accumulate between the blocks. Input: - terrain: A list of integers representing a series of terrain blocks with differenct heights. Output: - An integer representing the zero-based index of the identified terrain block. """ def calculate_covered_area(index: int) -> int: left = index while left > 0 and terrain[left - 1] <= terrain[left]: left -= 1 right = index while right < len(terrain) - 1 and terrain[right + 1] <= terrain[right]: right += 1 return right - left + 1 max_area = 0 best_index = 0 for i in range(len(terrain)): current_area = calculate_covered_area(i) if current_area > max_area: max_area = current_area best_index = i return best_index
# Problem Description This is a terrain water flow optimization problem where: - We have a series of terrain blocks of different heights - Water can be poured at any block - Water flows to adjacent blocks if they are at the same height or lower - Water seeps into blocks (doesn't accumulate) - Goal: Find the optimal pouring position (block index) that results in maximum water coverage area - Water flow stops when it encounters a higher block or reaches the terrain edges # Visual Facts 1. Each example shows a series of terrain blocks represented as bars 2. Heights are labeled with numbers (1-4) 3. Blue lines show water flow paths 4. Water flows both leftward and rightward from the pouring point 5. Example 1 terrain: [3,1,2,3,3,2,4] 6. Example 2 terrain: [3,1,4,3,3,2,4] 7. Both examples show water being poured at a block with height 3 8. Green text indicates the area "covered with water" # Visual Patterns 1. Water Flow Rules: - Water flows horizontally to adjacent blocks - Flow continues if next block is same height or lower - Flow stops at higher blocks - Flow stops at terrain edges 2. Coverage Pattern: - Coverage area includes the pour point and all connected blocks that can be reached - A block is reachable if there's a path of same-or-lower height blocks from pour point - Higher blocks act as barriers, splitting the flow 3. Optimization Strategy: - Pour points at higher elevations can potentially cover more area - Ideal pour points are likely at local maxima - Central locations might be advantageous as they allow flow in both directions 4. Scoring Mechanism: - Coverage is counted by number of blocks water reaches - Each block counts as 1 unit regardless of height - Example 1 shows 5 blocks covered - Example 2 shows 3 blocks covered
def test(): test_cases = [ ([3, 1, 2, 3, 3, 2, 4], [3, 4]), ([1, 2, 3, 4], 3), ([3, 2, 1, 1, 1], 0), ([1, 3, 3, 5, 3, 5, 9, 5, 1, 3, 6, 8, 6, 4, 2, 7, 9, 6, 4, 2, 8, 2, 3, 4, 5, 1, 7, 1], 11), ([1, 3, 3, 5, 9, 5, 1, 3, 6, 8, 6, 4, 2, 3, 4, 5, 1, 7, 1], 4), ([2, 5, 3, 6, 4], 1), ([8, 8, 5, 5, 3, 3, 7, 7, 5, 5, 6, 6, 3, 3, 8, 8, 6, 6, 3, 3, 1, 1, 3, 3, 4, 4, 7, 7, 9, 9], 14) ] for i, (terrain, expected_output) in enumerate(test_cases): try: output = solution(terrain) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`terrain`: {terrain}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if isinstance(expected_output, list): if output not in expected_output: error_message = ( f"The following Test Case failed:\n" f"`terrain`: {terrain}\n\n" f"Actual Output: {output}\n" f"Expected Output should be one of: {expected_output}" ) assert False, error_message else: if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`terrain`: {terrain}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(terrain: List[int]) -> int: """ Determine the index of the terrain block where pouring water would result in the most area being covered with water. The water will quickly seep into the terrain block and will not accumulate between the blocks. Input: - terrain: A list of integers representing a series of terrain blocks with differenct heights. Output: - An integer representing the zero-based index of the identified terrain block. """
{ "Common Sense": [ "Flow of Water" ], "Data Structures": null, "Dynamic Patterns": [ "Propagation" ], "Geometric Objects": [ "Rectangle" ], "Mathematical Operations": [ "Value Comparison" ], "Spatial Transformations": null, "Topological Relations": [ "Adjacency", "Boundary", "Connectivity" ] }
Direct Calculation
q29
from typing import List, Tuple def solution(n: int, chain: List[Tuple[int, int]], top_left: Tuple[int, int], bottom_right: Tuple[int, int]) -> int: """ Given a chain and a yellow region in an n x n 2D matrix, find the number of red regions that are formed. Parameters: n (int): The size of the matrix. chain (List[Tuple[int, int]]): Coordinates of each node in the chain in order. top_left (Tuple[int, int]): Coordinates of the top-left corner of the yellow region. bottom_right (Tuple[int, int]): Coordinates of the bottom-right corner of the yellow region. Returns: int: The number of red regions. """ def is_inside(x: int, y: int) -> bool: """ Check if a point is inside the yellow region """ return top_left[0] <= x <= bottom_right[0] and top_left[1] <= y <= bottom_right[1] crossings = 0 for i in range(len(chain) - 1): x1, y1 = chain[i] x2, y2 = chain[i + 1] # Check if one point is inside and the other is outside the yellow region if is_inside(x1, y1) != is_inside(x2, y2): crossings += 1 return crossings
# Problem Description This is a geometric problem involving a grid, a polyline (chain), and a rectangular region. The task is to count the number of intersections (red regions) where the polyline crosses the boundary of a specified rectangular yellow region. The polyline consists of connected line segments that move horizontally or vertically through the grid points. # Visual Facts 1. Grid Properties: - 4×4 grid (n=4) - Grid points are labeled with coordinates (x,y) - Origin (0,0) is at top-left 2. Yellow Region: - Rectangular area marked with dashed yellow border - Top-left coordinate: (1,0) - Bottom-right coordinate: (2,2) 3. Blue Chain: - Consists of connected blue line segments - Moves only horizontally or vertically - Chain points: (0,0)→(0,1)→(1,1)→(1,0)→(2,0)→(3,0)→(3,1)→(2,1)→(2,2)→(2,3)→(1,3) 4. Red Intersections: - four red circular markers where the blue chain crosses yellow border - Located at: * Between (0,1) and (1,1). (0,1) is outside the yellow region, (1,1) is inside * Between (2,0) and (3,0). (2,0) is inside the yellow region, (3,0) is outside * Between (3,1) and (2,1). (3,1) is outside the yellow region, (2,1) is inside * Between (2,2) and (2,3). (2,2) is inside the yellow region, (2,3) is outside # Visual Patterns - Red regions appear only where the blue chain crosses the yellow rectangle's boundary - Each crossing of the chain with the yellow border counts as one intersection - Intersections occur when a line segment has one endpoint inside and one outside the yellow region
def test(): test_cases = [ (2, [(0, 0), (0, 1), (1, 1), (1, 0)], (1, 0), (1, 1), 1), (2, [(0, 0), (0, 1), (1, 1), (1, 0)], (1, 1), (1, 1), 2), (2, [(0, 0), (0, 1), (1, 1), (1, 0)], (1, 1), (1, 1), 2), (2, [(0, 0), (0, 1), (1, 0)], (1, 1), (1, 1), 0), (3, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (2, 2), (1, 2), (1, 1)], (1, 0), (2, 1), 3), (3, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (2, 2), (1, 2), (1, 1)], (1, 0), (2, 2), 1), (4, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (3, 0), (3, 1), (2, 1), (2, 2), (2, 3), (1, 3)], (1, 0), (2, 2), 4), (4, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (3, 0), (3, 1), (2, 1), (2, 2), (2, 3), (1, 3), (1, 2)], (1, 0), (2, 2), 5), (4, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (3, 0), (3, 1), (2, 1), (2, 2), (2, 3), (1, 3), (1, 2), (0, 2)], (1, 0), (2, 2), 6), (4, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (3, 0), (3, 1), (2, 1), (2, 2), (2, 3), (1, 3), (1, 2), (0, 2)], (0, 0), (2, 2), 4), (4, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (3, 0), (3, 1), (2, 1), (2, 2), (2, 3), (1, 3), (1, 2), (0, 2)], (0, 0), (3, 3), 0), ] for i, (n, chain, top_left, bottom_right, expected_output) in enumerate(test_cases): try: output = solution(n, chain, top_left, bottom_right) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`n`: {n}\n" f"`chain`: {chain}\n" f"`top_left`: {top_left}\n" f"`bottom_right`: {bottom_right}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`n`: {n}\n" f"`chain`: {chain}\n" f"`top_left`: {top_left}\n" f"`bottom_right`: {bottom_right}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List, Tuple def solution(n: int, chain: List[Tuple[int, int]], top_left: Tuple[int, int], bottom_right: Tuple[int, int]) -> int: """ Given a chain and a yellow region in an n x n 2D matrix, find the number of red regions that are formed. Parameters: n (int): The size of the matrix. chain (List[Tuple[int, int]]): Coordinates of each node in the chain in order. top_left (Tuple[int, int]): Coordinates of the top-left corner of the yellow region. bottom_right (Tuple[int, int]): Coordinates of the bottom-right corner of the yellow region. Returns: int: The number of red regions. """
{ "Common Sense": null, "Data Structures": [ "Path" ], "Dynamic Patterns": null, "Geometric Objects": [ "Line Segment", "Grid", "Point", "Coordinate System", "Rectangle" ], "Mathematical Operations": [ "Counting" ], "Spatial Transformations": null, "Topological Relations": [ "Connectivity", "Boundary", "Intersection" ] }
Aggregation
q29-2
from typing import List, Tuple def solution(n: int, chain: List[Tuple[int, int]], top_left: Tuple[int, int], bottom_right: Tuple[int, int]) -> Tuple[int, int]: """ Given a chain and a yellow region in an n x n 2D matrix, find the number of red regions and green regions that are formed. Parameters: n (int): The size of the matrix. chain (List[Tuple[int, int]]): Coordinates of each node in the chain in order. top_left (Tuple[int, int]): Coordinates of the top-left corner of the yellow region. bottom_right (Tuple[int, int]): Coordinates of the bottom-right corner of the yellow region. Returns: Tuple[int,int]: The number of red regions and green regions respectively. """ def is_inside(x: int, y: int) -> bool: """ Check if a point is inside the yellow region """ return top_left[0] <= x <= bottom_right[0] and top_left[1] <= y <= bottom_right[1] v_crossings = 0 h_crossings = 0 for i in range(len(chain) - 1): x1, y1 = chain[i] x2, y2 = chain[i + 1] # Check if one point is inside and the other is outside the yellow region if is_inside(x1, y1) != is_inside(x2, y2): if x1 == x2: v_crossings += 1 else: h_crossings += 1 return (v_crossings, h_crossings)
# Problem Description This is a geometric problem that involves analyzing intersections between a polyline (chain) and a rectangular region on a grid. The goal is to count two types of intersections: 1. Red regions: where the polyline crosses the yellow rectangle's boundary vertically 2. Green regions: where the polyline crosses the yellow rectangle's boundary horizontally The solution needs to return a tuple containing the count of these two types of intersections. # Visual Facts 1. Grid Properties: - 4×4 grid (n=4) - Grid points labeled with coordinates (x,y) - Origin (0,0) at top-left 2. Yellow Region: - Rectangular area marked with dashed yellow border - Top-left coordinate: (1,0) - Bottom-right coordinate: (2,2) 3. Blue Chain: - Connected blue line segments - Moves only horizontally or vertically - Chain points: (0,0)→(0,1)→(1,1)→(1,0)→(2,0)→(3,0)→(3,1)→(2,1)→(2,2)→(2,3)→(1,3)→(1,2) 4. Intersection Markers: - Red circles (3): Mark vertical crossings at boundaries * Between (0,1) and (1,1). (0,1) is outside the yellow region, (1,1) is inside * Between (2,0) and (3,0). (2,0) is inside the yellow region, (3,0) is outside * Between (3,1) and (2,1). (3,1) is outside the yellow region, (2,1) is inside - Green circles (2): Mark horizontal crossings at boundaries * Between (2,2) and (2,3). (2,2) is inside the yellow region, (2,3) is outside * Between (1,2) and (1,3). (1,2) is inside the yellow region, (1,3) is outside # Visual Patterns 1. Determining the points inside the yellow region: - use (a, b) to represent the top-left corner of the yellow region, and (c, d) to represent the bottom-right corner of the yellow region. - a point (x, y) is inside the yellow region if a ≤ x ≤ c and b ≤ y ≤ d. 2. Intersection Classification Rules: - Vertical crossings (red): * Chain segment must be vertical (identical y coordinate) at crossing point - Horizontal crossings (green): * Chain segment must be horizontal (identical x coordinate) at crossing point
def test(): test_cases = [ (2, [(0, 0), (0, 1), (1, 1), (1, 0)], (1, 0), (1, 1), (0, 1)), (2, [(0, 0), (0, 1), (1, 1), (1, 0)], (1, 1), (1, 1), (1, 1)), (2, [(0, 0), (0, 1), (1, 0)], (1, 1), (1, 1), (0, 0)), (3, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (2, 2), (1, 2), (1, 1)], (1, 0), (2, 1), (2,1)), (3, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (2, 2), (1, 2), (1, 1)], (1, 0), (2, 2), (0, 1)), (4, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (3, 0), (3, 1), (2, 1), (2, 2), (2, 3), (1, 3), (1, 2)], (1, 0),(2, 2),(2,3)), (4, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (3, 0), (3, 1), (2, 1), (2, 2), (2, 3), (1, 3)], (1, 0), (2, 2), (1, 3)), (4, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (3, 0), (3, 1), (2, 1), (2, 2), (2, 3), (1, 3), (1, 2)], (1, 0), (2, 2), (2,3)), (4, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (3, 0), (3, 1), (2, 1), (2, 2), (2, 3), (1, 3), (1, 2), (0, 2)], (1, 0), (2, 2), (2, 4)), (4, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (3, 0), (3, 1), (2, 1), (2, 2), (2, 3), (1, 3), (1, 2), (0, 2)], (0, 0), (2, 2), (2, 2)), (4, [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (3, 0), (3, 1), (2, 1), (2, 2), (2, 3), (1, 3), (1, 2), (0, 2)], (0, 0), (3, 3), (0, 0)), ] for i, (n, chain, top_left, bottom_right, expected_output) in enumerate(test_cases): try: output = solution(n, chain, top_left, bottom_right) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`n`: {n}\n" f"`chain`: {chain}\n" f"`top_left`: {top_left}\n" f"`bottom_right`: {bottom_right}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`n`: {n}\n" f"`chain`: {chain}\n" f"`top_left`: {top_left}\n" f"`bottom_right`: {bottom_right}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List, Tuple def solution(n: int, chain: List[Tuple[int, int]], top_left: Tuple[int, int], bottom_right: Tuple[int, int]) -> Tuple[int, int]: """ Given a chain and a yellow region in an n x n 2D matrix, find the number of red regions and green regions that are formed. Parameters: n (int): The size of the matrix. chain (List[Tuple[int, int]]): Coordinates of each node in the chain in order. top_left (Tuple[int, int]): Coordinates of the top-left corner of the yellow region. bottom_right (Tuple[int, int]): Coordinates of the bottom-right corner of the yellow region. Returns: Tuple[int,int]: The number of red regions and green regions respectively. """
{ "Common Sense": null, "Data Structures": [ "Path" ], "Dynamic Patterns": null, "Geometric Objects": [ "Line Segment", "Grid", "Point", "Coordinate System", "Rectangle" ], "Mathematical Operations": [ "Counting" ], "Spatial Transformations": null, "Topological Relations": [ "Connectivity", "Boundary", "Intersection" ] }
Aggregation
q3
def solution(start: str, end: str) -> list[str]: """ Find the shortest path from one point to another Parameters: start (str): The starting node of the path. end (str): The ending node of the path. Returns: Optional[List[str]]: A list of nodes representing the path from start to end, if such a path exists. Returns None if no path exists. Example: path = solution('C', 'B') # Output might be ['C', 'A', 'B'] """ graph = { 'A': ['B'], 'B': ['D', 'E'], 'C': ['A', 'D'], 'D': ['A'], 'E': [] # No outgoing edges from E } if start not in graph or end not in graph: return None queue = [[start]] # Initialize the queue with the starting node in a path list visited = set() # To keep track of visited nodes while queue: path = queue.pop(0) # Get the first path from the queue (FIFO) node = path[-1] # Get the last node in the path if node in visited: continue visited.add(node) # Check if we've reached the end node if node == end: return path # Explore adjacent nodes for neighbor in graph[node]: new_path = path + [neighbor] # Create a new path including the neighbor queue.append(new_path) # If the loop ends, no path was found return None
# Problem Description This is a shortest path finding problem in a directed graph where: - We need to find the shortest path between two given nodes in the graph - The path must follow the direction of the arrows - The input nodes are represented as single letters - We need to return the complete path as a list of nodes - If no path exists between the start and end nodes, return None # Visual Facts - The graph contains 5 nodes labeled A, B, C, D, and E - There are 7 directed edges in total: * C → A * C → D * D → A * A → B * B → D * B → E - All nodes are represented as circles with single letter labels - The edges are represented as purple arrows # Visual Patterns - Distance between nodes should be measured by the number of edges traversed, not any physical distance in the visualization
def test(): test_cases = [ ('A', 'B', ['A', 'B']), ('C', 'E', ['C', 'A', 'B', 'E']), ('A', 'E', ['A', 'B', 'E']), ('B', 'D', ['B', 'D']), ('C', 'B', ['C', 'A', 'B']), ('C', 'D', ['C', 'D']), ('B', 'E', ['B', 'E']) ] for start, end, expected_output in test_cases: try: output = solution(start, end) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message none_cases = [ ['E', 'C'], ['E', 'B'] ] for start, end in none_cases: try: output = solution(start, end) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output is not None: error_message = ( f"The following Test Case failed:\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Actual Output: {output}\n" f"Expected Output: None" ) assert False, error_message test()
def solution(start: str, end: str) -> list[str]: """ Find the shortest path from one point to another Parameters: start (str): The starting node of the path. end (str): The ending node of the path. Returns: Optional[List[str]]: A list of nodes representing the path from start to end, if such a path exists. Returns None if no path exists. Example: path = solution('C', 'B') # Output might be ['C', 'A', 'B'] """ graph = {}
{ "Common Sense": null, "Data Structures": [ "Directed Graph", "Path" ], "Dynamic Patterns": null, "Geometric Objects": [ "Circle", "Arrow" ], "Mathematical Operations": null, "Spatial Transformations": null, "Topological Relations": [ "Connectivity", "Adjacency", "Connection" ] }
Direct Calculation
q3-2
def solution(start: str, end: str) -> list[str]: """ Find the shortest path from one point to another Parameters: start (str): The starting node of the path. end (str): The ending node of the path. Returns: Optional[List[str]]: A list of nodes representing the path from start to end, if such a path exists. Returns None if no path exists. Example: path = solution('A', 'E') # Output might be ['A', 'B', 'E'] """ graph = { 'A': ['B', 'C', 'D'], 'B': ['A', 'E', 'D'], 'C': ['A', 'D'], 'D': ['C', 'A', 'B'], 'E': ['B'] } if start not in graph or end not in graph: return None queue = [[start]] # Initialize the queue with the starting node in a path list visited = set() # To keep track of visited nodes while queue: path = queue.pop(0) # Get the first path from the queue (FIFO) node = path[-1] # Get the last node in the path if node in visited: continue visited.add(node) # Check if we've reached the end node if node == end: return path # Explore adjacent nodes for neighbor in graph[node]: new_path = path + [neighbor] # Create a new path including the neighbor queue.append(new_path) # If the loop ends, no path was found return None
# Problem Description This is a shortest path finding problem in an undirected graph. The task is to implement a function that finds the shortest path between two nodes in the graph, given start and end nodes. The function should return the sequence of nodes that represents the shortest path from start to end. # Visual Facts 1. The graph contains 5 nodes labeled A, B, C, D, and E 2. There are 7 edges in the graph: - A-B - A-C - A-D - B-D - B-E - C-D 3. All edges are undirected (shown by single lines) 4. All edges appear to have equal weight (shown by similar line styles) # Visual Patterns - All edges have equal weight (no different line styles or weights shown) - The shortest path will be the one with the minimum number of edges
def test(): test_cases = [ ('A', 'B', ['A', 'B']), ('A', 'E', ['A', 'B', 'E']), ('B', 'D', ['B', 'D']), ('C', 'D', ['C', 'D']), ('B', 'E', ['B', 'E']) ] for start, end, expected_output in test_cases: try: output = solution(start, end) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message multi_cases = [ ('C', 'E', ['C', 'A', 'B', 'E'], ['C', 'D', 'B', 'A']), ('C', 'B', ['C', 'A', 'B'], ['C', 'D', 'B']), ] for start, end, expected_output_1, expected_output_2 in multi_cases: try: output = solution(start, end) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output_1 and output != expected_output_2: error_message = ( f"The following Test Case failed:\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Actual Output: {output}\n" f"Expected Output 1: {expected_output_1}\n" f"Expected Output 2: {expected_output_2}" ) assert False, error_message test()
def solution(start: str, end: str) -> list[str]: """ Find the shortest path from one point to another Parameters: start (str): The starting node of the path. end (str): The ending node of the path. Returns: Optional[List[str]]: A list of nodes representing the path from start to end, if such a path exists. Returns None if no path exists. Example: path = solution('A', 'E') # Output might be ['A', 'B', 'E'] """ graph = {}
{ "Common Sense": null, "Data Structures": [ "Undirected Graph", "Path" ], "Dynamic Patterns": null, "Geometric Objects": [ "Circle", "Arrow" ], "Mathematical Operations": null, "Spatial Transformations": null, "Topological Relations": [ "Connectivity", "Adjacency", "Connection" ] }
Direct Calculation
q3-3
def solution(start: str, end: str) -> list[str]: """ Find the shortest path from one point to another Parameters: start (str): The starting node of the path. end (str): The ending node of the path. Returns: Optional[List[str]]: A list of nodes representing the path from start to end, if such a path exists. Returns None if no path exists. Example: path = solution('A', 'E') # Output might be ['A', 'B', 'E'] """ graph = { 'A': ['B'], 'B': ['D'], 'C': ['A'], 'D': ['C'], 'E': ['B', 'D'] } if start not in graph or end not in graph: return None queue = [[start]] # Initialize the queue with the starting node in a path list visited = set() # To keep track of visited nodes while queue: path = queue.pop(0) # Get the first path from the queue (FIFO) node = path[-1] # Get the last node in the path if node in visited: continue visited.add(node) # Check if we've reached the end node if node == end: return path # Explore adjacent nodes for neighbor in graph[node]: new_path = path + [neighbor] # Create a new path including the neighbor queue.append(new_path) # If the loop ends, no path was found return None
# Problem Description This is a shortest path finding problem in a directed graph. The task is to implement a function that finds the shortest path between two given nodes in a directed graph. The function should return the sequence of nodes that represents the shortest path from the start node to the end node. # Visual Facts 1. The graph contains 5 nodes labeled A, B, C, D, and E 2. There are 6 directed edges in the graph: - A → B - C → A - D → C - B → D - E → B - E → D 3. Each edge is represented by a purple arrow 4. All edges appear to have the same visual weight/thickness 5. Each node is represented by a blue circle with a letter inside # Visual Patterns - Movement is only allowed in the direction of the arrows - Since all edges are visually identical, they likely have equal weights - This suggests we should count the number of edges (hops) to determine the shortest path
def test(): test_cases = [ ('A', 'B', ['A', 'B']), ('E', 'C', ['E', 'D', 'C']), ('E', 'A', ['E', 'D', 'C', 'A']), ('B', 'D', ['B', 'D']), ('C', 'B', ['C', 'A', 'B']), ('C', 'D', ['C', 'A', 'B', 'D']), ('E', 'B', ['E', 'B']) ] for start, end, expected_output in test_cases: try: output = solution(start, end) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}\n\n" f"Graph Structure:\n" "{'A': ['B', 'C'], 'B': ['A', 'D'], 'C': ['A', 'D'], 'D': ['B', 'C', 'E'], 'E': ['B', 'D']}" ) assert False, error_message none_cases = [ ['C', 'E'], ['A', 'E'] ] for start, end in none_cases: try: output = solution(start, end) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output is not None: error_message = ( f"The following Test Case failed:\n" f"`start`: {start}\n" f"`end`: {end}\n\n" f"Actual Output: {output}\n" f"Expected Output: None\n\n" f"Graph Structure:\n" "{'A': ['B', 'C'], 'B': ['A', 'D'], 'C': ['A', 'D'], 'D': ['B', 'C', 'E'], 'E': ['B', 'D']}" ) assert False, error_message test()
def solution(start: str, end: str) -> list[str]: """ Find the shortest path from one point to another Parameters: start (str): The starting node of the path. end (str): The ending node of the path. Returns: Optional[List[str]]: A list of nodes representing the path from start to end, if such a path exists. Returns None if no path exists. Example: path = solution('A', 'E') # Output might be ['A', 'B', 'E'] """ graph = {}
{ "Common Sense": null, "Data Structures": [ "Directed Graph", "Path" ], "Dynamic Patterns": null, "Geometric Objects": [ "Circle", "Arrow" ], "Mathematical Operations": null, "Spatial Transformations": null, "Topological Relations": [ "Connectivity", "Adjacency", "Connection" ] }
Direct Calculation
q30
from typing import Optional class TreeNode: """ This class represents a node in a tree. Each node contains a value and a list of children. """ def __init__(self, value: int, children=[None, None]): self.value = value self.children = children def is_mirror(left: Optional[TreeNode], right: Optional[TreeNode]) -> bool: """ Helper function to determine if two trees are mirror images of each other. Parameters: left (TreeNode): The root node of the left subtree. right (TreeNode): The root node of the right subtree. Returns: bool: True if the trees are mirror images, False otherwise. """ if left is None and right is None: return True if left is None or right is None: return False if left.value != right.value: return False return is_mirror(left.children[0], right.children[1]) and is_mirror(left.children[1], right.children[0]) def solution(root: Optional[TreeNode]) -> int: """ Determine which type the binary tree belongs to. Parameters: root (TreeNode): The root node of a binary tree. Returns: int: Type 1 if the tree is symmetrical, Type 2 otherwise. """ if root is None: return 1 return 1 if is_mirror(root.children[0], root.children[1]) else 2
# Problem Description This is a binary tree classification problem where we need to determine if a given binary tree belongs to Type 1 or Type 2. The main task is to determine if a binary tree has mirror symmetry - where the left subtree is a mirror reflection of the right subtree. Type 1 represents symmetrical trees, while Type 2 represents non-symmetrical trees. # Visual Facts 1. Both examples show multiple binary trees for each type 2. Type 1 trees: - Shows 4 example trees - The left and right subtrees of the root node are perfectly symmetrical along a vertical axis through the root node (shown with green dashed line) 3. Type 2 trees: - Shows 4 example trees - Each tree has a red dashed line with an X mark - Trees lack mirror symmetry in either structure or values # Visual Patterns 1. Symmetry Rules for Type 1: - The root value can be any number - Left and right subtrees of the root node must be mirror images of each other - null nodes are also considered as regular nodes for symmetry comparison 2. Asymmetry Patterns for Type 2: - Trees become Type 2 if either: * The structure is not symmetrical (different number of nodes on left vs right) * Any single violation of symmetry makes it Type 2
def tree_to_string(node: TreeNode, level: int = 0) -> str: """Helper function to convert a tree to a readable string format""" if node is None: return "None" indent = " " * level result = f"TreeNode({node.value}" if node.children: result += ", [\n" child_strings = [] for child in node.children: child_str = tree_to_string(child, level + 1) child_strings.append(indent + " " + child_str) result += ",\n".join(child_strings) result += f"\n{indent}])" else: result += ")" return result def test(): Tree1 = TreeNode(1, [ TreeNode(1), TreeNode(2) ]) # 2 Tree2 = TreeNode(1, [ TreeNode(2), TreeNode(2) ]) # 1 Tree3 = TreeNode(3, [ TreeNode(3), None ]) # 2 Tree4 = TreeNode(2, [ TreeNode(2), TreeNode(2, [ TreeNode(2), None ]) ]) # 2 Tree5 = TreeNode(2, [ TreeNode(2, [ TreeNode(2), None ]), TreeNode(2, [ None, TreeNode(2) ]) ]) # 1 Tree6 = TreeNode(2, [ TreeNode(2, [ None, TreeNode(2) ]), TreeNode(2, [ None, TreeNode(2) ]) ]) # 2 Tree7 = TreeNode(2, [ TreeNode(1, [TreeNode(2), None]), TreeNode(2, [TreeNode(3), None]) ]) # 2 Tree8 = TreeNode(2, [ TreeNode(1, [ TreeNode(2, [TreeNode(2), TreeNode(3)]), TreeNode(3, [TreeNode(3), TreeNode(2)]) ]), TreeNode(1, [ TreeNode(3, [TreeNode(2), TreeNode(3)]), TreeNode(2, [TreeNode(3), TreeNode(2)]) ]) ]) # 1 test_cases = [ (Tree1, 2), (Tree2, 1), (Tree3, 2), (Tree4, 2), (Tree5, 1), (Tree6, 2), (Tree7, 2), (Tree8, 1) ] for i, (root, expected_output) in enumerate(test_cases): try: output = solution(root) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`root`: Tree{i+1}\n" f"Tree structure:\n{tree_to_string(root)}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`root`: Tree{i+1}\n" f"Tree structure:\n{tree_to_string(root)}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List class TreeNode: """ This class represents a node in a tree. Each node contains a value and a list of children. """ def __init__(self, value: int, children=[None, None]): self.value = value self.children = children # contains the left and right children, or empty list if no children def solution(root: TreeNode) -> int: """ Determine which type the binary tree belongs to Parameters: root (TreeNode): The root node of a binary tree. Returns: int: Type 1 or 2. """
{ "Common Sense": null, "Data Structures": [ "Binary Tree" ], "Dynamic Patterns": [ "Mirror Symmetry" ], "Geometric Objects": null, "Mathematical Operations": [ "Value Comparison" ], "Spatial Transformations": null, "Topological Relations": [ "Connectivity" ] }
Validation
q30-2
from typing import List class TreeNode: """ This class represents a node in a tree. Each node contains a value and a list of children. """ def __init__(self, value: int, children=[None, None]): self.value = value self.children = children def are_identical(left: TreeNode, right: TreeNode) -> bool: """ Determine if two subtrees are identical. Parameters: left (TreeNode): The root node of the left subtree. right (TreeNode): The root node of the right subtree. Returns: bool: True if the subtrees are identical, False otherwise. """ if left is None and right is None: return True if left is None or right is None: return False if left.value != right.value: return False return are_identical(left.children[0], right.children[0]) and are_identical(left.children[1], right.children[1]) def solution(root: TreeNode) -> int: """ Determine which type the binary tree belongs to. Parameters: root (TreeNode): The root node of a binary tree. Returns: int: Type 1 if the tree has identical left and right subtrees, Type 2 otherwise. """ if root is None: return 2 left = root.children[0] right = root.children[1] if are_identical(left, right): return 1 else: return 2
# Problem Description This is a binary tree classification problem where we need to determine if a given binary tree belongs to Type 1 or Type 2. The main task is to determine if a binary tree follows a special pattern where the left subtree is exactly identical (same structure and values) to the right subtree. Type 1 represents trees with identical subtrees, while Type 2 represents trees without this property. # Visual Facts 1. The image shows two categories of trees (Type 1 and Type 2), each with 4 examples 2. Type 1 trees have: - Green dashed vertical lines through the root node - Binary tree structure with maximum 2 children per node 3. Type 2 trees have: - Red dashed lines with X marks - At least one difference between left and right subtrees 4. Each tree is properly structured as a binary tree with: - A single root node - Maximum two children per node # Visual Patterns 1. Type 1 Pattern Requirements: - The left subtree must be exactly identical to the right subtree in both: * Structure (same arrangement of nodes) * Values (corresponding nodes must have same values) - This pattern must hold at the root level - Example: Tree with root 3 has identical 4's as children 2. Type 2 Pattern Characteristics: - A tree becomes Type 2 if there's any violation of the Type 1 pattern: * Different values in corresponding positions * Different structure between left and right subtrees * Even a single node mismatch makes it Type 2 3. Additional Pattern Rules: - The root value itself doesn't determine the type - The comparison is about exact equality, not mirror symmetry - Null children (missing nodes) must also match on both sides
def print_tree(node: TreeNode, level=0, prefix="Root: "): """Helper function to create a string representation of the tree""" if node is None: return prefix + "None\n" result = prefix + str(node.value) + "\n" for i, child in enumerate(node.children): if child: result += print_tree(child, level + 1, " " * (level + 1) + f"Child {i}: ") else: result += " " * (level + 1) + f"Child {i}: None\n" return result def test(): Tree1 = TreeNode(1, [ TreeNode(1), TreeNode(2) ]) # 2 Tree2 = TreeNode(1, [ TreeNode(2), TreeNode(2) ]) # 1 Tree3 = TreeNode(3, [ TreeNode(3), None ]) # 2 Tree4 = TreeNode(2, [ TreeNode(2), TreeNode(2, [ TreeNode(2), None ]) ]) # 2 Tree5 = TreeNode(2, [ TreeNode(2, [ TreeNode(2), None ]), TreeNode(2, [ TreeNode(2), None ]) ]) # 1 Tree6 = TreeNode(2, [ TreeNode(2, [ TreeNode(2), None ]), TreeNode(2, [ None, TreeNode(2) ]) ]) # 2 Tree7 = TreeNode(2, [ TreeNode(1, [TreeNode(2), None]), TreeNode(2, [TreeNode(3), None]) ]) # 2 Tree8 = TreeNode(2, [ TreeNode(1, [ TreeNode(3, [TreeNode(2), TreeNode(3)]), TreeNode(2, [TreeNode(3), TreeNode(2)]) ]), TreeNode(1, [ TreeNode(3, [TreeNode(2), TreeNode(3)]), TreeNode(2, [TreeNode(3), TreeNode(2)]) ]) ]) # 1 test_cases = [ (Tree1, 2), (Tree2, 1), (Tree3, 2), (Tree4, 2), (Tree5, 1), (Tree6, 2), (Tree7, 2), (Tree8, 1) ] for i, (root, expected_output) in enumerate(test_cases): try: output = solution(root) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`root`: Tree structure:\n{print_tree(root)}\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`root`: Tree structure:\n{print_tree(root)}\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List class TreeNode: """ This class represents a node in a tree. Each node contains a value and a list of children. """ def __init__(self, value: int, children=[None, None]): self.value = value self.children = children # contains the left and right children, or empty list if no children def solution(root: TreeNode) -> int: """ Determine which type the binary tree belongs to Parameters: root (TreeNode): The root node of a binary tree. Returns: int: Type 1 or 2. """
{ "Common Sense": null, "Data Structures": [ "Binary Tree" ], "Dynamic Patterns": [ "Mirror Symmetry" ], "Geometric Objects": null, "Mathematical Operations": [ "Value Comparison" ], "Spatial Transformations": null, "Topological Relations": [ "Connectivity" ] }
Validation
q31
from typing import List def solution(cubes: List[List[int]]) -> int: """ Count the red squares from a specified view of the stacked cubes. Parameters: cubes (List[List[int]]): A 2D list where cubes[i][j] represents the number of cubes stacked at coordinate (i, j). (0-indexed) Returns: int: The number of red squares from the given view. """ max_z = max(max(row) for row in cubes) return sum(1 for row in cubes for cell in row if cell >= max_z)
# Problem Description - The task involves calculating the number of red squares visible from a given view of a 3D stack of cubes represented by a 2D grid. The red squares appear as the top-most cube among all the cubes. The function accepts a 2D grid cubes where each entry cubes[i][j] specifies the number of stacked cubes at the grid cell (i, j). - The goal is to implement the function solution, which counts and returns the total number of red squares visible in the specified view. # Visual Facts 1. 3D Grid Representation: - The 3D structure is built on a 2D coordinate plane defined by the x and y axes, with the z axis representing the height (stacked cubes). - Each (x, y) cell contains a number of stacked cubes. 2. Red Squares: - Red squares represent the top-most cube among all the cubes. - "Top-most" represents the cube with the largest Z-coordinate. - Each column (x, y) does not necessarily have a red cube, only the column(s) with the most stacking along the Z-axis can have a red cube. 3. Examples in the image: - Example 1: In the (x, y) view, red squares appear at the highest points (height z). - Example 2, 3, and 4 follow the same principle. # Visual Patterns 1. Top-most Cube Identification: - A red square is assigned only to the cube(s) with the largest Z-coordinate across the entire 3D grid. - This means that not all columns (x, y) will necessarily have a red cube. Only the column(s) with the maximum stacking height along the Z-axis can have red cubes. 2. Single Red Cube per Column: - In a column (x, y) where the stacking height matches the maximum Z-coordinate in the grid, there can be one red cube. 3. Columns with No Contribution: - Any column (x, y) where the height (stacking along Z-axis) is less than the maximum Z-coordinate does not contribute any red cubes. 4. Global Maximum Z-coordinate: - The identification of red cubes depends on determining the global maximum stacking height (largest Z-coordinate) in the entire grid.
def test(): cubes1 = [[2, 1, 3], [1, 2, 1]] cubes2 = [[2, 1, 3], [1, 0, 1]] cubes3 = [[2, 1, 3], [1, 1, 1]] cubes4 = [[1, 2], [3, 4]] cubes5 = [[1, 2], [3, 0], [5, 6]] cubes6 = [[1, 2], [3, 0], [5, 6], [0, 8]] cubes7 = [[1, 2], [3, 4], [5, 6], [7, 9], [9, 9]] cubes8 = [[0, 0], [0, 0], [0, 0], [0, 1], [0, 0]] test_cases = [ (cubes1, 1), (cubes2, 1), (cubes3, 1), (cubes4, 1), (cubes5, 1), (cubes6, 1), (cubes7, 3), (cubes8, 1) ] for i, (cubes, expected_output) in enumerate(test_cases): try: output = solution(cubes) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`cubes`: {cubes}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`cubes`: {cubes}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(cubes: List[List[int]]) -> int: """ Count the red squares from a specified view of the stacked cubes. Parameters: cubes (List[List[int]]): A 2D list where cubes[i][j] represents the number of cubes stacked at coordinate (i, j). (0-indexed) Returns: int: The number of red squares from the given view. """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": [ "Layered Structure" ], "Geometric Objects": [ "Coordinate System", "Grid", "Square" ], "Mathematical Operations": null, "Spatial Transformations": [ "Stacking" ], "Topological Relations": [ "Adjacency" ] }
Aggregation
q31-2
from typing import List def solution(cubes: List[List[int]]) -> int: """ Count the red squares from a specified view of the stacked cubes. Parameters: cubes (List[List[int]]): A 2D list where cubes[i][j] represents the number of cubes stacked at coordinate (i, j). (0-indexed) Returns: int: The number of red squares from the given view. """ # for each column, find the first non-zero element in the last row last_none_zero_row = 0 for j in range(len(cubes[0])): for i in range(len(cubes)-1, -1, -1): if cubes[i][j] != 0: last_none_zero_row = max(last_none_zero_row, i) break red_squares = sum(cubes[last_none_zero_row]) return red_squares
# Problem Description The task involves analyzing a 3D stack of cubes and determining how many "rightmost cubes" are visible when viewing the stack from the right side. The function `solution` accepts a 2D list `cubes` where `cubes[i][j]` represents the number of cubes stacked vertically at coordinate `(i, j)` on a 2D grid. The goal is to count and return the total number of "rightmost cubes" visible from the right side. # Visual Facts 1. **3D Grid Representation**: - The 3D structure is built on a 2D coordinate plane defined by the x and y axes, with the z axis representing the height (stacked cubes). - Each (x, y) cell contains a number of stacked cubes. 2. **Rightmost Cubes**: - Rightmost cubes are highlighted in red in the image. - These cubes are the first cubes encountered when looking from the right side along the x-axis. 3. **Examples in the Image**: - **Example 1**: - In the figure, the stack heights are as follows: (0, 0) has a height of 2, (0, 1) has a height of 1, (0, 2) has a height of 3, (1, 0) has a height of 1, and (1, 2) has a height of 1. - The rightmost cubes are the cubes stacked on the rightmost stacks, which are the stacks with the maximum x-coordinate, located at (1, 0) and (1, 2). - The number of red cubes is the sum of the hight of rightmost stacks that is 1 + 1 = 2. - **Example 4**: - In the figure, the stack heights are as follows: (0, 0) has a height of 1, (0, 1) has a height of 1, (0, 2) has a height of 1, (1, 2) has a height of 1, and (2, 2) has a height of 1. - The rightmost cubes are the cubes stacked on the rightmost stacks, which are the stacks with the maximum x-coordinate, located at (2, 2). - The number of red cubes is 1. # Visual Patterns 1. **Rightmost Cube Identification**: - A cube is considered a "rightmost cube" if it is the first cube encountered when looking from the right in its row (along the x-axis). - The forward direction of x in the picture represents the direction of the increase in the number of rows of the matrix, and the forward direction of y represents the direction of the increase in the number of columns of the input matrix, which means that the rightmost direction in the picture corresponds to the last **non-zero** row of the input matrix 2. **Counting Rightmost Cubes**: - The total number of cubes with the rightmost x-coordinate(the last **non-zero** row) is the desired answer.
def test(): cubes1 = [[2, 1, 3], [1, 2, 1]] cubes2 = [[2, 1, 3], [1, 0, 1]] cubes3 = [[2, 1, 3], [1, 1, 1]] cubes4 = [[1, 2], [3, 4]] cubes5 = [[1, 2], [3, 0], [5, 6]] cubes6 = [[1, 2], [3, 0], [5, 6], [0, 8]] cubes7 = [[1, 2], [3, 4], [5, 6], [7, 9], [9, 9]] cubes8 = [[0, 0], [0, 0], [0, 0], [0, 1], [0, 0]] test_cases = [ (cubes1, 4), (cubes2, 2), (cubes3, 3), (cubes4, 7), (cubes5, 11), (cubes6, 8), (cubes7, 18), (cubes8, 1) ] for i, (cubes, expected_output) in enumerate(test_cases): try: output = solution(cubes) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`cubes`: {cubes}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`cubes`: {cubes}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(cubes: List[List[int]]) -> int: """ Count the red squares from a specified view of the stacked cubes. Parameters: cubes (List[List[int]]): A 2D list where cubes[i][j] represents the number of cubes stacked at coordinate (i, j). (0-indexed) Returns: int: The number of red squares from the given view. """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": [ "Layered Structure" ], "Geometric Objects": [ "Coordinate System", "Grid", "Square" ], "Mathematical Operations": null, "Spatial Transformations": [ "Stacking" ], "Topological Relations": [ "Adjacency" ] }
Aggregation
q31-3
from typing import List def solution(cubes: List[List[int]]) -> int: """ Count the red squares from a specified view of the stacked cubes. Parameters: cubes (List[List[int]]): A 2D list where cubes[i][j] represents the number of cubes stacked at coordinate (i, j). (0-indexed) Returns: int: The number of red squares from the given view. """ # for each row, find the first non-zero element in the first column first_none_zero_column = len(cubes[0]) for i in range(len(cubes)): for j in range(0, len(cubes[0])): if cubes[i][j] != 0: first_none_zero_column = min(first_none_zero_column, j) break red_squares = sum(cubes[i][first_none_zero_column] for i in range(len(cubes))) return red_squares
# Problem Description The task involves analyzing a 3D stack of cubes and determining how many "front-most cubes" are visible when viewing the stack from the front side. The function `solution` accepts a 2D list `cubes` where `cubes[i][j]` represents the number of cubes stacked at coordinate `(i, j)` on a 2D grid. The goal is to count and return the total number of "front-most cubes" visible from the front side. # Visual Facts 1. **3D Grid Representation**: - The 3D structure is built on a 2D coordinate plane defined by the x and y axes, with the z axis representing the height (stacked cubes). - Each (x, y) cell contains a number of stacked cubes. 2. **Front-most Cubes**: - Front-most cubes are highlighted in red in the image. - These cubes are the first cubes encountered when looking from the front side along the y-axis. 3. **Examples in the Image**: - **Example 1**: - The stack heights are as follows: (0, 0) has a height of 2, (0, 1) has a height of 1, (0, 2) has a height of 3, (1, 0) has a height of 1, and (1, 2) has a height of 1. - The front-most cubes are the cubes stacked on the front-most stacks, which are the stacks with the minimum y-coordinate, located at (0, 0), (1, 0). - The number of red cubes is 2 + 1 = 3. - **Example 2**: - The stack heights are as follows: (0, 0) has a height of 2, (0, 1) has a height of 1, (0, 2) has a height of 1, and (1, 2) has a height of 1. - The front-most cubes are the cubes stacked on the front-most stacks, which are the stacks with the minimum y-coordinate, located at (0, 0). - The number of red cubes is 2. - **Example 3**: - The stack heights are as follows: (0, 0) has a height of 2, (0, 1) has a height of 1, (0, 2) has a height of 2, (1, 0) has a height of 1, (1, 2) has a height of 1, and (2, 2) has a height of 1. - The front-most cubes are the cubes stacked on the front-most stacks, which are the stacks with the minimum y-coordinate, located at (0, 0), (1, 0). - The number of red cubes is 2 + 1 = 3. - **Example 4**: - The stack heights are as follows: (0, 0) has a height of 1, (0, 1) has a height of 1, (0, 2) has a height of 1, (1, 2) has a height of 1, and (2, 2) has a height of 1. - The front-most cubes are the cubes stacked on the front-most stacks, which are the stacks with the minimum y-coordinate, located at (0, 0). - The number of red cubes is 1. # Visual Patterns 1. **Front-most Cube Identification**: - A cube is considered a "front-most cube" if it is the first cube encountered when looking from the front in its column (along the y-axis). - - The forward direction of x in the picture represents the direction of the increase in the number of rows of the matrix, and the forward direction of y represents the direction of the increase in the number of columns of the input matrix, which means that the frontmost direction in the picture corresponds to the first **non-zero** column of the input matrix 2. **Counting Front-most Cubes**: - The total number of cubes with the front-most y-coordinate(the first non-zero column) is the desired answer.
def test(): cubes1 = [[2, 1, 3], [1, 2, 1]] cubes2 = [[2, 1, 3], [1, 0, 1]] cubes3 = [[2, 1, 3], [1, 1, 1]] cubes4 = [[0, 2], [0, 4]] cubes5 = [[1, 2], [3, 0], [5, 6]] cubes6 = [[1, 2], [3, 0], [5, 6], [0, 8]] cubes7 = [[1, 2], [3, 4], [5, 6], [7, 9], [9, 9]] cubes8 = [[3, 1], [3], [2, 2], [1]] test_cases = [ (cubes1, 3), (cubes2, 3), (cubes3, 3), (cubes4, 6), (cubes5, 9), (cubes6, 9), (cubes7, 25), (cubes8, 9) ] for i, (cubes, expected_output) in enumerate(test_cases): try: output = solution(cubes) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`cubes`: {cubes}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`cubes`: {cubes}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(cubes: List[List[int]]) -> int: """ Count the red squares from a specified view of the stacked cubes. Parameters: cubes (List[List[int]]): A 2D list where cubes[i][j] represents the number of cubes stacked at coordinate (i, j). (0-indexed) Returns: int: The number of red squares from the given view. """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": [ "Layered Structure" ], "Geometric Objects": [ "Coordinate System", "Grid", "Square" ], "Mathematical Operations": null, "Spatial Transformations": [ "Stacking" ], "Topological Relations": [ "Adjacency" ] }
Aggregation
q32
def solution(n: int) -> int: """ Refer to the pattern in the figure, calculate the number of cells with the specified n. Args: n: integer in [1, 1000] Returns: int: The number of cells """ return n*(n+3)+1
# Problem Description - The problem involves calculating the total number of hexagonal cells in a specific pattern for a given value of n - Input n is an integer between 1 and 1000 - The pattern grows symmetrically from the center, forming an hourglass-like shape - Need to find a formula that gives the total count of hexagonal cells for any valid n # Visual Facts 1. The image shows three different patterns for n=1, 2, and 3 2. For n=1: - Total cells: 5 - Central column has 1 cell - Left and right columns each have 2 cells 3. For n=2: - Total cells: 11 - Pattern has 5 columns - Outer columns have 3 cells each 4. For n=3: - Total cells: 19 - Pattern has 7 columns - Outer columns have 4 cells each # Visual Patterns 1. Growth Pattern: - Each increment of n adds 2 new columns (one on each side) - Number of columns = 2n + 1 - For n=1: 3 columns - For n=2: 5 columns - For n=3: 7 columns 2. Cell Count Pattern: - For n=1: 5 cells - For n=2: 11 cells = 5 + 6 - For n=3: 19 cells = 11 + 8 - The increment between consecutive n values follows: +6, +8 3. Mathematical Pattern: - The total number of cells follows the sequence: 5, 11, 19, ... - This formula generates the correct sequence: - n=1: 1+2*2 = 5 - n=2: 1+2*2+2*3 = 11 - n=3: 1+2*2+2*3+2*4 = 19 - The formula for total cells = 1 + 2*2 + 2*3 + 2*4 + ... + 2*(n+1)
def test(): x = lambda x: x*(x+3)+1 test_cases = [ (1, x(1)), (2, x(2)), (3, x(3)), (8, x(8)), (10, x(10)), (20, x(20)), (21, x(21)), (50, x(50)), (100, x(100)), (1000, x(1000)) ] for input_n, expected_output in test_cases: try: output = solution(input_n) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`n`: {input_n}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`n`: {input_n}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(n: int) -> int: """ Refer to the pattern in the figure, calculate the number of cells with the specified n. Args: n: integer in [1, 1000] Returns: int: The number of cells """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": [ "Layered Structure", "Mirror Symmetry", "Linear Increment" ], "Geometric Objects": [ "Hexagon", "Grid" ], "Mathematical Operations": null, "Spatial Transformations": [ "Scaling", "Stacking" ], "Topological Relations": [ "Adjacency", "Connectivity" ] }
Expansion
q32-2
def solution(n: int) -> int: """ Refer to the pattern in the figure, calculate the number of cells with the specified n. Args: n: integer in [1, 1000] Returns: int: The number of cells """ return n*(n+3)+1
# Problem Description - The problem involves calculating the total number of hexagonal cells in a triangular-like pattern for a given value of n - Input n is an integer between 1 and 1000 - The pattern grows vertically, forming a triangular structure that expands both upward and downward - Need to find the total count of hexagonal cells for any valid n # Visual Facts 1. Three patterns are shown for n=1, 2, and 3 2. n=1 pattern: - Total of 5 hexagonal cells - Forms a butterfly-like shape - 2 cells on top, 1 in middle, 2 on bottom 3. n=2 pattern: - Total of 11 hexagonal cells - 3 cells on top row - 5 cells in middle section - 3 cells on bottom row 4. n=3 pattern: - Total of 19 hexagonal cells - 4 cells on top row - 11 cells in middle section - 4 cells on bottom row # Visual Patterns 1. Growth Pattern: - Top and bottom rows are always symmetrical - Number of cells in top/bottom rows = n + 1 - Middle section expands with each n 2. Recursive Pattern: - Middle section of nth pattern contains the entire (n-1)th pattern - For n=2: middle section = total cells from n=1 (5) - For n=3: middle section = total cells from n=2 (11) 3. Mathematical Pattern: - The total number of cells follows the sequence: 5, 11, 19, ... - This formula generates the correct sequence: - n=1: 1+2*2 = 5 - n=2: 1+2*2+2*3 = 11 - n=3: 1+2*2+2*3+2*4 = 19 - The formula for total cells = 1 + 2*2 + 2*3 + 2*4 + ... + 2*(n+1)
def test(): x = lambda x: x*(x+3)+1 test_cases = [ (1, x(1)), (2, x(2)), (3, x(3)), (8, x(8)), (10, x(10)), (20, x(20)), (21, x(21)), (50, x(50)), (100, x(100)), (1000, x(1000)) ] for n, expected_output in test_cases: try: output = solution(n) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`n`: {n}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`n`: {n}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(n: int) -> int: """ Refer to the pattern in the figure, calculate the number of cells with the specified n. Args: n: integer in [1, 1000] Returns: int: The number of cells """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": [ "Layered Structure", "Mirror Symmetry", "Linear Increment" ], "Geometric Objects": [ "Hexagon", "Grid" ], "Mathematical Operations": null, "Spatial Transformations": [ "Scaling", "Stacking" ], "Topological Relations": [ "Adjacency", "Connectivity" ] }
Expansion
q32-3
def solution(n: int) -> int: """ Refer to the pattern in the figure, calculate the number of cells with the specified n. Args: n: integer in [1, 1000] Returns: int: The number of cells """ return n*(n+3)+1
# Problem Description - Calculate the total number of hexagonal cells in a specific pattern for a given value of n - Input n is an integer between 1 and 1000 - The pattern forms a symmetrical hourglass-like shape with hexagonal cells - Need to find a formula for counting total hexagons for any valid n # Visual Facts 1. Pattern for n=1: - Contains 5 hexagonal cells - Forms a compact hourglass shape - 2 cells in top row - 1 cell in middle - 2 cells in bottom row 2. Pattern for n=2: - Contains 11 hexagonal cells - 3 cells in top row - 5 cells in middle section - 3 cells in bottom row 3. Pattern for n=3: - Contains 19 hexagonal cells - 4 cells in top row - 11 cells in middle section - 4 cells in bottom row # Visual Patterns 1. Growth Pattern: - Each increment of n adds one more cell to top and bottom rows - Middle section expands systematically - For n=1: top/bottom have 2 cells each - For n=2: top/bottom have 3 cells each - For n=3: top/bottom have 4 cells each 2. Cell Count Pattern: - n=1: 5 cells - n=2: 11 cells (increase of 6) - n=3: 19 cells (increase of 8) - The increment between consecutive n values increases by 2 each time 3. Mathematical Pattern: - The total number of cells follows the sequence: 5, 11, 19, ... - This formula generates the correct sequence: - n=1: 1+2*2 = 5 - n=2: 1+2*2+2*3 = 11 - n=3: 1+2*2+2*3+2*4 = 19 - The formula for total cells = 1 + 2*2 + 2*3 + 2*4 + ... + 2*(n+1)
def test(): x = lambda x: x*(x+3)+1 test_cases = [ (1, x(1)), (2, x(2)), (3, x(3)), (8, x(8)), (10, x(10)), (20, x(20)), (21, x(21)), (50, x(50)), (100, x(100)), (1000, x(1000)) ] for n, expected_output in test_cases: try: output = solution(n) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`n`: {n}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`n`: {n}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(n: int) -> int: """ Refer to the pattern in the figure, calculate the number of cells with the specified n. Args: n: integer in [1, 1000] Returns: int: The number of cells """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": [ "Layered Structure", "Mirror Symmetry", "Linear Increment" ], "Geometric Objects": [ "Hexagon", "Grid" ], "Mathematical Operations": null, "Spatial Transformations": [ "Scaling", "Stacking" ], "Topological Relations": [ "Adjacency", "Connectivity" ] }
Expansion
q33
from collections import deque class TreeNode: """ Represents a node in a tree. Each node contains an integer value and a list of child TreeNodes. Attributes: value (int): The integer value of the node. children (list): A list of child nodes (TreeNode objects). """ def __init__(self, value: int, children: list=[]): self.value = value self.children = children def solution(root: TreeNode) -> list[int]: """ Computes the output sequence based on the given tree structure. Parameters: root (TreeNode): The root node of the tree. Returns: list[int]: A list of integers representing the output sequence as illustrated in the figure. """ if not root: return [] queue = deque([root]) result = [] while queue: level_size = len(queue) for i in range(level_size): node = queue.popleft() if i == level_size - 1: result.append(node.value) for child in node.children: queue.append(child) return result
# Problem Description The problem requires implementing a function that processes a binary tree and returns a sequence of node values based on specific rules. The function takes a root node of a tree as input and should return a list of integers representing the "rightmost" nodes in the tree, following certain patterns visible in the examples. # Visual Facts 1. Each example shows a binary tree with numbered nodes (1 to 8 maximum) 2. Some nodes are highlighted in orange, while others are in black 3. Each example has an associated output sequence shown below it 4. Orange arrows point to the right side of each tree 5. The trees have different shapes and depths: - Example 1: depth 4, 8 nodes - Example 2: depth 4, 7 nodes - Example 3: depth 4, 5 nodes 6. The output always starts with node 1 (root) 7. Each tree is a valid binary tree 8. The output sequence length varies (4 numbers in each example) # Visual Patterns Output Sequence Pattern: - The output sequence consists of only the orange-highlighted nodes - The sequence follows top-to-bottom order of the highlighted nodes - The root node is always included in the output - The output sequence includes all the rightmost nodes at each level
def print_tree(node, level=0, prefix="Root: "): """Helper function to create a string representation of the tree""" if not node: return "" ret = " " * level + prefix + str(node.value) + "\n" for i, child in enumerate(node.children): ret += print_tree(child, level + 1, f"Child {i}: ") return ret def test(): Tree0 = TreeNode(0) Tree1 = TreeNode(1, [TreeNode(1), TreeNode(2)]) Tree2 = TreeNode(3, [TreeNode(3)]) Tree3 = TreeNode(2, [TreeNode(2), TreeNode(2, [TreeNode(2)])]) Tree4 = TreeNode(2, [TreeNode(1, [TreeNode(2)]), TreeNode(2, [TreeNode(3)])]) Tree5 = TreeNode(5, [TreeNode(5, [TreeNode(5, [TreeNode(5)]), TreeNode(5)]), TreeNode(5, [TreeNode(5), TreeNode(5)])]) Tree6 = TreeNode(8, [TreeNode(8, [TreeNode(8, [TreeNode(8)]), TreeNode(8)]), TreeNode(8, [TreeNode(8, [TreeNode(8)]), TreeNode(8)])]) Tree7 = TreeNode(2, [TreeNode(2, [TreeNode(2, [TreeNode(1)]), TreeNode(2)]), TreeNode(2, [TreeNode(2), TreeNode(1, [TreeNode(2)])])]) Tree8 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(3)]), TreeNode(3, [TreeNode(3), TreeNode(3, [TreeNode(3)])])]) Tree9 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(8, [TreeNode(3)])]), TreeNode(3, [TreeNode(8), TreeNode(8, [TreeNode(3)])])]) Tree10 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(1, [TreeNode(1)])]), TreeNode(3, [TreeNode(3, [TreeNode(1)]), TreeNode(3, [TreeNode(3)])])]) test_cases = [ (Tree0, [0]), (Tree1, [1, 2]), (Tree2, [3, 3]), (Tree3, [2, 2, 2]), (Tree4, [2, 2, 3]), (Tree5, [5, 5, 5, 5]), (Tree6, [8, 8, 8, 8]), (Tree7, [2, 2, 1, 2]), (Tree8, [3, 3, 3, 3]), (Tree9, [3, 3, 8, 3]), (Tree10, [3, 3, 3, 3]), ] for i, (root, expected_output) in enumerate(test_cases): try: output = solution(root) except Exception as e: error_message = ( f"An exception occurred while running test case {i}:\n" f"Input Tree Structure:\n" f"{print_tree(root)}\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case {i} failed:\n" f"Input Tree Structure:\n" f"{print_tree(root)}\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
class TreeNode: """ Represents a node in a tree. Each node contains an integer value and a list of child TreeNodes. Attributes: value (int): The integer value of the node. children (list): A list of child nodes (TreeNode objects). """ def __init__(self, value: int, children: list=[]): self.value = value self.children = children def solution(root: TreeNode) -> list[int]: """ Computes the output sequence based on the given tree structure. Parameters: root (TreeNode): The root node of the tree. Returns: list[int]: A list of integers representing the output sequence as illustrated in the figure. """
{ "Common Sense": null, "Data Structures": [ "Sequence", "Binary Tree" ], "Dynamic Patterns": [ "Layered Structure" ], "Geometric Objects": [ "Arrow" ], "Mathematical Operations": null, "Spatial Transformations": [ "Filtering" ], "Topological Relations": [ "Adjacency", "Connectivity" ] }
Transformation
q33-2
from collections import deque class TreeNode: """ Represents a node in a tree. Each node contains an integer value and a list of child TreeNodes. Attributes: value (int): The integer value of the node. children (list): A list of child nodes (TreeNode objects). """ def __init__(self, value: int, children: list=[]): self.value = value self.children = children def solution(root: TreeNode) -> list[int]: """ Computes the output sequence based on the given tree structure. Parameters: root (TreeNode): The root node of the tree. Returns: list[int]: A list of integers representing the output sequence as illustrated in the figure. """ if not root: return [] queue = deque([root]) result = [] while queue: level_size = len(queue) for i in range(level_size): node = queue.popleft() if i == 0: result.append(node.value) for child in node.children: queue.append(child) return result
# Problem Description The problem requires implementing a function that processes a binary tree and returns a sequence of node values based on specific rules. The function takes a root node of a tree as input and should return a list of integers representing the "leftmost" nodes in the tree, following certain patterns visible in the examples. # Visual Facts 1. Each example shows a binary tree with numbered nodes (1 to 8 maximum). 2. Some nodes are highlighted in orange, while others are in black. 3. Each example has an associated output sequence shown below it. 4. Orange arrows point to the left side of each tree. 5. The trees have different shapes and depths: - Example 1: depth 4, 8 nodes. - Example 2: depth 4, 7 nodes. - Example 3: depth 4, 5 nodes. 6. The output always starts with node 1 (root). 7. Each tree is a valid binary tree. 8. The output sequence length varies (4 numbers in each example). # Visual Patterns Output Sequence Pattern: - The output sequence consists of only the orange-highlighted nodes. - The sequence follows top-to-bottom order of the highlighted nodes. - The root node is always included in the output. - The output sequence includes all the leftmost nodes at each level.
def tree_to_string(node, level=0): """Helper function to convert a tree to a readable string format.""" if not node: return "None" result = f"TreeNode({node.value})" if node.children: result += " → [" child_strings = [] for child in node.children: child_strings.append(tree_to_string(child, level + 1)) result += ", ".join(child_strings) result += "]" return result def test(): Tree0 = TreeNode(0) Tree1 = TreeNode(1, [TreeNode(1), TreeNode(2)]) Tree2 = TreeNode(3, [TreeNode(3)]) Tree3 = TreeNode(2, [TreeNode(2), TreeNode(2, [TreeNode(2)])]) Tree4 = TreeNode(2, [TreeNode(1, [TreeNode(2)]), TreeNode(2, [TreeNode(3)])]) Tree5 = TreeNode(5, [TreeNode(5, [TreeNode(5, [TreeNode(5)]), TreeNode(5)]), TreeNode(5, [TreeNode(5), TreeNode(5)])]) Tree6 = TreeNode(8, [TreeNode(8, [TreeNode(8, [TreeNode(8)]), TreeNode(8)]), TreeNode(8, [TreeNode(8, [TreeNode(8)]), TreeNode(8)])]) Tree7 = TreeNode(2, [TreeNode(2, [TreeNode(2, [TreeNode(1)]), TreeNode(2)]), TreeNode(2, [TreeNode(2), TreeNode(1, [TreeNode(2)])])]) Tree8 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(3)]), TreeNode(3, [TreeNode(3), TreeNode(3, [TreeNode(3)])])]) Tree9 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(8, [TreeNode(3)])]), TreeNode(3, [TreeNode(8), TreeNode(8, [TreeNode(3)])])]) Tree10 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(1, [TreeNode(1)])]), TreeNode(3, [TreeNode(3, [TreeNode(1)]), TreeNode(3, [TreeNode(3)])])]) test_cases = [ (Tree0, [0]), (Tree1, [1, 1]), (Tree2, [3, 3]), (Tree3, [2, 2, 2]), (Tree4, [2, 1, 2]), (Tree5, [5, 5, 5, 5]), (Tree6, [8, 8, 8, 8]), (Tree7, [2, 2, 2, 1]), (Tree8, [3, 3, 3, 3]), (Tree9, [3, 3, 3, 3]), (Tree10, [3, 3, 3, 3]), ] for i, (root, expected_output) in enumerate(test_cases): try: output = solution(root) except Exception as e: error_message = ( f"An exception occurred while running test case {i}:\n" f"`root`: {tree_to_string(root)}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case {i} failed:\n" f"`root`: {tree_to_string(root)}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
class TreeNode: """ Represents a node in a tree. Each node contains an integer value and a list of child TreeNodes. Attributes: value (int): The integer value of the node. children (list): A list of child nodes (TreeNode objects). """ def __init__(self, value: int, children: list=[]): self.value = value self.children = children def solution(root: TreeNode) -> list[int]: """ Computes the output sequence based on the given tree structure. Parameters: root (TreeNode): The root node of the tree. Returns: list[int]: A list of integers representing the output sequence as illustrated in the figure. """
{ "Common Sense": null, "Data Structures": [ "Sequence", "Binary Tree" ], "Dynamic Patterns": [ "Layered Structure" ], "Geometric Objects": [ "Arrow" ], "Mathematical Operations": null, "Spatial Transformations": [ "Filtering" ], "Topological Relations": [ "Adjacency", "Connectivity" ] }
Transformation
q33-3
class TreeNode: """ Represents a node in a tree. Each node contains an integer value and a list of child TreeNodes. Attributes: value (int): The integer value of the node. children (list): A list of child nodes (TreeNode objects). """ def __init__(self, value: int, children: list=[]): self.value = value self.children = children def solution(root: TreeNode) -> list[int]: """ Computes the output sequence based on the given tree structure. Parameters: root (TreeNode): The root node of the tree. Returns: list[int]: A list of integers representing the output sequence as illustrated in the figure. """ def dfs(node: TreeNode) -> list[int]: # Base case: if the node has no children, it's a leaf node if not node.children: return [node.value] # Recursively visit all children and collect their leaf nodes leaves = [] for child in node.children: leaves.extend(dfs(child)) # Collect leaf nodes from all children return leaves if not root: return [] return dfs(root)
# Problem Description The problem requires implementing a function that processes a binary tree and returns a sequence of node values based on specific rules. The function takes a root node of a tree as input and should return a list of integers representing the "leaf" nodes in the tree. The leaf nodes are those that do not have any children. # Visual Facts 1. Each example shows a binary tree with numbered nodes (1 to 8 maximum). 2. Some nodes are highlighted in orange, while others are in black. 3. Each example has an associated output sequence shown below it. 4. Orange arrows point upwards from the output sequence to the corresponding nodes in the tree. 5. The trees have different shapes and depths: - Example 1: depth 4, 8 nodes. - Example 2: depth 3, 7 nodes. - Example 3: depth 3, 5 nodes. 6. The output sequence consists of the values of the nodes highlighted in orange. 7. The highlighted nodes are the leaf nodes of the tree. # Visual Patterns Output Sequence Pattern: - The output sequence consists of only the leaf nodes (nodes without children). - The sequence follows the left-to-right order of the leaf nodes as they appear in the tree. - The root node is never included in the output if it has children. - The output sequence includes all the leaf nodes at each level, ordered from left to right.
def tree_to_string(node, level=0): """Helper function to convert a tree to a readable string format""" if not node: return "None" result = f"TreeNode({node.value})" if node.children: result += " → [" children_str = ", ".join(tree_to_string(child, level + 1) for child in node.children) result += children_str + "]" return result def test(): Tree0 = TreeNode(0) Tree1 = TreeNode(1, [TreeNode(1), TreeNode(2)]) Tree2 = TreeNode(3, [TreeNode(3)]) Tree3 = TreeNode(2, [TreeNode(2), TreeNode(2, [TreeNode(2)])]) Tree4 = TreeNode(2, [TreeNode(1, [TreeNode(2)]), TreeNode(2, [TreeNode(3)])]) Tree5 = TreeNode(5, [TreeNode(5, [TreeNode(5, [TreeNode(5)]), TreeNode(5)]), TreeNode(5, [TreeNode(5), TreeNode(5)])]) Tree6 = TreeNode(8, [TreeNode(8, [TreeNode(8, [TreeNode(8)]), TreeNode(8)]), TreeNode(8, [TreeNode(8, [TreeNode(8)]), TreeNode(8)])]) Tree7 = TreeNode(2, [TreeNode(2, [TreeNode(2, [TreeNode(1)]), TreeNode(2)]), TreeNode(2, [TreeNode(2), TreeNode(1, [TreeNode(2)])])]) Tree8 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(3)]), TreeNode(3, [TreeNode(3), TreeNode(3, [TreeNode(3)])])]) Tree9 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(8, [TreeNode(3)])]), TreeNode(3, [TreeNode(6), TreeNode(8, [TreeNode(3)])])]) Tree10 = TreeNode(3, [TreeNode(3, [TreeNode(3, [TreeNode(3)]), TreeNode(1, [TreeNode(1)])]), TreeNode(3, [TreeNode(3, [TreeNode(1)]), TreeNode(3, [TreeNode(3)])])]) test_cases = [ (Tree0, [0]), (Tree1, [1, 2]), (Tree2, [3]), (Tree3, [2, 2]), (Tree4, [2, 3]), (Tree5, [5, 5, 5, 5]), (Tree6, [8, 8, 8, 8]), (Tree7, [1, 2, 2, 2]), (Tree8, [3, 3, 3, 3]), (Tree9, [3, 3, 6, 3]), (Tree10, [3, 1, 1, 3]), ] for i, (root, expected_output) in enumerate(test_cases): try: output = solution(root) except Exception as e: error_message = ( f"An exception occurred while running test case {i}:\n" f"`root`: {tree_to_string(root)}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case {i} failed:\n" f"`root`: {tree_to_string(root)}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
class TreeNode: """ Represents a node in a tree. Each node contains an integer value and a list of child TreeNodes. Attributes: value (int): The integer value of the node. children (list): A list of child nodes (TreeNode objects). """ def __init__(self, value: int, children: list=[]): self.value = value self.children = children def solution(root: TreeNode) -> list[int]: """ Computes the output sequence based on the given tree structure. Parameters: root (TreeNode): The root node of the tree. Returns: list[int]: A list of integers representing the output sequence as illustrated in the figure. """
{ "Common Sense": null, "Data Structures": [ "Sequence", "Binary Tree" ], "Dynamic Patterns": [ "Layered Structure" ], "Geometric Objects": [ "Arrow" ], "Mathematical Operations": null, "Spatial Transformations": [ "Filtering" ], "Topological Relations": [ "Adjacency", "Connectivity" ] }
Transformation
q34
def solution(input_matrix: list[list[str]]) -> int: """ Count the number of edges dirived from the given matrix. Args: input_matrix (list[list[str]]): A 2D list where input_matrix[i][j] represents a character at row i, column j. Returns: int: The number of edges in the given matrix. """ rows = len(input_matrix) cols = len(input_matrix[0]) edges = 0 for i in range(rows): for j in range(cols - 1): if input_matrix[i][j] == input_matrix[i][j + 1]: edges += 1 for i in range(rows - 1): for j in range(cols): if input_matrix[i][j] == input_matrix[i + 1][j]: edges += 1 return edges
# Problem Description This is a grid-based edge counting problem where: - We need to count the number of edges between adjacent cells containing identical letters - An edge exists when two adjacent cells (horizontally or vertically) contain the same letter - The goal is to return the total count of such edges in the given matrix # Visual Facts 1. Matrix Structure: - Two example cases are shown - First case: 4×4 matrix with 12 edges - Second case: 5×6 matrix with 22 edges - Matrices contain letters A, B, C, and D 2. Edge Representation: - Edges are shown as red lines connecting adjacent cells - Edges only connect cells with matching letters - Edges can be horizontal or vertical - Each edge connects exactly two cells 3. Example Counts: - First matrix results in 12 edges - Second matrix results in 22 edges # Visual Patterns 1. Edge Formation Rules: - An edge forms only between two adjacent cells containing identical letters - Adjacency is only vertical or horizontal (not diagonal) - Multiple edges can connect to the same cell (up to 4 possible edges per cell) 2. Counting Patterns: - Each edge is counted exactly once - The same letter can form multiple separate groups of connections - Letter groups can form different shapes (squares, lines, etc.) 3. Calculation Method: - Need to check both horizontal and vertical adjacencies - For horizontal edges: compare each cell with its right neighbor - For vertical edges: compare each cell with its bottom neighbor - Sum all valid connections to get total edges
def test(): test_cases = [ { 'matrix': [ ['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I'] ], "expected": 0 }, { 'matrix': [ ['A', 'A', 'A'], ['A', 'A', 'A'], ['A', 'A', 'A'] ], 'expected': 12 }, { 'matrix': [ ['A', 'A', 'C', 'D'], ['A', 'A', 'C', 'D'], ['D', 'B', 'C', 'D'], ['D', 'B', 'C', 'C'] ], 'expected': 12 }, { 'matrix': [ ['A', 'B', 'C', 'D'], ['A', 'B', 'C', 'D'], ['D', 'B', 'C', 'D'], ['D', 'B', 'C', 'D'] ], 'expected': 11 }, { 'matrix': [ ['A', 'B', 'B', 'D'], ['A', 'B', 'B', 'D'], ['D', 'C', 'C', 'D'], ['D', 'C', 'C', 'D'] ], 'expected': 13 }, { 'matrix': [ ['A', 'B', 'B', 'D'], ['A', 'B', 'B', 'D'], ['D', 'C', 'C', 'D'], ['D', 'C', 'C', 'D'], ['D', 'C', 'C', 'D'] ], 'expected': 18 }, { 'matrix': [ ['D', 'A', 'B', 'C', 'D'], ['A', 'A', 'B', 'C', 'D'], ['D', 'C', 'C', 'C', 'D'], ['D', 'C', 'C', 'A', 'D'], ['D', 'C', 'C', 'A', 'D'] ], 'expected': 20 }, { 'matrix': [ ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['D', 'D', 'C', 'D', 'E'], ['D', 'C', 'C', 'C', 'E'], ['D', 'B', 'C', 'E', 'E'] ], 'expected': 18 } ] for test_case in test_cases: try: output = solution(test_case['matrix']) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`input_matrix`:\n" ) for row in test_case['matrix']: error_message += f"{row}\n" error_message += f"\nException: '{str(e)}'" assert False, error_message if output != test_case['expected']: error_message = ( f"The following Test Case failed:\n" f"`input_matrix`:\n" ) for row in test_case['matrix']: error_message += f"{row}\n" error_message += ( f"\nActual Output: {output}\n" f"Expected Output: {test_case['expected']}" ) assert False, error_message test()
def solution(input_matrix: list[list[str]]) -> int: """ Count the number of edges. Args: input_matrix (list[list[str]]). Returns: int: The number of edges in the given matrix. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": null, "Geometric Objects": [ "Line Segment", "Grid" ], "Mathematical Operations": [ "Counting" ], "Spatial Transformations": null, "Topological Relations": [ "Connection", "Adjacency", "Connectivity" ] }
Aggregation
q34-2
def solution(input_matrix: list[list[str]]) -> int: """ Count the number of edges dirived from the given matrix. Args: input_matrix (list[list[str]]): A 2D list where input_matrix[i][j] represents a character at row i, column j. Returns: int: The number of edges in the given matrix. """ rows = len(input_matrix) cols = len(input_matrix[0]) edges = 0 for i in range(rows - 1): for j in range(cols): if input_matrix[i][j] == input_matrix[i + 1][j]: edges += 1 return edges
# Problem Description This problem involves counting the number of vertical edges in a given matrix. An edge is defined as a connection between two vertically adjacent cells that contain the same letter. The goal is to return the total count of such vertical edges in the given matrix. # Visual Facts 1. **Matrix Structure**: - Two example matrices are shown. - The first matrix is a 4×4 grid. - The second matrix is a 5×6 grid. - Each cell in the matrices contains one of the letters: A, B, C, or D. 2. **Edge Representation**: - Edges are depicted as red lines connecting vertically adjacent cells. - Edges only connect cells with the same letter. - The first matrix has 7 edges. - The second matrix has 12 edges. 3. **Example Counts**: - The first 4×4 matrix results in 7 vertical edges. - The second 5×6 matrix results in 12 vertical edges. # Visual Patterns 1. **Edge Formation Rules**: - An edge forms only between two vertically adjacent cells containing the same letter. - Horizontal adjacencies are not considered for edge formation in this problem. - Each edge connects exactly two cells. 2. **Counting Patterns**: - For each cell in the matrix, check the cell directly below it. - If the cell below contains the same letter, count it as an edge. - Continue this process for all cells except those in the last row (as they have no cell below them). 3. **Calculation Method**: - Iterate through each cell in the matrix. - For each cell, compare it with the cell directly below it. - If they contain the same letter, increment the edge count. - Sum all valid connections to get the total number of vertical edges.
def test(): test_cases = [ { 'matrix': [ ['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I'] ], "expected": 0 }, { 'matrix': [ ['A', 'A', 'A'], ['A', 'A', 'A'], ['A', 'A', 'A'] ], 'expected': 6 }, { 'matrix': [ ['A', 'A', 'C', 'D'], ['A', 'A', 'C', 'D'], ['D', 'B', 'C', 'D'], ['D', 'B', 'C', 'C'] ], 'expected': 9 }, { 'matrix': [ ['A', 'B', 'C', 'D'], ['A', 'B', 'C', 'D'], ['D', 'B', 'C', 'D'], ['D', 'B', 'C', 'D'] ], 'expected': 11 }, { 'matrix': [ ['A', 'B', 'B', 'D'], ['A', 'B', 'B', 'D'], ['D', 'C', 'C', 'D'], ['D', 'C', 'C', 'D'] ], 'expected': 9 }, { 'matrix': [ ['A', 'B', 'B', 'D'], ['A', 'B', 'B', 'D'], ['D', 'C', 'C', 'D'], ['D', 'C', 'C', 'D'], ['D', 'C', 'C', 'D'] ], 'expected': 13 }, { 'matrix': [ ['D', 'A', 'B', 'C', 'D'], ['A', 'A', 'B', 'C', 'D'], ['D', 'C', 'C', 'C', 'D'], ['D', 'C', 'C', 'A', 'D'], ['D', 'C', 'C', 'A', 'D'] ], 'expected': 15 }, { 'matrix': [ ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['D', 'D', 'C', 'D', 'E'], ['D', 'C', 'C', 'C', 'E'], ['D', 'B', 'C', 'E', 'E'] ], 'expected': 14 } ] for test_case in test_cases: input_matrix = test_case['matrix'] expected_output = test_case['expected'] try: output = solution(input_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`input_matrix`:\n" ) for row in input_matrix: error_message += f"{row}\n" error_message += f"\nException: '{str(e)}'" assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`input_matrix`:\n" ) for row in input_matrix: error_message += f"{row}\n" error_message += ( f"\nActual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(input_matrix: list[list[str]]) -> int: """ Count the number of edges dirived from the given matrix. Args: input_matrix (list[list[str]]): A 2D list where input_matrix[i][j] represents a character at row i, column j. Returns: int: The number of edges in the given matrix. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": null, "Geometric Objects": [ "Line Segment", "Grid" ], "Mathematical Operations": [ "Counting" ], "Spatial Transformations": null, "Topological Relations": [ "Connection", "Adjacency", "Connectivity" ] }
Aggregation
q34-3
def solution(input_matrix: list[list[str]]) -> int: """ Count the number of edges dirived from the given matrix. Args: input_matrix (list[list[str]]): A 2D list where input_matrix[i][j] represents a character at row i, column j. Returns: int: The number of edges in the given matrix. """ rows = len(input_matrix) cols = len(input_matrix[0]) edges = 0 for i in range(rows): for j in range(cols - 1): if input_matrix[i][j] == input_matrix[i][j + 1]: edges += 1 return edges
# Problem Description This problem involves counting the number of edges in a grid where each cell contains a letter (A, B, C, or D). An edge is defined as a connection between two horizontally adjacent cells that contain the same letter. The goal is to return the total number of such edges in the given matrix. # Visual Facts 1. **Matrix Structure**: - Two example matrices are shown. - The first matrix is a 4x4 grid. - The second matrix is a 5x6 grid. - Each cell in the matrices contains one of the letters A, B, C, or D. 2. **Edge Representation**: - Edges are represented as red lines connecting horizontally adjacent cells. - Only horizontally adjacent cells with the same letter are connected by an edge. - The number of edges is explicitly counted and displayed for each matrix. 3. **Example Counts**: - The first matrix has 4 edges. - The second matrix has 10 edges. # Visual Patterns 1. **Edge Formation Rules**: - An edge is formed only between two horizontally adjacent cells containing the same letter. - Vertical adjacency does not count towards the edge count. - Each edge connects exactly two cells. 2. **Counting Patterns**: - For each row in the matrix, compare each cell with its right neighbor. - If the letters in both cells are the same, an edge is counted. - The total number of edges is the sum of all such valid horizontal connections. 3. **Calculation Method**: - Iterate through each row of the matrix. - For each cell in a row, compare it with the cell to its immediate right. - If the letters match, increment the edge count. - Continue this process for all rows to get the total number of edges.
def test(): test_cases = [ { 'matrix': [ ['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I'] ], "expected": 0 }, { 'matrix': [ ['A', 'A', 'A'], ['A', 'A', 'A'], ['A', 'A', 'A'] ], 'expected': 6 }, { 'matrix': [ ['A', 'A', 'C', 'D'], ['A', 'A', 'C', 'D'], ['D', 'B', 'C', 'D'], ['D', 'B', 'C', 'C'] ], 'expected': 3 }, { 'matrix': [ ['A', 'B', 'C', 'D'], ['A', 'B', 'C', 'D'], ['D', 'B', 'C', 'D'], ['D', 'B', 'C', 'D'] ], 'expected': 0 }, { 'matrix': [ ['A', 'B', 'B', 'D'], ['A', 'B', 'B', 'D'], ['D', 'C', 'C', 'D'], ['D', 'C', 'C', 'D'] ], 'expected': 4 }, { 'matrix': [ ['A', 'B', 'B', 'D'], ['A', 'B', 'B', 'D'], ['D', 'C', 'C', 'D'], ['D', 'C', 'C', 'D'], ['D', 'C', 'C', 'D'] ], 'expected': 5 }, { 'matrix': [ ['D', 'A', 'B', 'C', 'D'], ['A', 'A', 'B', 'C', 'D'], ['D', 'C', 'C', 'C', 'D'], ['D', 'C', 'C', 'A', 'D'], ['D', 'C', 'C', 'A', 'D'] ], 'expected': 5 }, { 'matrix': [ ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['D', 'D', 'C', 'D', 'E'], ['D', 'C', 'C', 'C', 'E'], ['D', 'B', 'C', 'E', 'E'] ], 'expected': 4 } ] for test_case in test_cases: try: output = solution(test_case['matrix']) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`input_matrix`:\n" ) # Format the matrix for better readability for row in test_case['matrix']: error_message += f"{row}\n" error_message += f"\nException: '{str(e)}'" assert False, error_message if output != test_case['expected']: error_message = ( f"The following Test Case failed:\n" f"`input_matrix`:\n" ) # Format the matrix for better readability for row in test_case['matrix']: error_message += f"{row}\n" error_message += ( f"\nActual Output: {output}\n" f"Expected Output: {test_case['expected']}" ) assert False, error_message test()
def solution(input_matrix: list[list[str]]) -> int: """ Count the number of edges dirived from the given matrix. Args: input_matrix (list[list[str]]): A 2D list where input_matrix[i][j] represents a character at row i, column j. Returns: int: The number of edges in the given matrix. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": null, "Geometric Objects": [ "Line Segment", "Grid" ], "Mathematical Operations": [ "Counting" ], "Spatial Transformations": null, "Topological Relations": [ "Connection", "Adjacency", "Connectivity" ] }
Aggregation
q35
from typing import List import numpy as np def solution(input_matrix: List[List[int]]) -> List[List[int]]: """ Transform the given N*3 matrix as illustrated in the figure. Args: input_matrix: A 2D list where input_matrix[i][j] contains an integer. (i is in range [0, N-1], N % 2 == 0; j is in range [0, 2]) Returns: A 2D list containing the transformed N*3 matrix. """ input_matrix = np.array(input_matrix) n = input_matrix.shape[0] even_rows = input_matrix[0:n:2, :] odd_rows = input_matrix[1:n:2, :] result_matrix = np.vstack((even_rows, odd_rows)) return result_matrix.tolist()
# Problem Description This is a matrix transformation problem where we need to rearrange rows of an N×3 matrix according to specific rules. The input matrix has an even number of rows (N is even), and we need to reorder these rows based on their position (odd/even-numbered rows) while maintaining certain patterns. # Visual Facts 1. Each example shows a transformation of a matrix with 3 columns 2. Matrix dimensions shown in examples: - 2×3 matrix (first example) - 4×3 matrix (second example) - 6×3 matrix (third example) 3. All matrices contain sequential numbers starting from 0 4. The color coding shows three columns: - Left column (pink/salmon) - Middle column (green) - Right column (purple) 5. Each row has exactly 3 elements 6. The number of rows is always even 7. The original sequential ordering is preserved within each row # Visual Patterns 1. **Row Reordering Pattern**: - For N=2: No change in row order - For N=4: Odd-numbered rows (1st, 3rd) are grouped at the top, followed by even-numbered rows (2nd, 4th) - For N=6: Odd-numbered rows (1st, 3rd, 5th) are grouped at the top, followed by even-numbered rows (2nd, 4th, 6th) 2. **General Transformation Rules**: - If matrix has only 2 rows (N=2), no transformation is needed - For matrices with N>2 rows: * All odd-numbered rows (1-based index) move to the first half of the matrix * All even-numbered rows move to the second half of the matrix * The relative order within odd and even groups is preserved 3. **Preservation Rules**: - Elements within each row stay in their original order - Column structure (3 columns) remains unchanged - The total number of rows remains unchanged - The grouping creates two sections: odd-indexed rows section and even-indexed rows section 4. **Mathematical Pattern**: - For a matrix with N rows, the transformation creates: * First N/2 rows: Contains odd-indexed rows from original matrix * Last N/2 rows: Contains even-indexed rows from original matrix
import numpy as np def test(): test_cases = [ ([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], [[1, 2, 3], [7, 8, 9], [4, 5, 6], [10, 11, 12]] ), ([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]], [[1, 2, 3], [7, 8, 9], [13, 14, 15], [4, 5, 6], [10, 11, 12], [16, 17, 18]] ), ([[10, 11, 12], [7, 8, 9], [4, 5, 6], [1, 2, 3]], [[10, 11, 12], [4, 5, 6], [7, 8, 9], [1, 2, 3]]), ([[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4], [5, 5, 5], [6, 6, 6], [7, 7, 7], [8, 8, 8], [9, 9, 9], [10, 10, 10], [11, 11, 11], [12, 12, 12]], [[1, 1, 1], [3, 3, 3], [5, 5, 5], [7, 7, 7], [9, 9, 9], [11, 11, 11], [2, 2, 2], [4, 4, 4], [6, 6, 6], [8, 8, 8], [10, 10, 10], [12, 12, 12]] ), ([[2, 4, 6], [1, 3, 5]], [[2, 4, 6], [1, 3, 5]]) ] for i, (input_matrix, expected_output) in enumerate(test_cases): try: output = np.array(solution(np.array(input_matrix))) except Exception as e: error_message = ( f"An exception occurred while running test case {i+1}:\n" f"`input_matrix`:\n{np.array(input_matrix)}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if not np.array_equal(output, np.array(expected_output)): error_message = ( f"The following Test Case {i+1} failed:\n" f"`input_matrix`:\n{np.array(input_matrix)}\n\n" f"Actual Output:\n{output}\n" f"Expected Output:\n{np.array(expected_output)}" ) assert False, error_message test()
from typing import List def solution(input_matrix: List[List[int]]) -> List[List[int]]: """ Transform the given N*3 matrix as illustrated in the figure. Args: input_matrix: A 2D list where input_matrix[i][j] contains an integer. (i is in range [0, N-1], N % 2 == 0; j is in range [0, 2]) Returns: A 2D list containing the transformed N*3 matrix. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": [ "Alternation", "Layered Structure" ], "Geometric Objects": null, "Mathematical Operations": null, "Spatial Transformations": [ "Swapping", "Grouping" ], "Topological Relations": null }
Transformation
q35-2
from typing import List import numpy as np def solution(input_matrix: List[List[int]]) -> List[List[int]]: """ Transform the given N*3 matrix as illustrated in the figure. Args: input_matrix: A 2D list where input_matrix[i][j] contains an integer. (i is in range [0, N-1], N % 2 == 0; j is in range [0, 2]) Returns: A 2D list containing the transformed N*3 matrix. """ input_matrix = np.array(input_matrix) n = input_matrix.shape[0] odd_rows = input_matrix[1:n:2, :] even_rows = input_matrix[0:n:2, :] result_matrix = np.vstack((odd_rows, even_rows)) return result_matrix.tolist()
# Problem Description This is a matrix transformation problem where we need to rearrange rows of an N×3 matrix according to specific rules. The input matrix has an even number of rows (N is even), and we need to reorder these rows based on their position (odd/even-numbered rows) while maintaining certain patterns. # Visual Facts 1. Each example shows a transformation of a matrix with 3 columns 2. Matrix dimensions shown in examples: - 2×3 matrix (first example) - 4×3 matrix (second example) - 6×3 matrix (third example) 3. All matrices contain sequential numbers starting from 0 4. The color coding shows three columns: - Left column (pink/salmon) - Middle column (green) - Right column (purple) 5. Each row has exactly 3 elements 6. The number of rows is always even 7. The original sequential ordering is preserved within each row # Visual Patterns 1. **Row Reordering Pattern**: - For N=2: No change in row order - For N=4: Even-numbered (1-indexed) rows (2nd, 4th) are grouped at the top, followed by odd-numbered rows (1st, 3rd) - For N=6: Even-numbered (1-indexed) rows (2nd, 4th, 6th) are grouped at the top, followed by odd-numbered rows (1st, 3rd, 5th) 2. **General Transformation Rules**: - If matrix has only 2 rows (N=2), no transformation is needed - For matrices with N>2 rows: * All even-numbered (1-indexed) rows move to the first half of the matrix * All odd-numbered (1-indexed) rows move to the second half of the matrix * The relative order within odd and even groups is preserved 3. **Preservation Rules**: - Elements within each row stay in their original order - Column structure (3 columns) remains unchanged - The total number of rows remains unchanged - The grouping creates two sections: odd-indexed rows section and even-indexed rows section 4. **Mathematical Pattern**: - For a matrix with N rows, the transformation creates: * First N/2 rows: Contains even-indexed rows (1-indexed) from original matrix * Last N/2 rows: Contains odd-indexed rows (1-indexed) from original matrix
import numpy as np def test(): test_cases = [ ([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], [[4, 5, 6], [10, 11, 12], [1, 2, 3], [7, 8, 9]] ), ([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]], [[4, 5, 6], [10, 11, 12], [16, 17, 18], [1, 2, 3], [7, 8, 9], [13, 14, 15]] ), ([[10, 11, 12], [7, 8, 9], [4, 5, 6], [1, 2, 3]], [[7, 8, 9], [1, 2, 3], [10, 11, 12], [4, 5, 6]]), ([[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4], [5, 5, 5], [6, 6, 6], [7, 7, 7], [8, 8, 8], [9, 9, 9], [10, 10, 10], [11, 11, 11], [12, 12, 12]], [[2, 2, 2], [4, 4, 4], [6, 6, 6], [8, 8, 8], [10, 10, 10], [12, 12, 12], [1, 1, 1], [3, 3, 3], [5, 5, 5], [7, 7, 7], [9, 9, 9], [11, 11, 11]] ), ([[2, 4, 6], [1, 3, 5]], [[1, 3, 5], [2, 4, 6]]) ] for test_case in test_cases: input_matrix, expected_output = test_case try: output = solution(input_matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`input_matrix`:\n{np.array(input_matrix)}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if not np.array_equal(np.array(output), np.array(expected_output)): error_message = ( f"The following Test Case failed:\n" f"`input_matrix`:\n{np.array(input_matrix)}\n\n" f"Actual Output:\n{np.array(output)}\n" f"Expected Output:\n{np.array(expected_output)}" ) assert False, error_message test()
from typing import List def solution(input_matrix: List[List[int]]) -> List[List[int]]: """ Transform the given N*3 matrix as illustrated in the figure. Args: input_matrix: A 2D list where input_matrix[i][j] contains an integer. (i is in range [0, N-1], N % 2 == 0; j is in range [0, 2]) Returns: A 2D list containing the transformed N*3 matrix. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": [ "Alternation", "Layered Structure" ], "Geometric Objects": null, "Mathematical Operations": null, "Spatial Transformations": [ "Swapping", "Grouping" ], "Topological Relations": null }
Transformation
q35-3
from typing import List import numpy as np def solution(input_matrix: List[List[int]]) -> List[List[int]]: """ Transform the given N*3 matrix as illustrated in the figure. Args: input_matrix: A 2D list where input_matrix[i][j] contains an integer. (i is in range [0, N-1], N % 2 == 0; j is in range [0, 2]) Returns: A 2D list containing the transformed N*3 matrix. """ input_matrix = np.array(input_matrix) n = input_matrix.shape[0] even_rows = input_matrix[0:n:2, :] odd_rows = input_matrix[1:n:2, :] result_matrix = np.vstack((even_rows, odd_rows)) return result_matrix.tolist()
# Problem Description This is a matrix transformation problem where we need to rearrange rows of an N×4 matrix according to specific rules. The input matrix has an even number of rows (N is even), and we need to reorder these rows based on their position (odd/even-numbered rows) while maintaining certain patterns. # Visual Facts 1. Each example shows a transformation of a matrix with 3 columns 2. Matrix dimensions shown in examples: - 2×4 matrix (first example) - 4×4 matrix (second example) - 6×4 matrix (third example) 3. All matrices contain sequential numbers starting from 0 4. The color coding shows three columns: - Left column (pink/salmon) - Middle column (green) - Right column (purple) 5. Each row has exactly 4 elements 6. The number of rows is always even 7. The original sequential ordering is preserved within each row # Visual Patterns 1. **Row Reordering Pattern**: - For N=2: No change in row order - For N=4: Odd-numbered rows (1st, 3rd) are grouped at the top, followed by even-numbered rows (2nd, 4th) - For N=6: Odd-numbered rows (1st, 3rd, 5th) are grouped at the top, followed by even-numbered rows (2nd, 4th, 6th) 2. **General Transformation Rules**: - If matrix has only 2 rows (N=2), no transformation is needed - For matrices with N>2 rows: * All odd-numbered rows (1-based index) move to the first half of the matrix * All even-numbered rows move to the second half of the matrix * The relative order within odd and even groups is preserved 3. **Preservation Rules**: - Elements within each row stay in their original order - Column structure (4 columns) remains unchanged - The total number of rows remains unchanged - The grouping creates two sections: odd-indexed rows section and even-indexed rows section 4. **Mathematical Pattern**: - For a matrix with N rows, the transformation creates: * First N/2 rows: Contains odd-indexed rows from original matrix * Last N/2 rows: Contains even-indexed rows from original matrix
import numpy as np def test(): test_cases = [ ([[1, 2, 3, 4], [6, 7, 8, 9]], [[1, 2, 3, 4], [6, 7, 8, 9]]), ([[1, 2, 3, 4], [6, 7, 8, 9], [11, 12, 13, 14], [16, 17, 18, 19]], [[1, 2, 3, 4], [11, 12, 13, 14], [6, 7, 8, 9], [16, 17, 18, 19]] ), ([[1, 2, 3, 4], [6, 7, 8, 9], [11, 12, 13, 14], [16, 17, 18, 19], [21, 22, 23, 24], [26, 27, 28, 29]], [[1, 2, 3, 4], [11, 12, 13, 14], [21, 22, 23, 24], [6, 7, 8, 9], [16, 17, 18, 19], [26, 27, 28, 29]] ), ([[1, 2, 3, 4], [6, 7, 8, 9], [11, 12, 13, 14], [16, 17, 18, 19], [21, 22, 23, 24]], [[1, 2, 3, 4], [11, 12, 13, 14], [21, 22, 23, 24], [6, 7, 8, 9], [16, 17, 18, 19]] ), ([[2, 4, 6, 8], [1, 3, 5, 7]], [[2, 4, 6, 8], [1, 3, 5, 7]]) ] for input_matrix, expected_output in test_cases: try: output = solution(np.array(input_matrix)) output = np.array(output) expected_output = np.array(expected_output) if not np.array_equal(output, expected_output): error_message = ( f"The following Test Case failed:\n" f"`input_matrix`:\n{np.array(input_matrix)}\n\n" f"Actual Output:\n{output}\n\n" f"Expected Output:\n{expected_output}" ) assert False, error_message except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`input_matrix`:\n{np.array(input_matrix)}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message test()
from typing import List def solution(input_matrix: List[List[int]]) -> List[List[int]]: """ Transform the given N*3 matrix as illustrated in the figure. Args: input_matrix: A 2D list where input_matrix[i][j] contains an integer. (i is in range [0, N-1], N % 2 == 0; j is in range [0, 2]) Returns: A 2D list containing the transformed N*3 matrix. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": [ "Alternation", "Layered Structure" ], "Geometric Objects": null, "Mathematical Operations": null, "Spatial Transformations": [ "Swapping", "Grouping" ], "Topological Relations": null }
Transformation
q36
from typing import List def solution(numbers: List[int]) -> int: """ Given a sequence of numbers, determine the number of red segments that would be illuminated. Parameters: numbers (List[int]): A list of integers Returns: int: The total number of segments that will turn red based on the combination of the input numbers. """ segment_map = { 0: 0b0111111, 1: 0b0000110, 2: 0b1011011, 3: 0b1001111, 4: 0b1100110, 5: 0b1101101, 6: 0b1111101, 7: 0b0000111, 8: 0b1111111, 9: 0b1101111 } if not numbers: return 0 result = 0b1111111 for number in numbers: result &= segment_map[number] red_blocks = bin(result).count('1') return red_blocks
# Problem Description The problem involves working with seven-segment displays and logical AND operations. Given a sequence of numbers, we need to determine how many segments would be illuminated (shown in red) after performing a logical AND operation on the segment patterns of all input numbers. The result should count the segments that are common to all input numbers in their seven-segment display representation. # Visual Facts 1. Each example shows digital numbers in seven-segment display format 2. The displays use standard seven-segment representation where each digit is formed by up to 7 segments 3. Each example demonstrates AND operations between 2-3 different digits 4. Results are shown with red segments indicating the common segments between all operands 5. Four different examples are provided: - 8 & 1 results in 2 red segments - 5 & 3 results in 4 red segments - 2 & 6 & 4 results in 1 red segment - 7 & 8 & 9 results in 3 red segments # Visual Patterns 1. Logical Pattern: - The red segments in the result represent segments that are ON (active) in ALL input numbers - This is effectively a bitwise AND operation on the segment patterns 2. Segment Conservation: - Result segments can only be present if they appear in all input numbers - The number of red segments is always less than or equal to the minimum number of segments in any input digit 3. Multiple Input Handling: - The operation can handle 2 or more input numbers - When more numbers are involved, fewer segments tend to remain common (red) 4. Segment Rules: - The logical AND operation is applied segment-by-segment - Each segment is treated independently - A segment must be present in all input numbers to appear in the result
def test(): test_cases = [ ([0, 1], 2), ([3, 5], 4), ([5, 3], 4), ([2, 3], 4), ([4, 5], 3), ([6, 7], 2), ([8, 9], 6), ([2, 6, 4], 1), ([7, 8, 9], 3), ([1, 2, 3, 4], 1), ([5, 6, 7, 8], 2), ([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], 0) ] for i, (numbers, expected_output) in enumerate(test_cases): try: output = solution(numbers) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`numbers`: {numbers}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`numbers`: {numbers}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(numbers: List[int]) -> int: """ Given a sequence of numbers, determine the number of red segments that would be illuminated. Parameters: numbers (List[int]): A list of integers Returns: int: The total number of segments that will turn red based on the combination of the input numbers. """
{ "Common Sense": [ "Seven-Segment Display" ], "Data Structures": null, "Dynamic Patterns": null, "Geometric Objects": null, "Mathematical Operations": [ "Logical Operations" ], "Spatial Transformations": null, "Topological Relations": [ "Overlap", "Connectivity" ] }
Direct Calculation
q36-2
from typing import List def solution(numbers: List[int]) -> int: """ Given a sequence of numbers, determine the number of red segments that would be illuminated. Parameters: numbers (List[int]): A list of integers Returns: int: The total number of segments that will turn red based on the combination of the input numbers. """ segment_map = { 0: 0b0111111, 1: 0b0000110, 2: 0b1011011, 3: 0b1001111, 4: 0b1100110, 5: 0b1101101, 6: 0b1111101, 7: 0b0000111, 8: 0b1111111, 9: 0b1101111 } if not numbers: return 0 result = 0b0000000 for number in numbers: result |= segment_map[number] red_blocks = bin(result).count('1') return red_blocks
# Problem Description The problem involves working with seven-segment displays and logical OR operations. Given a sequence of numbers, we need to determine how many segments would be illuminated (shown in red) after performing a logical OR operation on the segment patterns of all input numbers. The result should count the segments that are active in at least one of the input numbers in their seven-segment display representation. # Visual Facts 1. Each example shows digital numbers in seven-segment display format. 2. The displays use standard seven-segment representation where each digit is formed by up to 7 segments. 3. Each example demonstrates OR operations between 2-3 different digits. 4. Results are shown with red segments indicating the segments that are active in at least one of the operands. 5. Four different examples are provided: - **0 OR 8** results 6 red segments. - **5 OR 3** results 6 red segments. - **2 OR 6 OR 4** results 7 red segments. - **1 OR 4 OR 9** results 6 red segments. # Visual Patterns 1. Logical Pattern: - The red segments in the result represent segments that are ON (active) in at least one of the input numbers. - This is effectively a bitwise OR operation on the segment patterns. 2. Segment Activation: - Result segments can be present if they appear in any of the input numbers. - The number of red segments is always equal to or greater than the maximum number of segments in any input digit. 3. Multiple Input Handling: - The operation can handle 2 or more input numbers. - When more numbers are involved, more segments tend to be active (red). 4. Segment Rules: - The logical OR operation is applied segment-by-segment. - Each segment is treated independently. - A segment must be present in at least one input number to appear in the result.
def test(): test_cases = [ ([0, 1], 6), ([3, 5], 6), ([5, 3], 6), ([2, 3], 6), ([4, 5], 6), ([6, 7], 7), ([8, 9], 7), ([2, 6, 4], 7), ([7, 8, 9], 7), ([1, 2, 3, 4], 7), ([5, 6, 7, 8], 7), ([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], 7), ([1, 3], 5), ([1, 4], 4), ] for i, (numbers, expected_output) in enumerate(test_cases): try: output = solution(numbers) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`numbers`: {numbers}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`numbers`: {numbers}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(numbers: List[int]) -> int: """ Given a sequence of numbers, determine the number of red segments that would be illuminated. Parameters: numbers (List[int]): A list of integers Returns: int: The total number of segments that will turn red based on the combination of the input numbers. """
{ "Common Sense": [ "Seven-Segment Display" ], "Data Structures": null, "Dynamic Patterns": null, "Geometric Objects": null, "Mathematical Operations": [ "Logical Operations" ], "Spatial Transformations": null, "Topological Relations": [ "Overlap", "Connectivity" ] }
Direct Calculation
q36-3
from typing import List def solution(numbers: List[int]) -> int: """ Given a sequence of numbers, determine the number of red segments that would be illuminated. Parameters: numbers (List[int]): A list of integers Returns: int: The total number of segments that will turn red based on the combination of the input numbers. """ segment_map = { 0: 0b0111111, 1: 0b0000110, 2: 0b1011011, 3: 0b1001111, 4: 0b1100110, 5: 0b1101101, 6: 0b1111101, 7: 0b0000111, 8: 0b1111111, 9: 0b1101111 } if not numbers: return 0 result = 0b0000000 for number in numbers: result ^= segment_map[number] red_blocks = bin(result).count('1') return red_blocks
# Problem Description The problem involves working with seven-segment displays and logical XOR operations. Given a sequence of numbers, we need to determine how many segments would be illuminated (shown in red) after performing a logical XOR operation on the segment patterns of all input numbers. The result should count the segments that are different between the input numbers in their seven-segment display representation. # Visual Facts 1. Each example shows digital numbers in seven-segment display format. 2. The displays use standard seven-segment representation where each digit is formed by up to 7 segments. 3. Each example demonstrates XOR operations between 2-3 different digits. 4. Results are shown with red segments indicating the segments that differ between the operands. 5. Four different examples are provided: - 0 XOR 1 results in 4 red segments. - 5 XOR 3 results in 2 red segments. - 2 XOR 6 XOR 4 results in 1 red segment. - 1 XOR 4 XOR 9 results in 4 red segments. # Visual Patterns 1. Logical Pattern: - The red segments in the result represent segments that are different between the input numbers. - This is effectively a bitwise XOR operation on the segment patterns. 2. Segment Differentiation: - Result segments can only be present if they differ between the input numbers. - The number of red segments is the count of segments that are different between the input numbers. 3. Multiple Input Handling: - The operation can handle 2 or more input numbers. - When more numbers are involved, the XOR operation is applied cumulatively. 4. Segment Rules: - The logical XOR operation is applied segment-by-segment. - Each segment is treated independently. - A segment will be red if it is different between the input numbers.
def test(): test_cases = [ ([0, 1], 4), ([3, 5], 2), ([5, 3], 2), ([2, 3], 2), ([4, 5], 3), ([6, 7], 5), ([8, 9], 1), ([2, 6, 4], 1), ([1, 4, 9], 4), ([7, 8, 9], 4), ([1, 2, 3, 4], 4), ([5, 6, 7, 8], 3), ([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], 3) ] for i, (numbers, expected_output) in enumerate(test_cases): try: output = solution(numbers) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`numbers`: {numbers}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`numbers`: {numbers}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(numbers: List[int]) -> int: """ Given a sequence of numbers, determine the number of red segments that would be illuminated. Parameters: numbers (List[int]): A list of integers Returns: int: The total number of segments that will turn red based on the combination of the input numbers. """
{ "Common Sense": [ "Seven-Segment Display" ], "Data Structures": null, "Dynamic Patterns": null, "Geometric Objects": null, "Mathematical Operations": [ "Logical Operations" ], "Spatial Transformations": null, "Topological Relations": [ "Overlap", "Connectivity" ] }
Direct Calculation
q37
from math import atan2 def solution(points: list[tuple[int, int]], point_a_index: int, point_b_index: int) -> bool: """ Given a list of points and the index of two points, determine whether the two points should be connected to form the shape in the figure. Args: points (list[tuple[int, int]]): An list of tuples, where each tuple consists of two integers representing the x and y coordinates of a point. The points are not guaranteed to be in any particular order. point_a_index (int): The 0-based index of the first point. point_b_index (int): The 0-based index of the second point. Returns: bool: True if the two points should be connected, False otherwise. """ centroid_x = sum((x for x, y in points)) / len(points) centroid_y = sum((y for x, y in points)) / len(points) def polar_angle(point): x, y = point return atan2(y - centroid_y, x - centroid_x) sorted_points = sorted(range(len(points)), key=lambda i: polar_angle(points[i])) pos_a = sorted_points.index(point_a_index) pos_b = sorted_points.index(point_b_index) return (pos_a - pos_b) % len(points) == 2 or (pos_b - pos_a) % len(points) == 2
# Problem Description This is a geometric problem to determine whether two given points should be connected to form a valid five-pointed star (pentagram). The function needs to: 1. Take a list of 5 coordinate points and indices of 2 points 2. Determine if these two points should be connected based on the rules of pentagram construction 3. Return true if the points should be connected, false otherwise # Visual Facts 1. Coordinate System Facts: - All examples use a standard 8x8 grid coordinate system - Points are positioned at integer coordinates - All coordinates are positive (1-8 range) 2. Structure Facts: - Each example contains exactly 5 points - Each point connects to exactly 2 other points - The resulting shape is always a five-pointed star - No intersections occur at points, only along line segments - The lines form 5 intersections within the pentagon 3. Layout Facts: - The star can be drawn in different orientations and scales - The star doesn't need to be symmetrical (as shown in Example 4) - Points can be at different heights and distances from each other # Visual Patterns 1. Connection Patterns: - If we number points 1-5 in clockwise or counter-clockwise order: * Each point connects to points that are 2 steps away in the sequence * No adjacent points in the sequence are connected * The connection pattern follows: 1→3, 1→4, 2→4, 2→5, 3→5, 3→1, 4→1, 4→2, 5→2, 5→3 2. Geometric Patterns: - The five points form a convex pentagon when connected in sequence - The star is formed by connecting every second point in the sequence - There are exactly 5 intersection points formed by the line segments - Points must be arranged so that line segments can intersect to form the star pattern 3. Implementation Pattern: - Points need to be sorted by their angular position relative to the center point - The connection rule can be verified after establishing the correct sequence of points - Two points should be connected if their positions in the sorted sequence follow the connection pattern mentioned above These patterns suggest that the solution will need to: 1. Find the center point of all points 2. Sort points by their angular position 3. Apply the connection rules based on the sorted sequence
def test(): test_cases = [ ([(2, 5), (4, 7), (3, 2), (5, 2), (6, 5)], 2, 4, True), ([(2, 5), (4, 7), (3, 2), (5, 2), (6, 5)], 2, 3, False), ([(2, 5), (4, 7), (3, 2), (5, 2), (6, 5)], 0, 4, True), ([(2, 5), (4, 7), (3, 2), (5, 2), (6, 5)], 0, 2, False), ([(2, 5), (4, 7), (3, 2), (5, 2), (6, 5)], 1, 3, True), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2)], 0, 4, True), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2)], 0, 1, True), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2)], 1, 3, True), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2)], 2, 4, True), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2)], 2, 3, True), ] for points, point_a_index, point_b_index, expected_output in test_cases: try: output = solution(points, point_a_index, point_b_index) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`points`: {points}\n" f"`point_a_index`: {point_a_index}\n" f"`point_b_index`: {point_b_index}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`points`: {points}\n" f"`point_a_index`: {point_a_index}\n" f"`point_b_index`: {point_b_index}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(points: list[tuple[int, int]], point_a_index: int, point_b_index: int) -> bool: """ Given a list of points and the index of two points, determine whether the two points should be connected to form the shape in the figure. Args: points (list[tuple[int, int]]): An list of tuples, where each tuple consists of two integers representing the x and y coordinates of a point. The points are not guaranteed to be in any particular order. point_a_index (int): The 0-based index of the first point. point_b_index (int): The 0-based index of the second point. Returns: bool: True if the two points should be connected, False otherwise. """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": [ "Cyclic Motion", "Circular Arrangement" ], "Geometric Objects": [ "Pentagram", "Coordinate System", "Grid", "Line Segment", "Point" ], "Mathematical Operations": null, "Spatial Transformations": null, "Topological Relations": [ "Connectivity", "Adjacency", "Intersection" ] }
Validation
q37-2
from math import atan2 def solution(points: list[tuple[int, int]], point_a_index: int, point_b_index: int) -> bool: """ Given a list of points and the index of two points, determine whether the two points should be connected to form the shape in the figure. Args: points (list[tuple[int, int]]): An list of tuples, where each tuple consists of two integers representing the x and y coordinates of a point. The points are not guaranteed to be in any particular order. point_a_index (int): The 0-based index of the first point. point_b_index (int): The 0-based index of the second point. Returns: bool: True if the two points should be connected, False otherwise. """ centroid_x = sum((x for x, y in points)) / len(points) centroid_y = sum((y for x, y in points)) / len(points) def polar_angle(point): x, y = point return atan2(y - centroid_y, x - centroid_x) sorted_points = sorted(range(len(points)), key=lambda i: polar_angle(points[i])) pos_a = sorted_points.index(point_a_index) pos_b = sorted_points.index(point_b_index) return (pos_a - pos_b) % len(points) == 2 or (pos_b - pos_a) % len(points) == 2
# Problem Description This problem involves determining whether two given points should be connected to form a six-pointed star pattern. The function needs to: 1. Take a list of coordinate points and indices of 2 points. 2. Determine if these two points should be connected based on the rules of six-pointed star construction. 3. Return true if the points should be connected, false otherwise. # Visual Facts 1. Coordinate System Facts: - The examples use a standard 8x8 grid coordinate system. - Points are positioned at integer coordinates. - All coordinates are positive (1-8 range). 2. Structure Facts: - Each example contains exactly 6 points. - Each point connects to exactly 2 other points. - The resulting shape is always a six-pointed star. - No intersections occur at points, only along line segments. - The lines form intersections within the hexagon. 3. Layout Facts: - The star can be drawn in different orientations and scales. - The star doesn't need to be symmetrical (as shown in Example 4). - Points can be at different heights and distances from each other. # Visual Patterns 1. Connection Patterns: - If we number points 1-6 in clockwise or counter-clockwise order: * Each point connects to points that are 2 steps away in the sequence. * No adjacent points in the sequence are connected. * The connection pattern follows: 1→3, 1→5, 2→4, 2→6, 3→5, 3→1, 4→6, 4→2, 5→1, 5→3, 6→2, 6→4. 2. Geometric Patterns: - The six points form a convex hexagon when connected in sequence. - The star is formed by connecting every second point in the sequence. - There are exactly 6 intersection points formed by the line segments. - Points must be arranged so that line segments can intersect to form the star pattern. 3. Implementation Pattern: - Points need to be sorted by their angular position relative to the center point. - The connection rule can be verified after establishing the correct sequence of points. - Two points should be connected if their positions in the sorted sequence follow the connection pattern mentioned above.
def test(): test_cases = [ ([(2, 5), (4, 7), (6, 5), (5, 2), (3, 1), (1, 2)], 2, 4, True), ([(2, 5), (4, 7), (6, 5), (5, 2), (3, 1), (1, 2)], 2, 3, False), ([(2, 5), (4, 7), (6, 5), (5, 2), (3, 1), (1, 2)], 0, 4, True), ([(2, 5), (4, 7), (6, 5), (5, 2), (3, 1), (1, 2)], 0, 2, True), ([(2, 5), (4, 7), (6, 5), (5, 2), (3, 1), (1, 2)], 1, 3, True), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2), (1, 5)], 0, 4, True), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2), (1, 5)], 0, 1, False), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2), (1, 5)], 1, 3, True), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2), (1, 5)], 2, 4, True), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2), (1, 5)], 2, 5, False), ] for points, point_a_index, point_b_index, expected_output in test_cases: try: output = solution(points, point_a_index, point_b_index) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`points`: {points}\n" f"`point_a_index`: {point_a_index}\n" f"`point_b_index`: {point_b_index}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`points`: {points}\n" f"`point_a_index`: {point_a_index}\n" f"`point_b_index`: {point_b_index}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(points: list[tuple[int, int]], point_a_index: int, point_b_index: int) -> bool: """ Given a list of points and the index of two points, determine whether the two points should be connected to form the shape in the figure. Args: points (list[tuple[int, int]]): An list of tuples, where each tuple consists of two integers representing the x and y coordinates of a point. The points are not guaranteed to be in any particular order. point_a_index (int): The 0-based index of the first point. point_b_index (int): The 0-based index of the second point. Returns: bool: True if the two points should be connected, False otherwise. """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": [ "Cyclic Motion", "Circular Arrangement" ], "Geometric Objects": [ "Coordinate System", "Hexagon", "Grid", "Line Segment", "Point" ], "Mathematical Operations": null, "Spatial Transformations": null, "Topological Relations": [ "Connectivity", "Adjacency", "Intersection" ] }
Validation
q37-3
from math import atan2 def solution(points: list[tuple[int, int]], point_a_index: int, point_b_index: int) -> bool: """ Given a list of points and the index of two points, determine whether the two points should be connected to form the shape in the figure. Args: points (list[tuple[int, int]]): An list of tuples, where each tuple consists of two integers representing the x and y coordinates of a point. The points are not guaranteed to be in any particular order. point_a_index (int): The 0-based index of the first point. point_b_index (int): The 0-based index of the second point. Returns: bool: True if the two points should be connected, False otherwise. """ centroid_x = sum((x for x, y in points)) / len(points) centroid_y = sum((y for x, y in points)) / len(points) def polar_angle(point): x, y = point return atan2(y - centroid_y, x - centroid_x) sorted_points = sorted(range(len(points)), key=lambda i: polar_angle(points[i])) pos_a = sorted_points.index(point_a_index) pos_b = sorted_points.index(point_b_index) return (pos_a - pos_b) % len(points) == 1 or (pos_b - pos_a) % len(points) == 1
# Problem Description This problem requires determining whether two given points should be connected to form a pentagon. The function takes a list of points and the indices of two points, and it returns whether these two points should be connected to form a valid pentagon. The points are not guaranteed to be in any particular order. # Visual Facts 1. **Coordinate System Facts:** - The coordinate system is an 8x8 grid. - Points are positioned at integer coordinates within this grid. - All coordinates are positive and range from 1 to 8. 2. **Structure Facts:** - Each example contains exactly 5 points. - Each point is connected to exactly 2 other points. - The resulting shape is always a pentagon. - The pentagon is a closed figure with 5 sides. 3. **Layout Facts:** - The pentagon can be drawn in different orientations and scales. - The pentagon does not need to be symmetrical. - Points can be at different heights and distances from each other. # Visual Patterns 1. **Connection Patterns:** - Points are connected in a sequence to form a closed loop. - Each point connects to its adjacent points in the sequence. - The sequence forms a pentagon without any intersections. 2. **Geometric Patterns:** - The five points form a convex pentagon when connected in sequence. - The pentagon is formed by connecting each point to its next neighbor in the sequence. - The sequence of points can be in clockwise or counter-clockwise order. 3. **Implementation Pattern:** - Points need to be sorted by their angular position relative to the center point. - Two points should be connected if they are adjacent in the sorted sequence. - The function should determine the correct sequence of points and check if the given points are adjacent in this sequence.
def test(): test_cases = [ ([(2, 5), (4, 7), (3, 2), (5, 2), (6, 5)], 2, 4, False), ([(2, 5), (4, 7), (3, 2), (5, 2), (6, 5)], 2, 3, True), ([(2, 5), (4, 7), (3, 2), (5, 2), (6, 5)], 0, 4, False), ([(2, 5), (4, 7), (3, 2), (5, 2), (6, 5)], 0, 2, True), ([(2, 5), (4, 7), (3, 2), (5, 2), (6, 5)], 1, 3, False), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2)], 0, 4, False), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2)], 0, 1, False), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2)], 1, 3, False), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2)], 2, 4, False), ([(3, 8), (3, 0), (1, 1), (5, 6), (8, 2)], 2, 3, False), ] for points, point_a_index, point_b_index, expected_output in test_cases: try: output = solution(points, point_a_index, point_b_index) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`points`: {points}\n" f"`point_a_index`: {point_a_index}\n" f"`point_b_index`: {point_b_index}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`points`: {points}\n" f"`point_a_index`: {point_a_index}\n" f"`point_b_index`: {point_b_index}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(points: list[tuple[int, int]], point_a_index: int, point_b_index: int) -> bool: """ Given a list of points and the index of two points, determine whether the two points should be connected to form the shape in the figure. Args: points (list[tuple[int, int]]): An list of tuples, where each tuple consists of two integers representing the x and y coordinates of a point. The points are not guaranteed to be in any particular order. point_a_index (int): The 0-based index of the first point. point_b_index (int): The 0-based index of the second point. Returns: bool: True if the two points should be connected, False otherwise. """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": [ "Cyclic Motion", "Circular Arrangement" ], "Geometric Objects": [ "Coordinate System", "Grid", "Line Segment", "Pentagon", "Point" ], "Mathematical Operations": null, "Spatial Transformations": null, "Topological Relations": [ "Connectivity", "Adjacency", "Intersection" ] }
Validation
q38
from typing import List def solution(colors: List[int], line_position: int) -> List[int]: """ Transforms a 1D color array based on a given dashed line position. Args: colors (List[int]): A 1D array representing colors where: - 0 = white - 1 = light blue - 2 = dark blue line_position (int): The position of the dashed line used for transformation Returns: List[int]: A new 1D array with transformed colors where: - 0 = white - 1 = light blue - 2 = dark blue """ n = len(colors) left_part = colors[:line_position][::-1] right_part = colors[line_position:] max_length = max(len(left_part), len(right_part)) result = [] for i in range(max_length): left_value = left_part[i] if i < len(left_part) else 0 right_value = right_part[i] if i < len(right_part) else 0 merged_value = left_value + right_value result.append(min(merged_value, 2)) # Ensure the value does not exceed 2 return result
# Problem Description - The task involves transforming a 1d array of colors based on a given "vertical axis" (specified by the line_position). The input list contains integer values representing colors: 0 for white 1 for light blue 2 for dark blue - The transformation involves folding the 1d array around the vertical axis (line_position) and merging values on either side of the axis using a specific rule. The output is a new 1D list with transformed values. # Visual Facts - Each example starts with an input 1d array and a specified line_position (indicated by a dashed vertical line). - The 1d array is folded along the line_position. Values to the left of the axis are flipped (mirrored) and merged with the corresponding values to the right. - The output 1d array has fewer columns than the input 1d array. - The merging process appears to follow a rule where overlapping values are combined: - Values to the left of the axis are flipped (mirrored) and added to the corresponding values on the right. 1. If the sum equals 0, the result is white. 2. If the sum equals 1, the result is light blue. 3. If the sum equals 2, the result is dark blue. 4. There will never be a result greater than 2. 5. If the mirrored values on the left have no corresponding values on the right, it is assumed that the corresponding values on the right are 0, and the addition is performed accordingly. - Examples Example 1: Input: [1, 0, 1], line_position = 1 Transformation: Fold [1] (left of axis) onto [0] (right of axis). Merge: 1 + 0 = 1 Output: [1, 1] Example 2: Input: [0, 1, 1, 0, 1], line_position = 3 Transformation: Fold [0, 1, 1] onto [0, 1]. Merge: 1 + 0 = 1, 1 + 1 = 2, 0 + 0 = 0 Output: [1, 2, 0] Example 3: Input: [0, 1, 0, 0], line_position = 3 Transformation: Fold [0, 1, 0] onto [0]. Merge: 0 + 0 = 0, 1 + 0 = 1, 0 + 0 = 0 Output: [0, 1, 0] # Visual Patterns 1. 1d array Folding Values on the left of the line_position are reversed and folded over to overlap with values on the right. The length of the output list is determined by the maximum distance between line_position and either end of the input list. 2. Output Length For an input list of length n and a line_position of p, The output length is max(p, n - p).
def test(): test_cases = [ ([0, 1, 0, 1], 2, [1, 1]), ([0, 1, 0, 1], 1, [1, 0, 1]), ([1, 1, 0, 1], 2, [1, 2]), ([1, 1, 1, 1], 2, [2, 2]), ([0, 1, 0, 0], 3, [0, 1, 0]), ([0, 1, 1, 1, 0, 1], 2, [2, 1, 0, 1]), ([0, 1, 1, 1, 0, 1], 1, [1, 1, 1, 0, 1]), ([1, 1, 1, 0, 1, 1], 1, [2, 1, 0, 1, 1]), ([1, 0, 1, 1, 0, 1], 4, [1, 2, 0, 1]) ] for i, (colors, line_position, expected_output) in enumerate(test_cases): try: output = solution(colors, line_position) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`colors`: {colors}\n" f"`line_position`: {line_position}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`colors`: {colors}\n" f"`line_position`: {line_position}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(colors: List[int], line_position: int) -> List[int]: """ Transforms a 1D color array based on a given dashed line position. Args: colors (List[int]): A 1D array representing colors where: - 0 = white - 1 = light blue - 2 = dark blue line_position (int): The position of the dashed line used for transformation Returns: List[int]: A new 1D array with transformed colors where: - 0 = white - 1 = light blue - 2 = dark blue """
{ "Common Sense": null, "Data Structures": [ "Sequence" ], "Dynamic Patterns": [ "Mirror Reflection" ], "Geometric Objects": [ "Rectangle", "Grid", "Line" ], "Mathematical Operations": [ "Value Comparison", "Basic Arithmetic" ], "Spatial Transformations": [ "Flipping", "Mapping" ], "Topological Relations": [ "Adjacency" ] }
Direct Calculation
q38-2
from typing import List def solution(numbers: List[int], line_position: int) -> List[int]: """ You are given a list of numbers. Your task is to generate a new list based on the given dashed line position. Input: - numbers: A 1D list of integers representing the initial state of the numbers. - line_position: An integer indicating the position of the dashed line in the transformation process. Output: - Return a 1D list of integers that represents the newly generated numbers after the transformation. """ left_part = numbers[:line_position][::-1] right_part = numbers[line_position:] max_length = max(len(left_part), len(right_part)) result = [] for i in range(max_length): left_value = left_part[i] if i < len(left_part) else 0 right_value = right_part[i] if i < len(right_part) else 0 merged_value = left_value + right_value result.append(merged_value) return result
# Problem Description The task involves transforming a 1D array of integers based on a given "vertical axis" (specified by the line_position). The transformation involves folding the array around the vertical axis and merging values on either side of the axis using a specific rule. The output is a new 1D array with transformed values. # Visual Facts 1. Each example starts with an input 1D array and a specified line_position (indicated by a dashed vertical line). 2. The 1D array is folded along the line_position. Values to the left of the axis are flipped (mirrored) and merged with the corresponding values to the right. 3. The output 1D array has fewer elements than the input 1D array. 4. The merging process involves adding overlapping values: - Values to the left of the axis are flipped (mirrored) and added to the corresponding values on the right. - If the mirrored values on the left have no corresponding values on the right, it is assumed that the corresponding values on the right are 0, and the addition is performed accordingly. # Visual Patterns 1. **Folding Mechanism**: - The values to the left of the line_position are reversed and then added to the values on the right of the line_position. 2. **Output Length**: - The length of the output array is determined by the maximum distance between the line_position and either end of the input array. - Specifically, the output length is `max(line_position, len(numbers) - line_position)`. 3. **Addition Rule**: - For each position `i` in the output array, the value is calculated as `numbers[line_position + i - 1] + numbers[line_position - i]`.
def test(): test_cases = [ ([1, 2, 3], 1, [3, 3]), ([1, 2, 3], 2, [5, 1]), ([1, 2, 3, 2, 1], 3, [5, 3, 1]), ([1, 2, 3, 2, 1], 2, [5, 3, 1]), ([1, 2, 3, 2, 1], 1, [3, 3, 2, 1]), ([1, 2, 3, 4], 3, [7, 2, 1]), ([1, 2, 3, 4], 2, [5, 5]), ([5, 6, 7, 8], 1, [11, 7, 8]), ([1, 1, 1, 0, 1, 1], 4, [1, 2, 1, 1]) ] for numbers, line_position, expected_output in test_cases: try: output = solution(numbers, line_position) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`numbers`: {numbers}\n" f"`line_position`: {line_position}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`numbers`: {numbers}\n" f"`line_position`: {line_position}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(numbers: List[int], line_position: int) -> List[int]: """ You are given a list of numbers. Your task is to generate a new list based on the given dashed line position. Input: - numbers: A 1D list of integers representing the initial state of the numbers. - line_position: An integer indicating the position of the dashed line in the transformation process. Output: - Return a 1D list of integers that represents the newly generated numbers after the transformation. """
{ "Common Sense": null, "Data Structures": [ "Sequence" ], "Dynamic Patterns": [ "Mirror Reflection" ], "Geometric Objects": [ "Rectangle", "Grid", "Line" ], "Mathematical Operations": [ "Value Comparison", "Basic Arithmetic" ], "Spatial Transformations": [ "Flipping", "Mapping" ], "Topological Relations": [ "Adjacency" ] }
Direct Calculation
q38-3
from typing import List def solution(numbers: List[int], line_position: int) -> List[int]: """ You are given a list of numbers. Your task is to generate a new list based on the given dashed line position. Input: - numbers: A 1D list of integers representing the initial state of the numbers. - line_position: An integer indicating the position of the dashed line in the transformation process. Output: - Return a 1D list of integers that represents the newly generated numbers after the transformation. """ left_part = numbers[:line_position][::-1] right_part = numbers[line_position:] max_length = max(len(left_part), len(right_part)) result = [] for i in range(max_length): left_value = left_part[i] if i < len(left_part) else 0 right_value = right_part[i] if i < len(right_part) else 0 merged_value = right_value - left_value result.append(merged_value) return result
# Problem Description The task involves transforming a 1D array of integers based on a given "vertical axis" (specified by the line_position). The transformation involves folding the array around the vertical axis and merging values on either side of the axis using a specific rule. The output is a new 1D array with transformed values. # Visual Facts 1. Each example starts with an input 1D array and a specified line_position (indicated by a dashed vertical line). 2. The 1D array is folded along the line_position. Values to the left of the axis are flipped (mirrored) and merged with the corresponding values to the right. 3. The output 1D array has fewer elements than the input 1D array. 4. The merging process involves subtracting overlapping values: - Subtract the values on the right from the mirrored (flipped) values on the left. - If the mirrored values on the left have no corresponding values on the right, it is assumed that the corresponding values on the right are 0, and subtraction is performed accordingly. - If the mirrored values on the right have no corresponding values on the left, it is assumed that the corresponding values on the left are 0, and subtraction is performed accordingly. # Visual Patterns 1. **Folding Mechanism**: - The values on the right are subtracted from the reversed values on the left of the line_position. - For example, if the array is [1, 2, 3] and the line_position is at 1, then 1 is flipped to the position of 2, resulting in 2 - 1 = 1. 0 is flipped to the position of 3, resulting in 3 - 0 = 3. Therefore, the final result is [1, 3]. 2. **Output Length**: - The length of the output array is determined by the maximum distance between the line_position and either end of the input array. - Specifically, the output length is `max(line_position, len(numbers) - line_position)`. 3. **Subtraction Rule**: - Subtract the values on the right from the corresponding values on the left after they have been flipped. - For each position `i` (0-indexed) in the output array, the value is calculated as `output_numbers[i] = numbers[line_position + i] - numbers[line_position - i - 1]`.
def test(): test_cases = [ ([1, 2, 3], 1, [1, 3]), ([1, 2, 3], 2, [1, -1]), ([1, 2, 3, 4, 5], 3, [1, 3, -1]), ([1, 2, 3, 4, 5], 2, [1, 3, 5]), ([1, 2, 3, 4, 5], 1, [1, 3, 4, 5]), ([1, 2, 3, 2], 3, [-1, -2, -1]), ([5, 6, 7, 5], 2, [1, 0]), ([1, 2, 3, 2], 1, [1, 3, 2]), ([1, 1, 1, 0, 1, 1], 4, [1, 0, -1, -1]) ] for numbers, line_position, expected_output in test_cases: try: output = solution(numbers, line_position) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`numbers`: {numbers}\n" f"`line_position`: {line_position}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`numbers`: {numbers}\n" f"`line_position`: {line_position}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(numbers: List[int], line_position: int) -> List[int]: """ You are given a list of numbers. Your task is to generate a new list based on the given dashed line position. Input: - numbers: A 1D list of integers representing the initial state of the numbers. - line_position: An integer indicating the position of the dashed line in the transformation process. Output: - Return a 1D list of integers that represents the newly generated numbers after the transformation. """
{ "Common Sense": null, "Data Structures": [ "Sequence" ], "Dynamic Patterns": [ "Mirror Reflection" ], "Geometric Objects": [ "Rectangle", "Grid", "Line" ], "Mathematical Operations": [ "Value Comparison", "Basic Arithmetic" ], "Spatial Transformations": [ "Flipping", "Mapping" ], "Topological Relations": [ "Adjacency" ] }
Direct Calculation
q39
from typing import List, Tuple def move_direction(x: int, y: int, direction: str) -> Tuple[int, int]: """Move to the next cell based on the given direction.""" if direction == 'L': return x, y - 1 elif direction == 'R': return x, y + 1 elif direction == 'U': return x - 1, y elif direction == 'D': return x + 1, y return x, y def escape_path(matrix: List[List[str]], start_x: int, start_y: int) -> int: """Simulate the escape from a given start position.""" n = len(matrix) m = len(matrix[0]) visited = set() x, y = start_x, start_y x_, y_ = x, y while 1 <= x <= n and 1 <= y <= m: end_point = (x, y) if (x, y) in visited: x, y = move_direction(x, y, direction=matrix[x_-1][y_-1]) continue visited.add((x, y)) x_, y_ = x, y x, y = move_direction(x, y, matrix[x-1][y-1]) return end_point def solution(matrix: List[List[str]], start: Tuple[int, int]) -> Tuple[int, int]: """ Given the starting coordinates, find the ending coordinates in a 2D matrix. Args: matrix (List[List[str]]): A 2D matrix where each element is one of four upper case characters start (Tuple[int, int]): The starting position as (row, col) coordinates (1-indexed) Returns: Tuple[int, int]: The ending position as (row, col) coordinates (1-indexed) """ return escape_path(matrix, start[0], start[1])
# Problem Description This is a matrix traversal problem where: - We navigate through a matrix containing directional characters (R, L, U, D) - Movement starts from a given coordinate and follows the directional instructions - The goal is to find the final coordinates where the path exits the matrix - The coordinates are 1-indexed (as shown in the examples), the coordinates are (row, column) - There are special rules governing direction changes and path termination # Visual Facts 1. Matrix Structure: - First example show a 3x3 matrix, the second example shows a 3x4 matrix - Contains only directional characters: R (right), L (left), U (up), D (down) - Uses 1-based indexing for both rows and columns 2. Path Visualization: - Green dot marks START position - Red arrow marks END position - Orange arrows show the path of movement - Purple arrows point to an important rule note 3. Start/End Markers: - Example 1: Starts at (1,1), - the letter at row 1 col 1 is R, so we move right to (1,2) - the letter at row 1 col 2 is D, so we move down to (2,2) - the letter at row 2 col 2 is L, so we move left to (2,1) - the letter at row 2 col 1 is R, so we move right to (2,2) - (2, 2) has been visited, so direction remains right - now we move right to (2,3), containing a letter U, so then up to (1,3), - the letter at (1,3) is U, since we can't move up, we exit at (1,3) - Example 2: Starts at (1,2), ends at (3,1) - follow the path as per the directional letters in the matrix # Visual Patterns 1. Movement Rules: - Each cell's letter determines the direction when leaving that cell 2. Critical Constraints: - "Each block can only change direction once" (explicitly stated) - When revisiting a cell, its direction instruction is ignored (continue in current direction) 3. Path Termination: - The path ends when it would move outside the matrix boundaries - The last valid position before exiting becomes the end coordinates 4. Direction Change Pattern: - First visit to a cell: Apply the direction indicated by the letter - Subsequent visits: change directions based on the letter of the following cell - This creates a deterministic path through the matrix 5. Traversal Pattern: - The path can intersect with itself, but there is no loop because each cell can change direction only once - The solution always reaches an exit point (no infinite loops) - Movement is continuous until reaching a matrix boundary
def test(): test_cases = [ ( [['R', 'D', 'L'], ['L', 'U', 'R'], ['U', 'L', 'U']], (2, 2), (2, 1) ), ( [['D', 'R', 'L', 'D'], ['U', 'L', 'U', 'L'], ['D', 'U', 'U', 'R'], ['R', 'D', 'D', 'L']], (3, 3), (4, 2) ), ( [['D', 'R', 'D', 'D'], ['L', 'U', 'R', 'U']], (2, 2), (2, 4) ), ( [['R', 'D', 'R', 'U', 'D'], ['U', 'L', 'U', 'L', 'U'], ['D', 'U', 'U', 'R', 'R']], (1, 2), (1, 4) ), ( [['D', 'R', 'D', 'U'], ['U', 'U', 'R', 'L'], ['L', 'D', 'R', 'U']], (2, 2), (3, 1) ) ] for i, (matrix, start, expected_output) in enumerate(test_cases): try: output = solution(matrix, start) except Exception as e: error_message = ( f"An exception occurred while running test case {i + 1}:\n" f"`matrix`:\n" f"{'\n'.join([str(row) for row in matrix])}\n" f"`start`: {start}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case {i + 1} failed:\n" f"`matrix`:\n" f"{'\n'.join([str(row) for row in matrix])}\n" f"`start`: {start}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List, Tuple def solution(matrix: List[List[str]], start: Tuple[int, int]) -> Tuple[int, int]: """ Given the starting coordinates, find the ending coordinates in a 2D matrix. Args: matrix (List[List[str]]): A 2D matrix where each element is one of four upper case characters start (Tuple[int, int]): The starting position as (row, col) coordinates (1-indexed) Returns: Tuple[int, int]: The ending position as (row, col) coordinates (1-indexed) """
{ "Common Sense": null, "Data Structures": [ "Path", "Matrix" ], "Dynamic Patterns": null, "Geometric Objects": [ "Grid", "Point", "Arrow", "Coordinate System" ], "Mathematical Operations": null, "Spatial Transformations": null, "Topological Relations": [ "Boundary", "Connectivity", "Intersection" ] }
Iterative Calculation
q39-2
from typing import List, Tuple def solution(matrix: List[List[str]], start: Tuple[int, int], home: Tuple[int, int]) -> bool: """ Determine if it's possible to reach home given the starting point and the house coordinates. Args: matrix (List[List[str]]): A 2D matrix where each element is one of four upper case characters start (Tuple[int, int]): The starting position as (row, col) coordinates (1-indexed) home (Tuple[int, int]): The home position as (row, col) coordinates (1-indexed) Output: Return True if it's possible to reach home, otherwise False """ # Convert 1-indexed positions to 0-indexed for easier handling in Python lists start = (start[0] - 1, start[1] - 1) home = (home[0] - 1, home[1] - 1) n, m = len(matrix), len(matrix[0]) # Direction vectors for 'R', 'L', 'U', 'D' directions = { 'R': (0, 1), 'L': (0, -1), 'U': (-1, 0), 'D': (1, 0) } # Function to check if a position is out of bounds def out_of_bounds(r, c): return r < 0 or r >= n or c < 0 or c >= m # Starting from the initial position r, c = start visited = set() # print(home) while True: # Check if the current position is the home position if (r, c) == home: return True # If the position is out of bounds, check if it's the home position if out_of_bounds(r, c): if (r, c) == home: return True else: return False # If the position has been visited before, continue in the current direction if (r, c) in visited: dr, dc = current_direction else: # Mark the cell as visited and change direction based on the cell's character visited.add((r, c)) dr, dc = directions[matrix[r][c]] current_direction = (dr, dc) # Move to the next position r, c = r + dr, c + dc
# Problem Description This problem involves navigating through a matrix where each cell contains a directional character ('R', 'L', 'U', 'D'). Starting from a given coordinate, the goal is to determine if it's possible to reach a specified home position by following the directional instructions. Each cell can change direction only once, and the coordinates are 1-indexed. # Visual Facts 1. **Matrix Structure**: - The matrix contains directional characters: 'R' (right), 'L' (left), 'U' (up), 'D' (down). - The matrix uses 1-based indexing for both rows and columns. - Example 1: 3x3 matrix. - Example 2: 3x4 matrix. 2. **Start/End Markers**: - Example 1: Starts at (1,1), ends at (0,2). - Example 2: Starts at (1,2), ends at (3,5). 3. **Home Location**: - The home is located outside the boundaries of the matrix, so the coordinates will extend beyond the matrix range. - The row of the home could be 0 or len(matrix) + 1 (1-indexed). - The column of the home could be 0 or len(matrix[0]) + 1 (1-indexed). 3. **Path Visualization**: - Green dot marks the START position. - Black house symbol marks the HOME position. - Orange arrows show the path of movement. - Purple arrow points to an important rule note: "Each block can only change direction once." # Visual Patterns 1. **Movement Rules**: - Each cell's letter determines the direction when leaving that cell. - The path follows the direction indicated by the letter in the current cell. 2. **Critical Constraints**: - "Each block can only change direction once" (explicitly stated). - When revisiting a cell, its direction instruction is ignored (continue in the current direction). 3. **Path Termination**: - The path ends when it would move outside the matrix boundaries. - If the path reaches the home position when it leaves the matrix boundaries, return True; otherwise, return False. 4. **Direction Change Pattern**: - First visit to a cell: Apply the direction indicated by the letter. - Subsequent visits: Continue in the current direction without changing based on the cell's letter. - This creates a deterministic path through the matrix. 5. **Traversal Pattern**: - The path can intersect with itself, but there is no loop because each cell can change direction only once. - The solution always reaches an exit point (no infinite loops). - Movement is continuous until reaching a matrix boundary.
def test(): # Test case 1 matrix = [ ['R', 'D', 'L'], ['L', 'U', 'R'], ['U', 'L', 'U'] ] home = (0, 2) start = (1, 2) try: result = solution(matrix, start, home) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`matrix`:\n{'\n'.join([str(row) for row in matrix])}\n" f"`start`: {start}\n" f"`home`: {home}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message expected_result = True if result != expected_result: error_message = ( f"The following Test Case failed:\n" f"`matrix`:\n{'\n'.join([str(row) for row in matrix])}\n" f"`start`: {start}\n" f"`home`: {home}\n\n" f"Actual Output: {result}\n" f"Expected Output: {expected_result}" ) assert False, error_message # Test case 2 matrix = [ ['R', 'D', 'L'], ['L', 'U', 'R'], ['U', 'L', 'U'] ] home = (2, 0) start = (2, 2) try: result = solution(matrix, start, home) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`matrix`:\n{'\n'.join([str(row) for row in matrix])}\n" f"`start`: {start}\n" f"`home`: {home}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message expected_result = True if result != expected_result: error_message = ( f"The following Test Case failed:\n" f"`matrix`:\n{'\n'.join([str(row) for row in matrix])}\n" f"`start`: {start}\n" f"`home`: {home}\n\n" f"Actual Output: {result}\n" f"Expected Output: {expected_result}" ) assert False, error_message # Test case 3 matrix = [ ['D', 'R', 'L', 'D'], ['U', 'L', 'U', 'L'], ['D', 'U', 'U', 'R'], ['R', 'D', 'D', 'L'] ] home = (0, 3) start = (1, 3) try: result = solution(matrix, start, home) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`matrix`:\n{'\n'.join([str(row) for row in matrix])}\n" f"`start`: {start}\n" f"`home`: {home}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message expected_result = True if result != expected_result: error_message = ( f"The following Test Case failed:\n" f"`matrix`:\n{'\n'.join([str(row) for row in matrix])}\n" f"`start`: {start}\n" f"`home`: {home}\n\n" f"Actual Output: {result}\n" f"Expected Output: {expected_result}" ) assert False, error_message # Test case 4 matrix = [ ['D', 'R', 'L', 'D'], ['U', 'L', 'U', 'L'], ['D', 'U', 'U', 'R'], ['R', 'D', 'D', 'L'] ] home = (5, 1) start = (2, 2) try: result = solution(matrix, start, home) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`matrix`:\n{'\n'.join([str(row) for row in matrix])}\n" f"`start`: {start}\n" f"`home`: {home}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message expected_result = False if result != expected_result: error_message = ( f"The following Test Case failed:\n" f"`matrix`:\n{'\n'.join([str(row) for row in matrix])}\n" f"`start`: {start}\n" f"`home`: {home}\n\n" f"Actual Output: {result}\n" f"Expected Output: {expected_result}" ) assert False, error_message # Test case 5 matrix = [ ['D', 'R', 'D', 'D'], ['L', 'U', 'R', 'U'] ] home = (2, 0) start = (1, 1) try: result = solution(matrix, start, home) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`matrix`:\n{'\n'.join([str(row) for row in matrix])}\n" f"`start`: {start}\n" f"`home`: {home}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message expected_result = True if result != expected_result: error_message = ( f"The following Test Case failed:\n" f"`matrix`:\n{'\n'.join([str(row) for row in matrix])}\n" f"`start`: {start}\n" f"`home`: {home}\n\n" f"Actual Output: {result}\n" f"Expected Output: {expected_result}" ) assert False, error_message # Test case 6 matrix = [ ['D', 'R', 'D', 'D'], ['L', 'U', 'R', 'U'] ] home = (3, 3) start = (1, 1) try: result = solution(matrix, start, home) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`matrix`:\n{'\n'.join([str(row) for row in matrix])}\n" f"`start`: {start}\n" f"`home`: {home}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message expected_result = False if result != expected_result: error_message = ( f"The following Test Case failed:\n" f"`matrix`:\n{'\n'.join([str(row) for row in matrix])}\n" f"`start`: {start}\n" f"`home`: {home}\n\n" f"Actual Output: {result}\n" f"Expected Output: {expected_result}" ) assert False, error_message # Test case 7 matrix = [ ['D', 'R', 'D', 'U'], ['U', 'U', 'R', 'L'], ['L', 'D', 'R', 'U'] ] home = (2, 0) start = (1, 3) try: result = solution(matrix, start, home) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`matrix`:\n{'\n'.join([str(row) for row in matrix])}\n" f"`start`: {start}\n" f"`home`: {home}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message expected_result = False if result != expected_result: error_message = ( f"The following Test Case failed:\n" f"`matrix`:\n{'\n'.join([str(row) for row in matrix])}\n" f"`start`: {start}\n" f"`home`: {home}\n\n" f"Actual Output: {result}\n" f"Expected Output: {expected_result}" ) assert False, error_message test()
from typing import List, Tuple def solution(matrix: List[List[str]], start: Tuple[int, int], home: Tuple[int, int]) -> bool: """ Determine if it's possible to reach home given the starting point and the house coordinates. Args: matrix (List[List[str]]): A 2D matrix where each element is one of four upper case characters start (Tuple[int, int]): The starting position as (row, col) coordinates (1-indexed) home (Tuple[int, int]): The home position as (row, col) coordinates (1-indexed) Output: Return True if it's possible to reach home, otherwise False """
{ "Common Sense": null, "Data Structures": [ "Path", "Matrix" ], "Dynamic Patterns": null, "Geometric Objects": [ "Grid", "Point", "Arrow", "Coordinate System" ], "Mathematical Operations": null, "Spatial Transformations": null, "Topological Relations": [ "Boundary", "Connectivity", "Intersection" ] }
Iterative Calculation
q4
import matplotlib.pyplot as plt from typing import List, Tuple def solution(dots: List[Tuple[int, int]], top_left: Tuple[int, int], bottom_right: Tuple[int, int]) -> bool: """ Determines whether a rectangle is valid given its corner coordinates and a set of dots. Parameters: dots: A list of coordinate pairs representing points in a grid. top_left: The coordinates of the rectangle's top-left corner. bottom_right: The coordinates of the rectangle's bottom-right corner (note: y-coordinate of top_left > y-coordinate of bottom_right). Returns: True if the rectangle is valid, False otherwise. """ # Extract the rectangle boundaries x1, y1 = top_left x2, y2 = bottom_right # Check for dots inside the rectangle (excluding the edges) for x, y in dots: if x1 < x < x2 and y2 < y < y1: # If any dot is inside the rectangle, it's invalid # visualize(dots, top_left, bottom_right, is_valid=False) return False # If no dots are found inside, the rectangle is valid # visualize(dots, top_left, bottom_right, is_valid=True) return True # def visualize(dots: List[Tuple[int, int]], top_left: Tuple[int, int], bottom_right: Tuple[int, int], is_valid: bool): # """ # Visualize the dots and rectangle. # Parameters: # dots: A list of tuples representing the coordinates of dots in the grid. # top_left: The coordinates of the top-left corner of the rectangle. # bottom_right: The coordinates of the bottom-right corner of the rectangle. # is_valid: Whether the rectangle is valid or not. # """ # # Create a scatter plot of the dots # plt.figure(figsize=(8, 8)) # x_coords, y_coords = zip(*dots) if dots else ([], []) # plt.scatter(x_coords, y_coords, c='blue', label='Dots', s=50, edgecolor='black') # # Draw the rectangle # x1, y1 = top_left # x2, y2 = bottom_right # rect_color = 'green' if is_valid else 'red' # plt.plot([x1, x2, x2, x1, x1], [y1, y1, y2, y2, y1], c=rect_color, label='Rectangle', linewidth=2) # # Add labels and legend # plt.title(f'Rectangle Validity: {"Valid" if is_valid else "Invalid"}', fontsize=16, color=rect_color) # plt.xlabel('X Coordinate') # plt.ylabel('Y Coordinate') # plt.legend() # plt.grid(True) # plt.gca().set_aspect('equal', adjustable='box') # # Show the plot # plt.show()
# Problem Description: - The function solution is tasked with determining if a rectangle defined by its top_left and bottom_right corners is "valid" given a grid of points (dots). A rectangle is considered valid or invalid based on certain properties inferred from the image and the accompanying description. The goal is to implement the function logic to decide the validity of the rectangle. # Visual Facts: 1. Points and Grid: - The grid is marked with integer coordinates on both axes. - Red dots represent points on the grid. 2. Rectangles: - Rectangles are drawn using two different colors: orange and green. - The corners of each rectangle align with the grid lines. 3. Rectangle Labels: - Orange Rectangles: Labeled "Invalid." Contain at least one red point inside them. - Green Rectangles: Labeled "Valid." Contain no red points inside them. 4. Key Points on Labels: - The text "Points Inside" is used to indicate rectangles that have red points inside. - The text "No Points Inside" is used to indicate rectangles without red points. # Visual Patterns: 1. Validity Rule: - A rectangle is valid if and only if there are no red points (dots) inside it. - A rectangle becomes invalid if at least one red point lies strictly within its boundaries (not on the boundary). 2. Boundary Rules: - Points on the boundary of a rectangle do not affect its validity. - Validity is only determined by points strictly inside the rectangle. 3. Grid Alignment: - Rectangles are axis-aligned, meaning their edges are parallel to the x-axis and y-axis. - The coordinates of the top_left and bottom_right corners are sufficient to define a rectangle. 4. Input Constraints: - The list of dots represents red points on the grid. - The top_left corner has a higher y-coordinate than the bottom_right corner, consistent with the standard Cartesian grid.
def test(): test_cases = [ ([(1, 1), (3, 3), (5, 5)], (2, 6), (6, 2), False), ([(1, 1), (2, 3), (4, 6)], (2, 6), (6, 2), True), ([(2, 0), (3, 0), (5, 6)], (1, 6), (6, 1), True), ([(1, 1), (3, 3), (5, 5)], (2, 4), (4, 2), False), ([], (2, 6), (6, 2), True), ([(1, 1), (7, 7), (9, 9)], (2, 9), (3, 6), True), ([(10, 10), (20, 20), (30, 30)], (13, 25), (15, 12), True), ([(10, 10), (20, 20), (15, 15)], (12, 18), (13, 7), True), ([(2, 2), (3, 3)], (1, 5), (5, 1), False), ([(2, 2), (4, 4)], (1, 3), (3, 1), False), ([(0, 0), (9, 9)], (0, 10), (10, 0), False), ] for dots, top_left, bottom_right, expected_output in test_cases: try: output = solution(dots, top_left, bottom_right) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`dots`: {dots}\n" f"`top_left`: {top_left}\n" f"`bottom_right`: {bottom_right}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`dots`: {dots}\n" f"`top_left`: {top_left}\n" f"`bottom_right`: {bottom_right}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List, Tuple def solution(dots: List[Tuple[int, int]], top_left: Tuple[int, int], bottom_right: Tuple[int, int]) -> bool: """ Determines whether a rectangle is valid given its corner coordinates and a set of dots. Parameters: dots: A list of coordinate pairs representing points in a grid. top_left: The coordinates of the rectangle's top-left corner. bottom_right: The coordinates of the rectangle's bottom-right corner (note: y-coordinate of top_left > y-coordinate of bottom_right). Returns: True if the rectangle is valid, False otherwise. """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": null, "Geometric Objects": [ "Rectangle", "Coordinate System", "Point", "Grid" ], "Mathematical Operations": [ "Counting", "Conditional Branching" ], "Spatial Transformations": null, "Topological Relations": [ "Boundary", "Intersection", "Nesting", "Overlap" ] }
Validation
q4-2
import matplotlib.pyplot as plt from typing import List, Tuple import matplotlib.pyplot as plt def solution(dots: List[Tuple[int, int]], top_left: Tuple[int, int], bottom_right: Tuple[int, int]) -> bool: """ Determines whether a rectangle is valid given its corner coordinates and a set of dots. Parameters: dots: A list of coordinate pairs representing points in a grid. top_left: The coordinates of the rectangle's top-left corner. bottom_right: The coordinates of the rectangle's bottom-right corner (note: y-coordinate of top_left > y-coordinate of bottom_right). Returns: True if the rectangle is valid, False otherwise. """ # Extract the rectangle boundaries x1, y1 = top_left x2, y2 = bottom_right count = 0 # Check for dots inside the rectangle for x, y in dots: if x1 <= x <= x2 and y2 <= y <= y1: count += 1 if count != 1: # visualize(dots, top_left, bottom_right, is_valid=False) return False # visualize(dots, top_left, bottom_right, is_valid=True) return True # def visualize(dots: List[Tuple[int, int]], top_left: Tuple[int, int], bottom_right: Tuple[int, int], is_valid: bool): # """ # Visualize the dots and rectangle. # Parameters: # dots: A list of tuples representing the coordinates of dots in the grid. # top_left: The coordinates of the top-left corner of the rectangle. # bottom_right: The coordinates of the bottom-right corner of the rectangle. # is_valid: Whether the rectangle is valid or not. # """ # # Create a scatter plot of the dots # plt.figure(figsize=(8, 8)) # x_coords, y_coords = zip(*dots) if dots else ([], []) # plt.scatter(x_coords, y_coords, c='blue', label='Dots', s=50, edgecolor='black') # # Draw the rectangle # x1, y1 = top_left # x2, y2 = bottom_right # rect_color = 'green' if is_valid else 'red' # plt.plot([x1, x2, x2, x1, x1], [y1, y1, y2, y2, y1], c=rect_color, label='Rectangle', linewidth=2) # # Add labels and legend # plt.title(f'Rectangle Validity: {"Valid" if is_valid else "Invalid"}', fontsize=16, color=rect_color) # plt.xlabel('X Coordinate') # plt.ylabel('Y Coordinate') # plt.legend() # plt.grid(True) # plt.gca().set_aspect('equal', adjustable='box') # # Show the plot # plt.show()
# Problem Description: The task is to determine whether a given rectangle, defined by its top-left and bottom-right corners, is valid based on the presence of red dots within a grid. A rectangle is considered valid if it contains exactly one red dot either inside or on its boundary. The function `solution` takes a list of red dot coordinates and the coordinates of the rectangle's top-left and bottom-right corners as input and returns a boolean indicating the validity of the rectangle. # Visual Facts: 1. The grid is marked with integer coordinates on both axes. 2. Red dots are placed at specific coordinates on the grid. 3. Rectangles are drawn using two different colors: green and orange. 4. Green rectangles are labeled "Valid" and contain exactly one red dot either inside or on the boundary. 5. Orange rectangles are labeled "Invalid" and either contain no red dots or more than one red dot. 6. The rectangles are axis-aligned, meaning their edges are parallel to the x-axis and y-axis. 7. The coordinates of the top-left corner have a higher y-coordinate than the bottom-right corner. # Visual Patterns: 1. Validity Rule: - A rectangle is valid if it contains exactly one red dot either inside or on its boundary. - A rectangle is invalid if it contains no red dots or more than one red dot. 2. Boundary Inclusion: - Red dots on the boundary of the rectangle count towards the validity condition. 3. Grid Alignment: - Rectangles are defined by their top-left and bottom-right corners, which align with the grid lines. 4. Input Constraints: - The list of dots represents the coordinates of red points on the grid. - The top-left corner has a higher y-coordinate than the bottom-right corner, consistent with the standard Cartesian grid.
def test(): test_cases = [ ([(1, 1), (3, 3), (5, 5)], (2, 6), (6, 2), False), ([(1, 1), (2, 3), (4, 6)], (2, 6), (6, 2), False), ([(2, 0), (3, 0), (5, 6)], (1, 6), (6, 1), True), ([(1, 1), (3, 3), (5, 5)], (2, 4), (4, 2), True), ([], (2, 6), (6, 2), False), ([(1, 1), (7, 7), (9, 9)], (2, 9), (3, 6), False), ([(10, 10), (20, 20), (30, 30)], (13, 25), (15, 12), False), ([(10, 10), (20, 20), (15, 15)], (12, 18), (13, 7), False), ([(2, 2), (3, 3)], (1, 5), (5, 1), False), ([(2, 2), (4, 4)], (1, 3), (3, 1), True), ([(0, 0), (9, 9)], (0, 10), (10, 0), False), ] for i, (dots, top_left, bottom_right, expected_output) in enumerate(test_cases): try: output = solution(dots, top_left, bottom_right) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`dots`: {dots}\n" f"`top_left`: {top_left}\n" f"`bottom_right`: {bottom_right}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`dots`: {dots}\n" f"`top_left`: {top_left}\n" f"`bottom_right`: {bottom_right}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List, Tuple def solution(dots: List[Tuple[int, int]], top_left: Tuple[int, int], bottom_right: Tuple[int, int]) -> bool: """ Determines whether a rectangle is valid given its corner coordinates and a set of dots. Parameters: dots: A list of coordinate pairs representing points in a grid. top_left: The coordinates of the rectangle's top-left corner. bottom_right: The coordinates of the rectangle's bottom-right corner (note: y-coordinate of top_left > y-coordinate of bottom_right). Returns: True if the rectangle is valid, False otherwise. """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": null, "Geometric Objects": [ "Rectangle", "Coordinate System", "Point", "Grid" ], "Mathematical Operations": [ "Counting", "Conditional Branching" ], "Spatial Transformations": null, "Topological Relations": [ "Boundary", "Intersection", "Nesting", "Overlap" ] }
Validation
q4-3
import matplotlib.pyplot as plt from typing import List, Tuple import matplotlib.pyplot as plt def solution(dots: List[Tuple[int, int]], top_left: Tuple[int, int], bottom_right: Tuple[int, int]) -> bool: """ Determines whether a rectangle is valid given its corner coordinates and a set of dots. Parameters: dots: A list of coordinate pairs representing points in a grid. top_left: The coordinates of the rectangle's top-left corner. bottom_right: The coordinates of the rectangle's bottom-right corner (note: y-coordinate of top_left > y-coordinate of bottom_right). Returns: True if the rectangle is valid, False otherwise. """ # Extract the rectangle boundaries x1, y1 = top_left x2, y2 = bottom_right # Check for dots inside the rectangle for x, y in dots: if x1 <= x <= x2 and y2 <= y <= y1: # visualize(dots, top_left, bottom_right, is_valid=False) return False # visualize(dots, top_left, bottom_right, is_valid=True) return True # def visualize(dots: List[Tuple[int, int]], top_left: Tuple[int, int], bottom_right: Tuple[int, int], is_valid: bool): # """ # Visualize the dots and rectangle. # Parameters: # dots: A list of tuples representing the coordinates of dots in the grid. # top_left: The coordinates of the top-left corner of the rectangle. # bottom_right: The coordinates of the bottom-right corner of the rectangle. # is_valid: Whether the rectangle is valid or not. # """ # # Create a scatter plot of the dots # plt.figure(figsize=(8, 8)) # x_coords, y_coords = zip(*dots) if dots else ([], []) # plt.scatter(x_coords, y_coords, c='blue', label='Dots', s=50, edgecolor='black') # # Draw the rectangle # x1, y1 = top_left # x2, y2 = bottom_right # rect_color = 'green' if is_valid else 'red' # plt.plot([x1, x2, x2, x1, x1], [y1, y1, y2, y2, y1], c=rect_color, label='Rectangle', linewidth=2) # # Add labels and legend # plt.title(f'Rectangle Validity: {"Valid" if is_valid else "Invalid"}', fontsize=16, color=rect_color) # plt.xlabel('X Coordinate') # plt.ylabel('Y Coordinate') # plt.legend() # plt.grid(True) # plt.gca().set_aspect('equal', adjustable='box') # # Show the plot # plt.show()
# Problem Description: The task is to implement a function `solution` that determines whether a given rectangle is valid based on its corner coordinates and a set of points (dots) on a grid. A rectangle is considered valid if it does not contain any of the given points either inside or on its boundary. # Visual Facts: 1. **Grid and Points**: - The grid is marked with integer coordinates on both axes. - Red dots represent points on the grid. 2. **Rectangles**: - Rectangles are drawn using two different colors: orange and green. - The corners of each rectangle align with the grid lines. 3. **Rectangle Labels**: - Orange Rectangles: Labeled "Invalid." Contain at least one red point inside them. - Green Rectangles: Labeled "Valid." Contain no red points inside them. 4. **Key Points on Labels**: - The text "Containing point" is used to indicate rectangles that have red points inside. - The text "No Point" is used to indicate rectangles without red points. # Visual Patterns: 1. **Validity Rule**: - A rectangle is valid if and only if there are no red points (dots) either inside or on its boundary. - A rectangle becomes invalid if at least one red point lies either inside or on its boundary. 2. **Boundary Rules**: - Red dots on the boundary of the rectangle count towards the validity condition. 3. **Grid Alignment**: - Rectangles are axis-aligned, meaning their edges are parallel to the x-axis and y-axis. - The coordinates of the top_left and bottom_right corners are sufficient to define a rectangle. 4. **Input Constraints**: - The list of dots represents red points on the grid. - The top_left corner has a higher y-coordinate than the bottom_right corner, consistent with the standard Cartesian grid.
def test(): test_cases = [ ([(1, 1), (3, 3), (5, 5)], (2, 6), (6, 2), False), ([(1, 1), (2, 3), (4, 6)], (2, 6), (6, 2), False), ([(2, 0), (3, 0), (5, 6)], (1, 6), (6, 1), False), ([(1, 1), (3, 3), (5, 5)], (2, 4), (4, 2), False), ([], (2, 6), (6, 2), True), ([(1, 1), (7, 7), (9, 9)], (2, 9), (3, 6), True), ([(10, 10), (20, 20), (30, 30)], (13, 25), (15, 12), True), ([(10, 10), (20, 20), (15, 15)], (12, 18), (13, 7), True), ([(2, 2), (3, 3)], (1, 5), (5, 1), False), ([(2, 2), (4, 4)], (1, 3), (3, 1), False), ([(0, 0), (9, 9)], (0, 10), (10, 0), False), ] for dots, top_left, bottom_right, expected_output in test_cases: try: output = solution(dots, top_left, bottom_right) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`dots`: {dots}\n" f"`top_left`: {top_left}\n" f"`bottom_right`: {bottom_right}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`dots`: {dots}\n" f"`top_left`: {top_left}\n" f"`bottom_right`: {bottom_right}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List, Tuple def solution(dots: List[Tuple[int, int]], top_left: Tuple[int, int], bottom_right: Tuple[int, int]) -> bool: """ Determines whether a rectangle is valid given its corner coordinates and a set of dots. Parameters: dots: A list of coordinate pairs representing points in a grid. top_left: The coordinates of the rectangle's top-left corner. bottom_right: The coordinates of the rectangle's bottom-right corner (note: y-coordinate of top_left > y-coordinate of bottom_right). Returns: True if the rectangle is valid, False otherwise. """
{ "Common Sense": null, "Data Structures": null, "Dynamic Patterns": null, "Geometric Objects": [ "Rectangle", "Coordinate System", "Point", "Grid" ], "Mathematical Operations": [ "Counting", "Conditional Branching" ], "Spatial Transformations": null, "Topological Relations": [ "Boundary", "Intersection", "Nesting", "Overlap" ] }
Validation
q40
import math def solution(h: int, m: int, a: int, b: int, k: int) -> float: """ Given an initial time (in 12-hour format) and the lengths of the orange and green arrows, calculate the length of the red dashed line after k minutes Parameters: h (int): Hour. m (int): Minute. a (int): Length of the orange arrow. b (int): Length of the green arrow. k (int): Duration passed (in minutes). Returns: float: Length of the red dashed line (rounded to two decimal places). """ # Calculate the new time total_minutes = h * 60 + m + k new_m = total_minutes % 60 # Calculate the angles minute_angle = new_m * 6 # 6 degrees per minute hour_angle = (h % 12) * 30 + m * 0.5 # 30 degrees per hour + 0.5 degrees per minute # Convert angles to radians minute_angle_rad = math.radians(minute_angle) hour_angle_rad = math.radians(hour_angle) # Convert to Cartesian coordinates minute_x = b * math.cos(minute_angle_rad) minute_y = b * math.sin(minute_angle_rad) hour_x = a * math.cos(hour_angle_rad) hour_y = a * math.sin(hour_angle_rad) # Calculate the distance between the two points distance = math.sqrt((minute_x - hour_x) ** 2 + (minute_y - hour_y) ** 2) return round(distance, 2)
# Problem Description This is a geometric problem involving clock hand movements and distance calculations. We need to: 1. Start with an initial time (h:m) and two arrows of lengths a and b 2. After k minutes, calculate the length of a line that connects: - The initial position of the hour hand - The final position of the minute hand 3. Return this length rounded to 2 decimal places # Visual Facts 1. Two example scenarios are shown: - Scenario 1: 3:00 → 3:40 (40 min progression) - Scenario 2: 4:20 → 5:30 (70 min progression) 2. Each clock shows: - Orange arrow (hour hand) - Green arrow (minute hand) - Red dashed line (the target distance we need to calculate) 3. Clock face components: - 12 major marks (hours) - 360 degrees total - Center point where hands meet # Visual Patterns 1. Hand Movement Patterns: - Hour hand makes a complete 360° rotation in 12 hours (30° per hour) - Minute hand makes a complete 360° rotation in 60 minutes (6° per minute) - Hour hand moves proportionally between hours (0.5° per minute) 2. Geometric Relationships: - Red dashed line forms a triangle with: * Initial hour hand position (fixed) * Final minute hand position (after k minutes) * Center point of the clock 3. Calculation Pattern: - We need to use trigonometry to find the length of the red line - The angle between initial and final positions can be calculated using: * Initial hour position (h * 30 + m * 0.5 degrees) * Final minute position ((m + k) * 6 degrees) 4. Triangle Solution Pattern: - The red line length can be found using the law of cosines: ``` red_length = √(a² + b² - 2ab * cos(θ)) ``` where θ is the angle between the initial hour position and final minute position
def test(): test_cases = [ (3, 0, 3, 4, 40, 6.77), (3, 0, 4, 3, 180, 5.0), (3, 0, 2, 7, 40, 8.79), (4, 20, 6, 8, 70, 6.19), (6, 0, 6, 8, 150, 2), (8, 22, 5, 9, 137, 4.46), (7, 12, 4, 6, 29, 3.23), (1, 56, 2, 7, 173, 8.29), (1, 56, 3, 4, 104, 7.0), (0, 56, 3, 4, 84, 5.08), ] for h, m, a, b, k, expected_output in test_cases: try: output = solution(h, m, a, b, k) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`h`: {h}\n" f"`m`: {m}\n" f"`a`: {a}\n" f"`b`: {b}\n" f"`k`: {k}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`h`: {h}\n" f"`m`: {m}\n" f"`a`: {a}\n" f"`b`: {b}\n" f"`k`: {k}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(h: int, m: int, a: int, b: int, k: int) -> float: """ Given an initial time (in 12-hour format) and the lengths of the orange and green arrows, calculate the length of the red dashed line after k minutes Parameters: h (int): Hour. m (int): Minute. a (int): Length of the orange arrow. b (int): Length of the green arrow. k (int): Duration passed (in minutes). Returns: float: Length of the red dashed line (rounded to two decimal places). """
{ "Common Sense": [ "Clock" ], "Data Structures": null, "Dynamic Patterns": [ "Cyclic Motion", "Circular Motion" ], "Geometric Objects": [ "Line Segment", "Angle", "Triangle", "Circle", "Point", "Arrow" ], "Mathematical Operations": null, "Spatial Transformations": [ "Rotation" ], "Topological Relations": [ "Connection" ] }
Direct Calculation
q40-2
import math def solution(h: int, m: int, a: int, b: int, k: int) -> float: """ Given an initial time (in 12-hour format) and the lengths of the orange and green arrows, calculate the area of the blue region after k minutes Parameters: h (int): Hour. m (int): Minute. a (int): Length of the orange arrow. b (int): Length of the green arrow. k (int): Duration passed (in minutes). Returns: float: Area of the blue region (rounded to two decimal places). """ # Calculate the new time for the minute hand total_minutes = h * 60 + m + k new_m = total_minutes % 60 # Calculate the angles minute_angle = new_m * 6 # 6 degrees per minute hour_angle = (h % 12) * 30 + m * 0.5 # 30 degrees per hour + 0.5 degrees per minute # Convert angles to radians minute_angle_rad = math.radians(minute_angle) hour_angle_rad = math.radians(hour_angle) # Convert to Cartesian coordinates minute_x = b * math.cos(minute_angle_rad) minute_y = b * math.sin(minute_angle_rad) hour_x = a * math.cos(hour_angle_rad) hour_y = a * math.sin(hour_angle_rad) # Calculate the area of the triangle using the cross product formula area = 0.5 * abs(hour_x * minute_y - hour_y * minute_x) return round(area, 2)
# Problem Description The problem involves calculating the area of a triangle formed by the positions of the hour and minute hands on a clock after a given time has elapsed. The initial positions of the hour and minute hands are given, along with the lengths of the arrows representing these hands. We need to determine the area of the triangle formed by the initial position of the hour hand, the final position of the minute hand, and the center of the clock after a specified duration in minutes. # Visual Facts 1. The image shows two pairs of clocks, each pair representing an initial time and a time after a certain duration has passed. 2. Each clock has: - An orange arrow representing the hour hand. - A green arrow representing the minute hand. - A blue triangle formed by the initial position of the hour hand, the final position of the minute hand, and the center of the clock. 3. The first pair of clocks: - Initial time: 3:00 - Time after 40 minutes: 3:40 4. The second pair of clocks: - Initial time: 4:20 - Time after 70 minutes: 5:30 # Visual Patterns 1. **Hand Movement Patterns**: - The hour hand moves 30 degrees per hour (360 degrees in 12 hours). - The minute hand moves 6 degrees per minute (360 degrees in 60 minutes). - The hour hand also moves 0.5 degrees per minute (since it moves 30 degrees in 60 minutes). 2. **Geometric Relationships**: - The blue triangle is formed by the initial position of the hour hand, the final position of the minute hand, and the center of the clock. - The angle between the initial and final positions of the hands can be calculated using the degrees moved by each hand. 3. **Calculation Pattern**: - To find the area of the triangle, we need to calculate the angle between the initial and final positions of the hands. - The area of the triangle can be calculated using the formula for the area of a triangle given two sides and the included angle: Area = 1/2 * a * b * sin(θ) where a and b are the lengths of the hour and minute hands, and θ is the angle between them. 4. **Angle Calculation**: - Initial hour hand position: θ_h = h * 30 + m * 0.5 degrees - Final minute hand position: θ_m = (m + k) * 6 degrees - The angle between the initial hour hand position and the final minute hand position is: θ = |θ_m - θ_h|
def test(): test_cases = [ (3, 0, 3, 4, 30, 6.0), (3, 0, 4, 3, 180, 6.0), (3, 0, 2, 7, 40, 3.5), (4, 20, 6, 8, 70, 18.39), (6, 0, 6, 8, 150, 0), (8, 22, 5, 9, 137, 6.58), (7, 12, 4, 6, 29, 6.0), (1, 56, 2, 7, 173, 5.8), (1, 56, 3, 4, 104, 0.21), (0, 56, 3, 4, 84, 6.0), ] for h, m, a, b, k, expected_output in test_cases: try: output = solution(h, m, a, b, k) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`h`: {h}\n" f"`m`: {m}\n" f"`a`: {a}\n" f"`b`: {b}\n" f"`k`: {k}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`h`: {h}\n" f"`m`: {m}\n" f"`a`: {a}\n" f"`b`: {b}\n" f"`k`: {k}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(h: int, m: int, a: int, b: int, k: int) -> float: """ Given an initial time (in 12-hour format) and the lengths of the orange and green arrows, calculate the area of the blue region after k minutes Parameters: h (int): Hour. m (int): Minute. a (int): Length of the orange arrow. b (int): Length of the green arrow. k (int): Duration passed (in minutes). Returns: float: Area of the blue region (rounded to two decimal places). """
{ "Common Sense": [ "Clock" ], "Data Structures": null, "Dynamic Patterns": [ "Cyclic Motion", "Circular Motion" ], "Geometric Objects": [ "Line Segment", "Angle", "Triangle", "Circle", "Point", "Arrow" ], "Mathematical Operations": null, "Spatial Transformations": [ "Rotation" ], "Topological Relations": [ "Connection" ] }
Direct Calculation
q40-3
import math def solution(h: int, m: int, a: int, b: int, k: int) -> float: """ Given an initial time (in 12-hour format) and the lengths of the orange and green arrows, calculate the distance between the initial minute hand and the hour hand after k minutes. Parameters: h (int): Hour. m (int): Minute. a (int): Length of the orange arrow (hour hand). b (int): Length of the green arrow (minute hand). k (int): Duration passed (in minutes). Returns: float: Distance between the initial minute hand and the hour hand after k minutes (rounded to two decimal places). """ # Calculate the new time for the hour hand total_minutes = h * 60 + m + k new_h = (total_minutes // 60) % 12 new_m = total_minutes % 60 # Calculate the angles initial_minute_angle = m * 6 # 6 degrees per minute for the initial minute hand hour_angle = (new_h % 12) * 30 + new_m * 0.5 # 30 degrees per hour + 0.5 degrees per minute # Convert angles to radians minute_angle_rad = math.radians(initial_minute_angle) hour_angle_rad = math.radians(hour_angle) # Convert to Cartesian coordinates # Initial minute hand minute_x = b * math.cos(minute_angle_rad) minute_y = b * math.sin(minute_angle_rad) # New hour hand after k minutes hour_x = a * math.cos(hour_angle_rad) hour_y = a * math.sin(hour_angle_rad) # Calculate the distance between the two points distance = math.sqrt((minute_x - hour_x) ** 2 + (minute_y - hour_y) ** 2) return round(distance, 2)
# Problem Description The problem involves calculating the length of a line segment (red dashed line) on an analog clock after a certain duration has passed. The initial time is given along with the lengths of the hour and minute hands. The goal is to determine the length of the red dashed line, which connects the initial position of the minute hand to the new position of the hour hand after a specified number of minutes. # Visual Facts 1. **Initial Time and Hand Positions**: - The initial time is given in hours (h) and minutes (m). - The orange arrow represents the hour hand. - The green arrow represents the minute hand. 2. **Time Progression**: - The time progresses by a specified number of minutes (k). 3. **Hand Movements**: - The minute hand moves 6 degrees per minute. - The hour hand moves 0.5 degrees per minute. 4. **Red Dashed Line**: - The red dashed line connects the initial position of the minute hand to the new position of the hour hand after k minutes. # Visual Patterns 1. **Angle Calculation**: - The initial position of the hour hand can be calculated as θ_{h_{initial}} = h*30 + m*0.5 degrees. - The initial position of the minute hand can be calculated as θ_{m_{initial}} = m*6 degrees. - The new position of the hour hand after k minutes can be calculated as θ_{h_{final}} = θ_{h_{initial}} + k*0.5 degrees. - The new position of the minute hand after k minutes can be calculated as θ_{m_{final}} = (m + k)*6 degrees. 2. **Angle Between Initial and Final Positions**: - The angle between the initial position of the minute hand and the final position of the hour hand is θ = |θ_{m_{initial}} - θ_{h_{final}}|. 3. **Law of Cosines**: - To find the length of the red dashed line, we use the law of cosines: red_length = \sqrt{a^2 + b^2 - 2ab cos(θ)} where a is the length of the minute hand, b is the length of the hour hand, and θ is the angle between the initial position of the minute hand and the final position of the hour hand.
def test(): test_cases = [ (2, 0, 3, 4, 60, 5.0), (3, 0, 4, 3, 180, 7.0), (3, 0, 2, 7, 40, 7.91), (4, 20, 6, 8, 70, 5.67), (6, 0, 6, 8, 150, 11.17), (8, 22, 5, 9, 137, 13.97), (7, 12, 4, 6, 29, 9.83), (1, 56, 2, 7, 173, 8.97), (1, 56, 3, 4, 104, 6.46), (0, 56, 3, 4, 84, 5.16), ] for h, m, a, b, k, expected_output in test_cases: try: output = solution(h, m, a, b, k) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`h`: {h}\n" f"`m`: {m}\n" f"`a`: {a}\n" f"`b`: {b}\n" f"`k`: {k}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`h`: {h}\n" f"`m`: {m}\n" f"`a`: {a}\n" f"`b`: {b}\n" f"`k`: {k}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
def solution(h: int, m: int, a: int, b: int, k: int) -> float: """ Given an initial time (in 12-hour format) and the lengths of the orange and green arrows, calculate the length of the red dashed line after k minutes Parameters: h (int): Hour. m (int): Minute. a (int): Length of the orange arrow. b (int): Length of the green arrow. k (int): Duration passed (in minutes). Returns: float: Length of the red dashed line (rounded to two decimal places). """
{ "Common Sense": [ "Clock" ], "Data Structures": null, "Dynamic Patterns": [ "Cyclic Motion", "Circular Motion" ], "Geometric Objects": [ "Line Segment", "Angle", "Triangle", "Circle", "Point", "Arrow" ], "Mathematical Operations": null, "Spatial Transformations": [ "Rotation" ], "Topological Relations": [ "Connection" ] }
Direct Calculation
q41
from typing import List def solution(n: int) -> List[int]: """ Returns the numbers in the specified row. Parameters: n (int): The row number to retrieve. (n > 1) Returns: List[int]: A list containing all numbers in the nth row. """ ret = list() for i in range(n): row = list() for j in range(0, i + 1): if j == 0 or j == i: row.append(2) else: row.append(ret[i - 1][j] * ret[i - 1][j - 1]) ret.append(row) return ret[n - 1]
# Problem Description This is a hexagonal pyramid number pattern problem where we need to generate the nth row of numbers following specific rules. Each row contains numbers arranged in hexagonal cells, with the first row having one cell, and each subsequent row adding one more cell than the previous row. The function should return all numbers in the requested row as a list. # Visual Facts 1. The structure is a triangular arrangement of hexagonal cells 2. Each row n contains n cells 3. Row 1: [2] 4. Row 2: [2, 2] 5. Row 3: [2, 4, 2] 6. Row 4: [2, 8, 8, 2] 7. Row 5: [2, 16, 64, 16, 2] 8. All rows start and end with 2 9. The arrow marks in the image indicate multiplication relationships between cells # Visual Patterns 1. Pattern for number of elements: - Row n contains n elements 2. Edge elements pattern: - First and last elements of every row are always 2 3. Middle elements calculation pattern: - For row ≥ 3, each non-edge cell is calculated by multiplying the two cells above it - Example: In row 4, 8 = 2 × 4 (from row 3) - Example: In row 5, 64 = 8 × 8 (from row 4) 4. Symmetry pattern: - Each row is symmetrical from left to right - Example: Row 4: [2, 8, 8, 2] - Example: Row 5: [2, 16, 64, 16, 2]
def test(): test_cases = [ (1, [2]), (2, [2, 2]), (3, [2, 4, 2]), (4, [2, 8, 8, 2]), (5, [2, 16, 64, 16, 2]), (6, [2, 32, 1024, 1024, 32, 2]), (7, [2, 64, 32768, 1048576, 32768, 64, 2]), (8, [2, 128, 2097152, 34359738368, 34359738368, 2097152, 128, 2]), (9, [2, 256, 268435456, 72057594037927936, 1180591620717411303424, 72057594037927936, 268435456, 256, 2]), (10, [2, 512, 68719476736, 19342813113834066795298816, 85070591730234615865843651857942052864, 85070591730234615865843651857942052864, 19342813113834066795298816, 68719476736, 512, 2]), ] for n, expected_output in test_cases: try: output = solution(n) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`n`: {n}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`n`: {n}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(n: int) -> List[int]: """ Returns the numbers in the specified row. Parameters: n (int): The row number to retrieve. (n > 1) Returns: List[int]: A list containing all numbers in the nth row. """
{ "Common Sense": null, "Data Structures": [ "Sequence" ], "Dynamic Patterns": [ "Linear Increment", "Layered Structure", "Exponential Increment", "Mirror Symmetry", "Propagation" ], "Geometric Objects": [ "Triangle", "Hexagon" ], "Mathematical Operations": [ "Basic Arithmetic" ], "Spatial Transformations": null, "Topological Relations": [ "Adjacency", "Connection" ] }
Expansion
q41-2
from typing import List def solution(n: int) -> List[int]: """ Returns the numbers in the specified row. Parameters: n (int): The row number to retrieve. (n > 1) Returns: List[int]: A list containing all numbers in the nth row. """ ret = list() for i in range(n): row = list() for j in range(0, i + 1): if j == 0 or j == i: row.append(i + 1) else: row.append(ret[i - 1][j] * ret[i - 1][j - 1]) ret.append(row) return ret[n - 1]
# Problem Description This is a hexagonal pyramid number pattern problem where we need to generate the nth row of numbers following specific rules. Each row contains numbers arranged in hexagonal cells, with the first row having one cell, and each subsequent row adding one more cell than the previous row. The function should return all numbers in the requested row as a list. # Visual Facts 1. The structure is a triangular arrangement of hexagonal cells 2. Each row n contains n cells 3. Row 1: [1] 4. Row 2: [2, 2] 5. Row 3: [3, 4, 3] 6. Row 4: [4, 12, 12, 4] 7. Row 5: [5, 48, 144, 48, 5] 8. All rows start and end with corresponding row number 9. The arrow marks in the image indicate multiplication relationships between cells # Visual Patterns 1. Pattern for number of elements: - Row n contains n elements 2. Edge elements pattern: - First and last elements of every row are corresponding row number 3. Middle elements calculation pattern: - For row ≥ 3, each non-edge cell is calculated by multiplying the two cells above it - Example: In row 4, 12 = 3 × 4 (from row 3) - Example: In row 5, 48 = 4 × 12 (from row 4) 4. Symmetry pattern: - Each row is symmetrical from left to right - Example: Row 4: [4, 12, 12, 4] - Example: Row 5: [5, 48, 144, 48, 5]
def test(): test_cases = [ (1, [1]), (2, [2, 2]), (3, [3, 4, 3]), (4, [4, 12, 12, 4]), (5, [5, 48, 144, 48, 5]), (6, [6, 240, 6912, 6912, 240, 6]), (7, [7, 1440, 1658880, 47775744, 1658880, 1440, 7]), (8, [8, 10080, 2388787200, 79254226206720, 79254226206720, 2388787200, 10080, 8]), (9, [9, 80640, 24078974976000, 189321481108517289984000, 6281232371625943240173158400, 189321481108517289984000, 24078974976000, 80640, 9]), (10, [10, 725760, 1941728542064640000, 4558667206031244565988071440384000000, 1189172215782988266980141580906985588465965465600000, 1189172215782988266980141580906985588465965465600000, 4558667206031244565988071440384000000, 1941728542064640000, 725760, 10]), ] for n, expected_output in test_cases: try: output = solution(n) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`n`: {n}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`n`: {n}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(n: int) -> List[int]: """ Returns the numbers in the specified row. Parameters: n (int): The row number to retrieve. (n > 1) Returns: List[int]: A list containing all numbers in the nth row. """
{ "Common Sense": null, "Data Structures": [ "Sequence" ], "Dynamic Patterns": [ "Linear Increment", "Layered Structure", "Exponential Increment", "Mirror Symmetry", "Propagation" ], "Geometric Objects": [ "Triangle", "Hexagon" ], "Mathematical Operations": [ "Basic Arithmetic" ], "Spatial Transformations": null, "Topological Relations": [ "Adjacency", "Connection" ] }
Expansion
q41-3
from typing import List def solution(n: int) -> List[int]: """ Returns the numbers in the specified row. Parameters: n (int): The row number to retrieve. (n > 1) Returns: List[int]: A list containing all numbers in the nth row. """ ret = list() for i in range(n): row = list() for j in range(0, i + 1): if j == 0 or j == i: row.append(2) else: row.append(ret[i - 1][j] + ret[i - 1][j - 1]) ret.append(row) return ret[n - 1]
# Problem Description This is a hexagonal pyramid number pattern problem where we need to generate the nth row of numbers following specific rules. Each row contains numbers arranged in hexagonal cells, with the first row having one cell, and each subsequent row adding one more cell than the previous row. The function should return all numbers in the requested row as a list. # Visual Facts 1. The structure is a triangular arrangement of hexagonal cells 2. Each row n contains n cells 3. Row 1: [2] 4. Row 2: [2, 2] 5. Row 3: [2, 4, 2] 6. Row 4: [2, 6, 6, 2] 7. Row 5: [2, 8, 12, 8, 2] 8. All rows start and end with 2 9. The arrow marks in the image indicate addition relationships between cells # Visual Patterns 1. Pattern for number of elements: - Row n contains n elements 2. Edge elements pattern: - First and last elements of every row are always 2 3. Middle elements calculation pattern: - For row ≥ 3, each non-edge cell is calculated by adding the two cells above it - Example: In row 4, 6 = 2 + 4 (from row 3) - Example: In row 5, 12 = 6 + 6 (from row 4) 4. Symmetry pattern: - Each row is symmetrical from left to right - Example: Row 4: [2, 6, 6, 2] - Example: Row 5: [2, 8, 12, 8, 2]
def test(): test_cases = [ (1, [2]), (2, [2, 2]), (3, [2, 4, 2]), (4, [2, 6, 6, 2]), (5, [2, 8, 12, 8, 2]), (6, [2, 10, 20, 20, 10, 2]), (7, [2, 12, 30, 40, 30, 12, 2]), (8, [2, 14, 42, 70, 70, 42, 14, 2]), (9, [2, 16, 56, 112, 140, 112, 56, 16, 2]), (10, [2, 18, 72, 168, 252, 252, 168, 72, 18, 2]), ] for n, expected_output in test_cases: try: output = solution(n) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`n`: {n}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`n`: {n}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(n: int) -> List[int]: """ Returns the numbers in the specified row. Parameters: n (int): The row number to retrieve. (n > 1) Returns: List[int]: A list containing all numbers in the nth row. """
{ "Common Sense": null, "Data Structures": [ "Sequence" ], "Dynamic Patterns": [ "Linear Increment", "Layered Structure", "Exponential Increment", "Mirror Symmetry", "Propagation" ], "Geometric Objects": [ "Triangle", "Hexagon" ], "Mathematical Operations": [ "Basic Arithmetic" ], "Spatial Transformations": null, "Topological Relations": [ "Adjacency", "Connection" ] }
Expansion
q42
from typing import List def solution(matrix: List[List[int]]) -> int: """ Calculate the sum of the elements in the matrix. Parameters: matrix (List[List[int]]): A 3x3 integer matrix. Returns: int: The sum of the elements in the matrix. """ return matrix[0][2] + matrix[1][1] + matrix[2][0]
# Problem Description This appears to be a problem about calculating a specific sum in a 3x3 matrix, but the complete requirements aren't clear from the function signature alone. The image suggests we need to calculate the sum of elements along a diagonal path marked by arrows in each matrix case. # Visual Facts 1. Each case shows a 3x3 matrix with integers 2. Each matrix has a diagonal arrow line crossing through it 3. Three example cases are provided with their sums: - Case 1: Sum = 15 - Case 2: Sum = 13 - Case 3: Sum = 7 4. The diagonal arrows are oriented from top-right to bottom-left 5. The diagonal line passes through exactly 3 cells in each matrix # Visual Patterns 1. The sum in each case corresponds to the numbers along the diagonal path: - Case 1: 3 + 5 + 7 = 15 - Case 2: 5 + 0 + 8 = 13 - Case 3: 3 + 1 + 3 = 7 2. The diagonal always follows the pattern: - Starts at top-right element (position [0][2]) - Goes through middle element (position [1][1]) - Ends at bottom-left element (position [2][0]) 3. This is specifically the secondary diagonal (or counter-diagonal) pattern, but only these three positions are included in the sum
def test(): test_cases = [ ([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 15), ([[4, 4, 2], [1, 8, 6], [5, 3, 5]], 15), ([[4, 4, 1], [1, 3, 3], [2, 3, 5]], 6), ([[1, 0, 0], [2, 8, 6], [5, 4, 2]], 13), ([[3, 4, 5], [6, 1, 3], [2, 2, 1]], 8), ([[7, 1, 1], [2, 4, 6], [1, 3, 5]], 6), ([[1, 4, 0], [1, 0, 6], [0, 3, 3]], 0), ([[1, 3, 2], [3, 2, 6], [2, 2, 1]], 6), ([[1, 1, 1], [1, 1, 1], [2, 3, 4]], 4), ([[2, 1, 0], [-1, -8, -6], [-5, -3, -5]], -13), ] for matrix, expected_output in test_cases: try: output = solution(matrix) except Exception as e: error_message = ( f"An exception occurred while running the test case:\n" f"`matrix`: {matrix}\n\n" f"Exception: '{str(e)}'" ) assert False, error_message if output != expected_output: error_message = ( f"The following Test Case failed:\n" f"`matrix`: {matrix}\n\n" f"Actual Output: {output}\n" f"Expected Output: {expected_output}" ) assert False, error_message test()
from typing import List def solution(matrix: List[List[int]]) -> int: """ Calculate the sum of the elements in the matrix. Parameters: matrix (List[List[int]]): A 3x3 integer matrix. Returns: int: The sum of the elements in the matrix. """
{ "Common Sense": null, "Data Structures": [ "Matrix" ], "Dynamic Patterns": [ "Cross Pattern" ], "Geometric Objects": [ "Line", "Diagonal", "Arrow", "Grid" ], "Mathematical Operations": [ "Aggregation", "Basic Arithmetic" ], "Spatial Transformations": null, "Topological Relations": null }
Aggregation