DreadPirateShawn
DreadPirateShawn

Reputation: 8402

algorithm to determine whether a value is within a range of a multiple

Algorithm question:

Let's say I want to determine whether a value is within a range (eg 2) of a tens multiple -- so, 8-12, 18-22, 28-32, etc.

My current solution is to add the range to the value, mod by 10, then re-subtract the range -- thus leaving me with something from -2 to 8 -- and then check whether the absolute value is less than the desired range.

value = 38
range = 2
cycle = 10

tweaked_mod = ((value + range) % cycle) - range
# tweaked_mod = -2
within_range = (abs(tweaked_mod) <= range)
# within_range = True

versus:

value = 37
range = 2
cycle = 10

tweaked_mod = ((value + range) % cycle) - range
# tweaked_mod = 7
within_range = (abs(tweaked_mod) <= range)
# within_range = False

It works, but it's awkward.

Am I missing a more intuitive / succinct algorithm here?

Upvotes: 3

Views: 338

Answers (1)

Boris Strandjev
Boris Strandjev

Reputation: 46943

I find this solution easier to understand:

remainder = (value % cycle)
(remainder <= range) || (cycle - remainder) <= range

Basically I find the remainder of the value I search for in respect of the modulo (cycle) and then check if it is within the expected range.

Alternative:

An alternative solution (doing essentially the same) will be:

remainder = (value % cycle)
min(remainder, cycle - remainder) <= range

You are free to choose whichever of the two solutions you like better.

NOTE This algorithm works verbatim if range < cycle. In the other cases answer is always true.

Upvotes: 7

Related Questions