Code archives/Algorithms/Box, Box2 (bb & bmax)

This code has been declared by its author to be Public Domain code.

Download source code

Box, Box2 (bb & bmax) by CS_TBL2006
Box is a normal modulo, to keep any value within the 0..modulo range, but including negative values!

Box2 is nearly the same, except that it keeps a value within the given lo..hi range.

hm... example :P

if this is the range for box2: -4,2 then this is what the values -5..5 give:

1
-4
-3
-2
-1
0
1
-4
-3
-2
-1

Box works similary, except that its range is always 0..modulo, so -5..5 at a Box(<value>,3)would look like:

1
2
0
1
2
0
1
2
0
1
2


People who work with banks, pixmaps and other memchunks that can't go beyond the bounds will prolly see most use of all this, esp. when used for drawing graphics in such.
bmax:

Function Box:Int(value:Int,modulo:Int)
	If modulo<1 modulo=1
	Return ((value Mod modulo)+modulo) Mod modulo
End Function

Function Box2:Int(value:Int,lo:Int,hi:Int)
	Local o:Int
	If lo>hi
		o=lo
		lo=hi
		hi=o
	EndIf
	Local Modulo:Int=hi-lo
	value:-lo
	If modulo<1 modulo=1
	Return lo+((value Mod modulo)+modulo) Mod modulo
End Function


non-bmax:

Function Box(value,modulo)
	If modulo<1 modulo=1
	Return ((value Mod modulo)+modulo) Mod modulo
End Function

Function Box2(value,lo,hi)
	If lo>hi
		o=lo
		lo=hi
		hi=o
	EndIf
	Modulo=hi-lo
	value=value-lo
	If modulo<1 modulo=1
	Return lo+((value Mod modulo)+modulo) Mod modulo
End Function

Comments

N2006
I think this is known as 'clamping', actually.

Or maybe 'looping' if the term wasn't already reserved for, well, loops.

Hm... I still like clamping, since it's clamping the value within a range.


Code Archives Forum