I'm looking for an efficient algorithm that clamps an integer value within a range, while also changing its base10 end to one of multiple, variable length ends.
This should clamp a value between the min and max, while changing the end to one of the specific ends defined in ends, as close as possible to the original value.
Example input data:
ends: [26, 201, 330] (sorted list of integers, at least a factor 10 smaller than <value>)
min: 5350
max: 7392
value: 2000 -> 5426
value: 6205 -> 6201
value: 7400 -> 7330
I'll implement this in Go, but any pseudocode or other imperative language is also appreciated.
I guess you know how to clamp:
Then to remove the end and replace it with what it should end, you need the next higher power of 10:
So replacing the end of a number becomes simple:
Then you can check the other candidates on both sides, so when
m = replace(clamp(n, min, max), end)andp = nextPowerOf10(end), the other candidates are:m - pandm + p, everything put together:Examples: