# There must be a better way

Derek Parnell derek at nomail.afraid.org
Tue Aug 1 19:49:42 PDT 2006

```On Wed, 2 Aug 2006 03:57:07 +0200, Emp wrote:

> I wrap two values (x && y coordinates) like this:
>
> uint wrap(uint axis, int value)
> {
>  int max=0;
>  if (axis==1) max=25;
>  if (axis==0) max=10;
>  if(value>=max){
>   return (value % max);
>  }
>  if(value<0){
>   int newValue;
>   newValue=value;
>   while(newValue<0){
>    newValue+=max;
>   }
>   return (newValue);
>  }
> return value;
> }
>
> So I need to do things like 'wrap(0,currentX)' everytime to wrap the
> currentX. Like:
>
> (the original x && y need to be untouched)
> array[wrap(0,currentX)][wrap(1,currentY)];
>
> Is this really the best way, or am I just missing some nifty D
> programming?

Here is an alternative...

const AXIS0 = 10;
const AXIS1 = 25;

int mwrap(int max, int value)
{
if(value >= max)
{
value %= max;
}
else if (value < 0)
{
value = max + (value % max);
if (value == max)
value = 0;
}

return value;
}

unittest
{
assert(mwrap(AXIS0, 35) == 5);
assert(mwrap(AXIS0, 0) == 0);
assert(mwrap(AXIS0, 6) == 6);
assert(mwrap(AXIS0, 10) == 0);

assert(mwrap(AXIS1, 35) == 10);
assert(mwrap(AXIS1, 0) == 0);
assert(mwrap(AXIS1, 6) == 6);
assert(mwrap(AXIS1, 25) == 0);

assert(mwrap(AXIS0, -35) == 5);
assert(mwrap(AXIS0, -6) == 4);
assert(mwrap(AXIS0, -10) == 0);

assert(mwrap(AXIS1, -35) == 15);
assert(mwrap(AXIS1, -6) == 19);
assert(mwrap(AXIS1, -25) == 0);
}

The main change I made was to supply the actual maximum value as a
parameter. This will make the function more flexible in future. The other
change was to not a D trick, just a maths 'trick'.

> Two small questions:
> 1. Isn't inout more used than out for functions, in contrast to what the
> website says?
>     I use inout quite often, or am I just doing something wrong?

Yes, IMHO <g>
The use of return values rather than updating the input parameters leads to
programs that are easier to maintain and re-use.

> 2. Is it really difficult to make '>=" correctly compare an unsigned and a
> signed int?

No. This is huge wart in D. For some Bob-only-knows reason, D silently
interprets the bit-value of an int as if was a uint when doing such
comparisons. Daft!

If you know that there is not going to be an overflow issue, you can do
this ...

if (cast(int)my_uint >= my_int) ...

which is saying you want the uint converted to a signed value before
comparing the two.

--
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocrity!"
2/08/2006 12:41:01 PM

```