[Gambas-user] function to "wrap" a number between upper and lower bounds

Kevin Fishburne kevinfishburne at ...1887...
Thu Dec 13 00:50:30 CET 2012


On 12/12/2012 05:33 PM, Kevin Fishburne wrote:
> I need a function like:
>
> Wrap(number, lowerbound, upperbound)
>
> such that Wrap(5,1, 3) will return 2. In other words, it "wraps" the
> number around the supplied bounds and returns where it "lands". I
> believe it would work similarly to assigning a value to a datatype
> outside its scope, like assigning 300 to a Byte type.
>
> I looked up some solutions online and none of them really seemed to work
> properly and their comments were surrounded by debate. Is there an
> efficient way to do this, and does anyone think it would be a useful
> function to add to Gambas itself?
>

I found this:

|int  Wrap(int  kX,  int  const  kLowerBound,  int  const  kUpperBound)
{
     int  range_size=  kUpperBound-  kLowerBound+  1;

     if  (kX<  kLowerBound)
         kX+=  range_size*  ((kLowerBound-  kX)  /  range_size+  1);

     return  kLowerBound+  (kX-  kLowerBound)  %  range_size;
}|


however it relies on the Mod operator (%), which I think means it will 
only work for integers. Is there a way to do this for singles/floats?

-- 
Kevin Fishburne
Eight Virtues
www: http://sales.eightvirtues.com
e-mail: sales at ...1887...
phone: (770) 853-6271





More information about the User mailing list