G-Code Toolpath Optimization: Collision Avoidance with Bounding Box
Algorithm description:
This algorithm implements a collision detection mechanism for CNC toolpaths. It checks if a linear move (defined by two points) intersects with a rectangular obstacle (defined by a bounding box). This is a fundamental component of advanced CAM software and machine controllers to prevent damage to the workpiece, tool, or machine.
Algorithm explanation:
The `checkCollision` function determines if a tool's movement from `p1` to `p2` will intersect with an `obstacle` bounding box. It first uses `isPointInsideBox` to check if either the start or end point of the toolpath lies within the obstacle. If not, it calls `lineSegmentIntersectsBox` to perform a more rigorous check. `lineSegmentIntersectsBox` implements the Liang-Barsky line clipping algorithm, which is efficient for clipping a line segment against a rectangular window. It calculates parameters `t` representing the intersection points along the line segment relative to its endpoints. If the calculated `t` values indicate an intersection within the segment's bounds (0 to 1), it returns `true`. The time complexity is O(1) because the number of operations is constant, regardless of the input points or box dimensions. The space complexity is also O(1). Edge cases handled include endpoints inside the box, lines parallel to box edges (both inside and outside), and correctly ordered box coordinates. The algorithm's correctness relies on the established geometric principles of line-rectangle intersection.
Pseudocode:
FUNCTION checkCollision(p1, p2, obstacle):
IF isPointInsideBox(p1, obstacle) OR isPointInsideBox(p2, obstacle):
RETURN true
RETURN lineSegmentIntersectsBox(p1, p2, obstacle)
FUNCTION lineSegmentIntersectsBox(p1, p2, box):
// Ensure box min/max are ordered correctly
minX = min(box.Min.X, box.Max.X)
maxX = max(box.Min.X, box.Max.X)
minY = min(box.Min.Y, box.Max.Y)
maxY = max(box.Min.Y, box.Max.Y)
dx = p2.X - p1.X
dy = p2.Y - p1.Y
t_enter = 0.0
t_exit = 1.0
// Check against 4 clipping planes (left, right, bottom, top)
FOR k FROM 0 TO 3:
IF p[k] == 0.0: // Parallel to edge
IF q[k] < 0.0: RETURN false // Outside and parallel
ELSE:
r = q[k] / p[k]
IF p[k] < 0.0: // Entering edge
IF r > t_exit: RETURN false
IF r > t_enter: t_enter = r
ELSE: // Exiting edge
IF r < t_enter: RETURN false
IF r < t_exit: t_exit = r
RETURN t_enter <= t_exit
Exercise library
Library
Playable exercises
Choose Exercise
Filter, sort, and preview algorithm before you choose one to play.
Total1275published items
Pages160pages available
Browse published coding scenarios with filters, sorting, and pagination.
Loading scenarios…
⚠
Something went wrong. Please retry.
🗂
No scenarios to show yet. Adjust the filters or refresh.
Canonical Algorithm Text
Published
Visual Basic .NETGeneral (vbnet)
Find Peak Element in Array
Difficulty
writing:2
length:5
Popularity
0
Created
2026-01-28 15:01 UTC
Published
2026-01-28 15:16 UTC
Author
Damian
#binary search#peak finding#array#algorithms#logarithmic time#divide and conquer
goal: Find any peak element in an array.input: An array of integers `nums`.output: The index of a peak element.
Canonical Algorithm Text
Public Module PeakFinder ' Main function to find a peak element in an array. ' A peak element is an element that is strictly greater than its neighbors. ' If the array has multiple peaks, returning the index to any of the peaks is fine. Public Function FindPeakElement(ByVal nums(...
Description Algorithm
This algorithm finds a peak element in an array where a peak is defined as an element strictly greater than its neighbors. It uses a binary search approach to efficiently locate such an element. This is useful in scenari...
Explanation
The `FindPeakElement` function implements a modified binary search to locate a peak element in an array. A peak element is guaranteed to exist because we can imagine that `nums[-1] = nums[n] = -infinity`. The algorithm iteratively narrows down the search space. If `nums[mid] < nums[mid + 1]`, it implies that a peak must exist to the right of `mid` (inclusive of `mid + 1`), so `left` is updated to `mid + 1`. Otherwise, if `nums[mid] >= nums[mid + 1]`, a peak must exist at `mid` or to its left, so `right` is updated to `mid`. The loop invariant is that a peak element is always present within the `[left, right]` range. The time complexity is O(log n) due to the binary search, and the space complexity is O(1) as it uses a constant amount of extra space. Edge cases like empty or single-element arrays are handled implicitly by the binary search logic and explicitly by an initial check.
Pseudocode
Function FindPeakElement(array): If array is empty, throw error. Set left = 0, right = length of array - 1. While left < right: Calculate mid = left + (right - left) / 2. If array[mid] < array[mid + 1]: Set left = mid +...
Published
Visual Basic .NETGeneral (vbnet)
In-place Array Reversal
Difficulty
writing:4
length:7
Popularity
0
Created
2026-01-28 15:01 UTC
Published
2026-01-28 15:16 UTC
Author
Damian
#array reversal#in-place#pointers#swapping#algorithms#linear time
goal: Reverse the elements of an array in-place.input: An array of integers `arr`.output: The input array `arr` with its elements reversed.
Canonical Algorithm Text
Public Module ArrayReversal ' Reverses an array in-place. ' This means the original array is modified directly without creating a new one. Public Sub ReverseArrayInPlace(ByVal arr() As Integer) ' Check for null or empty array, or array with only one element. ' In these cases, no...
Description Algorithm
This function reverses the elements of an array in-place, meaning it modifies the original array directly without allocating any additional memory for a new array. It achieves this by swapping elements from the beginning...
Explanation
The `ReverseArrayInPlace` function utilizes two pointers, `left` starting at the beginning of the array and `right` starting at the end. The algorithm iteratively swaps the elements pointed to by `left` and `right` and then moves `left` one step forward and `right` one step backward. The loop continues as long as `left` is less than `right`. The loop invariant is that all elements outside the range `[left, right]` have already been swapped into their final reversed positions. The time complexity is O(n), where n is the number of elements in the array, because each element is swapped at most once. The space complexity is O(1) because the reversal is performed in-place, using only a constant amount of extra space for the temporary variable used during swapping. Edge cases such as null arrays, empty arrays, and arrays with a single element are handled by the initial conditional check, preventing any operations on invalid inputs and ensuring correctness.
Pseudocode
Function ReverseArrayInPlace(array): If array is null or has 0 or 1 element, return. Initialize left pointer to 0. Initialize right pointer to length of array - 1. While left < right: Swap element at left with element at...
goal: Calculate the sum of digits of a non-negative integer.input: A non-negative integer `n`.output: The sum of the digits of `n`.
Canonical Algorithm Text
Public Module DigitSumModule ' Calculates the sum of the digits of a non-negative integer. Public Function SumOfDigits(ByVal n As Integer) As Integer ' Ensure the input is non-negative. If n < 0 Then Throw New ArgumentOutOfRangeException(NameOf(n), "Input must be a non-negative i...
Description Algorithm
This function computes the sum of all digits in a given non-negative integer. For example, the sum of digits for 123 is 1 + 2 + 3 = 6. This is a fundamental operation used in various number theory problems, checksum calc...
Explanation
The `SumOfDigits` function iteratively extracts the last digit of a number and adds it to a running sum. The modulo operator (`Mod 10`) retrieves the last digit, and integer division (`\\ 10`) effectively removes it. This process continues until the number becomes zero. The loop invariant is that `sum` holds the sum of digits processed so far, and `currentNumber` holds the remaining part of the original number. The time complexity is O(d), where d is the number of digits in the input integer, which is logarithmic with respect to the value of the integer (O(log n)). The space complexity is O(1) as it uses a fixed amount of extra memory. The function correctly handles the edge case of `n = 0` as the `While` loop condition `currentNumber > 0` will be false, and it will return the initialized `sum` of 0.
Pseudocode
Function SumOfDigits(number): If number is negative, throw error. Initialize sum = 0. While number > 0: digit = number modulo 10. Add digit to sum. Divide number by 10 (integer division). Return sum.
Published
Visual Basic .NETGeneral (vbnet)
Find Minimum in Rotated Sorted Array
Difficulty
writing:9
length:5
Popularity
0
Created
2026-01-28 15:01 UTC
Published
2026-01-28 15:16 UTC
Author
Damian
#binary search#rotated array#duplicates#minimum finding#algorithms#logarithmic time#worst case linear
goal: Find the minimum element in a rotated sorted array, possibly with duplicates.input: An array of integers `nums` that was sorted and then rotated.output: The minimum element in the array.
Canonical Algorithm Text
Public Module RotatedArrayMinFinder ' Finds the minimum element in a rotated sorted array. ' The array may contain duplicates. Public Function FindMin(ByVal nums() As Integer) As Integer If nums Is Nothing OrElse nums.Length = 0 Then Throw New ArgumentException("Input array canno...
Description Algorithm
This algorithm finds the minimum element in a rotated sorted array, which is an array that was originally sorted in ascending order and then rotated at some pivot point. The array might contain duplicate elements. It emp...
Explanation
The `FindMin` function uses a binary search approach adapted for rotated sorted arrays, specifically handling duplicates. The core idea is to compare the middle element (`nums(mid)`) with the rightmost element (`nums(right)`). If `nums(mid) > nums(right)`, it implies that the rotation point (and thus the minimum element) lies in the right half of the array (`[mid + 1, right]`). If `nums(mid) < nums(right)`, the minimum element must be in the left half, including `mid` (`[left, mid]`). The most challenging scenario arises when `nums(mid) == nums(right)`. In this case, we cannot definitively determine which half contains the minimum. To resolve this, we safely discard the rightmost element by decrementing `right`. This is because if `nums(right)` is the minimum, `nums(mid)` is also a candidate, and we will eventually find it. If `nums(right)` is not the minimum, discarding it does not lose the true minimum. The loop invariant is that the minimum element is always contained within the `[left, right]` range. The time complexity is O(log n) on average, but degrades to O(n) in the worst case where all elements are identical due to the duplicate handling. The space complexity is O(1) as it uses a constant amount of extra space.
Pseudocode
Function FindMin(array): If array is empty, throw error. Set left = 0, right = length of array - 1. While left < right: Calculate mid = left + (right - left) / 2. If array[mid] > array[right]: Set left = mid + 1. Else If...
Published
GraphQLQuery (graphql)
GraphQL Schema Path Traversal
Difficulty
writing:8
length:10
Popularity
0
Created
2026-01-28 15:01 UTC
Published
2026-01-28 15:16 UTC
Author
Damian
#graphql#schema#traversal#dfs#recursion#graph
goal: Find all paths from a start field to a target field in a GraphQL schema.input: GraphQL schema (map of type names to GraphQLType objects), start type name, start field name, end field name.output: A list of lists, where each inner list represents a path of field names.
Canonical Algorithm Text
package main import ( "fmt" "strings" ) type GraphQLType struct { Name string Fields map[string]*GraphQLType IsNonNull bool IsList bool Description string } func (t *GraphQLType) GetField(fieldName string) *GraphQLType { if field, ok := t.Fields[fieldName]; ok { return field } re...
Description Algorithm
This Go program defines a simplified GraphQL schema and implements a Depth First Search (DFS) algorithm to find all possible traversal paths from a specified starting field within a given type to any field matching a tar...
Explanation
The `findPaths` function uses a recursive Depth First Search (DFS) approach to explore the GraphQL schema. It maintains a `visited` map to prevent infinite loops in case of cyclic schema definitions. The `dfs` helper function takes the current type and the path built so far. If the current field matches the `endField`, the path is recorded. For each field in the current type, it recursively calls `dfs` with the new path. The time complexity is roughly O(V + E) where V is the number of types and E is the number of fields in the schema, but can be worse with deep nesting and cycles. Space complexity is O(D) where D is the maximum depth of the schema, for the recursion stack and visited set.
Pseudocode
function findPaths(schema, startType, startField, endField): initialize empty list `paths` initialize empty set `visited` function dfs(currentType, currentPath): if currentType is null: return create a unique key for cur...
goal: Validate arguments of a GraphQL field against its schema definition.input: A GraphQLField object and its corresponding SchemaTypeField definition.output: A list of error strings, or an empty list if validation passes.
Canonical Algorithm Text
package main import ( "fmt" "reflect" "sort" "strconv" "strings" ) type GraphQLArgument struct { Name string Value interface{} Type string // e.g., "String", "Int", "Boolean", "[String]", "InputObject" IsNonNull bool } type GraphQLField struct { Name string Arguments []*GraphQLAr...
Description Algorithm
This Go program implements a comprehensive GraphQL field argument validation system. It compares the arguments provided in a GraphQL field against its definition in a schema, checking for required arguments, type mismatc...
Explanation
The `validateArguments` function orchestrates the validation process. It first creates a map of provided arguments for efficient lookup. It then iterates through the schema's expected arguments, checking for missing required arguments and validating the types and custom rules of provided arguments using `validateArgumentType`. Finally, it checks for any unexpected arguments not defined in the schema. The `validateArgumentType` function performs basic type checking, including handling NonNull wrappers and common scalar types. For more complex types or specific business logic, it relies on custom `Validator` functions defined in the schema. The time complexity is O(F * A) where F is the number of fields being validated and A is the average number of arguments per field, plus the complexity of custom validators. Space complexity is O(A) for storing provided arguments and errors.
Pseudocode
function validateArguments(field, schemaField): initialize empty list `validationErrors` create map `providedArgs` from `field.Arguments` for each `argName`, `schemaArg` in `schemaField.Arguments`: get `providedArg` from...
goal: Limit the maximum nesting depth of a GraphQL query.input: A list of GraphQLField objects representing the query's root fields, the maximum allowed depth, and the current depth (initially 1 for root).output: A new list of GraphQLField objects representing the query with fields exceeding maxDepth pruned.
Canonical Algorithm Text
package main import ( "fmt" "strings" ) type GraphQLField struct { Name string Alias string Arguments map[string]interface{} Directives []string SelectionSet []*GraphQLField } func limitQueryDepth(fields []*GraphQLField, maxDepth int, currentDepth int) []*GraphQLField { if curren...
Description Algorithm
This Go program implements a GraphQL query depth limiter. It traverses a simplified Abstract Syntax Tree (AST) representation of a GraphQL query and prunes any fields that exceed a specified maximum depth. This is a cruc...
Explanation
The `limitQueryDepth` function uses recursion to traverse the query's field structure. It takes the current list of fields, the maximum allowed depth, and the current depth as parameters. If the `currentDepth` exceeds `maxDepth`, the function returns `nil`, effectively pruning that branch. Otherwise, it iterates through the fields, creating new field objects to avoid modifying the original AST. For fields with selection sets, it recursively calls `limitQueryDepth` with an incremented `currentDepth`. A field is added to the result only if its pruned selection set is not `nil` or if it's a leaf node within the depth limit. The time complexity is O(N) where N is the total number of fields in the query AST, as each field is visited once. The space complexity is O(D) where D is the maximum depth of the query, due to the recursion stack.
Pseudocode
function limitQueryDepth(fields, maxDepth, currentDepth): if currentDepth > maxDepth: return null initialize empty list `limitedFields` for each `field` in `fields`: create a `newField` by copying `field`'s properties (N...
Published
GraphQLQuery (graphql)
GraphQL Field Selection Optimization
Difficulty
writing:8
length:9
Popularity
0
Created
2026-01-28 15:01 UTC
Published
2026-01-28 15:16 UTC
Author
Damian
#graphql#optimization#greedy#recursion#selection set
goal: Reduce GraphQL query payload by removing redundant fields.input: A list of GraphQLField objects representing the current selection set, and a map of strings to booleans indicating required field names or aliases.output: A new list of GraphQLField objects representing the optimized selection set.
Canonical Algorithm Text
package main import ( "fmt" "sort" "strings" ) type GraphQLField struct { Name string Alias string Arguments map[string]interface{} Directives []string SelectionSet []*GraphQLField } func optimizeSelections(fields []*GraphQLField, requiredFields map[string]bool) []*GraphQLField {...
Description Algorithm
This Go program demonstrates a greedy approach to optimizing GraphQL field selections. It takes a list of selected fields and a map of required fields, then recursively prunes unnecessary fields. The goal is to reduce th...
Explanation
The `optimizeSelections` function employs a greedy recursive strategy. For each field, it checks if the field itself is marked as required or if any of its sub-fields are required. If a field has a selection set, it recursively calls `optimizeSelections` on the sub-fields with a refined set of required sub-fields. A field is kept in the optimized selection set if it's directly required or if its optimized sub-selection set is not empty. This greedy approach prioritizes keeping any field that leads to a required piece of data, potentially leaving some fields that could be further optimized in more complex scenarios. Time complexity is roughly proportional to the number of fields and their nesting depth, as each field is visited once. Space complexity is O(D) where D is the maximum nesting depth of the selection set, due to recursion.
Pseudocode
function optimizeSelections(fields, requiredFields): initialize empty list `optimized` for each `field` in `fields`: set `isRequired` to true if `field.Name` or `field.Alias` is in `requiredFields` if `field` has a `Sele...
My Favorite Exercise
You have not saved any favorite exercises yet.
Custom exercise
Paste your own algorithm/text
Max 20,000 characters. (Dangerous HTML/script fragments will be blocked)
Normalized preview:
Publish details
Shown only if you opt to submit for review. Required when consent is checked.