Skip to the code
cf.
+25 XP

#178 Snap to a Guide Line

medium

A design tool snaps the cursor to straight guide lines. A guide runs from point start to point end, and the cursor is at point; each point is [x, y]. The guide is a segment: it does not continue past its ends.

Write distanceToGuide(point, start, end) that returns the shortest distance from the cursor to any point on the segment. Answers within 1e-5 count as correct.

A point on the segment can be written as start + t × (end - start) for t from 0 to 1, and its distance to the cursor first falls and then rises as t grows.

Example 1

Input: point = [2,3], start = [0,0], end = [4,0]
Output: 3

The closest point on the guide is [2, 0], straight below the cursor.

Example 2

Input: point = [7,4], start = [0,0], end = [4,0]
Output: 5

The cursor is past the end, so the closest point is the end [4, 0]: a 3-4-5 triangle.

Constraints

  • Coordinates are whole numbers from -10^4 to 10^4.
  • start and end may be the same point.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).