To test to see if a value is within a range of numbers, we can use a simple expression like
min <= value and value <= max.
Is there an equivalent expression to test if a value is within a range that uses a stepping.
I think the following function would suffice, for ascending range. Not too sure about descending ranges.
<extension> function IsBewteen( value As Integer, min As Integer, max As Integer, stepping As Integer) As Boolean If min <= max Then If stepping <= 0 Then Throw New ArgumentOutOfRangeException(NameOf(stepping), "Must have a non-zero positive value.") Return ((min <= value) And (value <= max)) AndAlso ( (value Mod stepping) = (min Mod stepping) ) Else If stepping >=0 Then Throw New ArgumentOutOfRangeException(NameOf(stepping), "Must have a non-zero negative value.") Return value.IsBewteen(max, min, -stepping) End IF End Function
There is still an issue around the
Integer.MaxValue, any suggestion on how to manage them with out resorting to enclosing it in a
try ... catch block?
I want to fairly efficiently to check if a value, is within two bounds but that range isn't continuous but has a regular stepping.
start := 0, finish := 10, stepping:= 2' Ifvalue:=2
then return true. Ifvalue=7` return false.
The following works, assuming we if pass in arguments that satisfies the for loop conditions.
Function IsBetween(value as Integer, start As Integer, finish As Integer, stepping As Integer ) As Boolean For index = start To finish Step stepping If index = value Then Return True Next Return False End Function
But it is rather inefficient, since we could check if a value is within some bounds simply using
Math.Min(start, finish) <= value and value<=Math.Max(start, finish). But this doesn't take into account a stepping. My question is, "Is there an efficient way to do that?"
(value - start) % step == 0?