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 |
HumanEval-V: Benchmarking High-Level Visual Reasoning with Complex Diagrams in Coding Tasks
📄 Paper • 🏠 Home Page • 💻 GitHub Repository • 🏆 Leaderboard • 🤗 Dataset Viewer
HumanEval-V is a novel benchmark designed to evaluate the diagram understanding and reasoning capabilities of Large Multimodal Models (LMMs) in programming contexts. Unlike existing benchmarks, HumanEval-V focuses on coding tasks that require sophisticated visual reasoning over complex diagrams, pushing the boundaries of LMMs' ability to comprehend and process visual information. The dataset includes 253 human-annotated Python coding tasks, each featuring a critical, self-explanatory diagram with minimal textual clues. These tasks require LMMs to generate Python code based on the visual context and predefined function signatures.

Key features:
- Complex diagram understanding that is indispensable for solving coding tasks.
- Real-world problem contexts with diverse diagram types and spatial reasoning challenges.
- Code generation tasks, moving beyond multiple-choice or short-answer questions to evaluate deeper visual and logical reasoning capabilities.
- Two-stage evaluation pipeline that separates diagram description generation and code implementation for more accurate visual reasoning assessment.
- Handcrafted test cases for rigorous execution-based evaluation through the pass@k metric.

Dataset Structure
Each task in the dataset consists of the following fields:
- qid: A unique identifier for each coding task (e.g., q1, with mutated versions like q1-2, q1-3).
- diagram: A single diagram that provides the essential visual context required to solve the task.
- function_signature: Includes necessary imports and the function signature that the LMMs must complete.
- test_script: The test cases used to validate the correctness of the generated code.
- ground_truth_solution: The human-annotated code solutions for the task.
- ground_truth_diagram_description: Human-annotated descriptions of the diagram.
- task_type: The type of the task, which falls into one of six categories, as shown in Figure 2.
- capability_aspects: The capabilities required to understand the diagram in the task, which include seven dimensions and their sub-aspects, as shown in Figure 3.
Usage
You can easily load the dataset using the Hugging Face datasets
library.
from datasets import load_dataset
humaneval_v = load_dataset("HumanEval-V/HumanEval-V-Benchmark", split="test")
Citation
@article{zhang2024humanevalv,
title={HumanEval-V: Benchmarking High-Level Visual Reasoning with Complex Diagrams in Coding Tasks},
author={Zhang, Fengji and Wu, Linquan and Bai, Huiyu and Lin, Guancheng and Li, Xiao and Yu, Xiao and Wang, Yue and Chen, Bei and Keung, Jacky},
journal={arXiv preprint arXiv:2410.12381},
year={2024},
}
- Downloads last month
- 0