Drill

ProblemsC# › validation

Keep a value inside its range

easyvalidationMathC#

A slider hands back whatever the user dragged it to, and the settings layer pins it into the range the setting allows.

ClampToRange(amount: int, low: int, high: int) → int

C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

public int ClampToRange(int amount, int low, int high) {
    
}

Worked examples

CallResult
ClampToRange(5, 1, 10)5
ClampToRange(0, 1, 10)1
ClampToRange(99, 1, 10)10
ClampToRange(5, 10, 1)5

Hint

Sort the bounds first and the rest is two comparisons.

Reference solution in C#
public int ClampToRange(int amount, int low, int high) {
    int lo = Math.Min(low, high), hi = Math.Max(low, high);
    return Math.Min(hi, Math.Max(lo, amount));
}

The same problem in another language

More validation problems in C#