Challenge: Make a data type for holding one of 8 directions allowing increment and overflow

Liam McGillivray yoshi.pit.link.mario at gmail.com
Tue Mar 12 05:38:03 UTC 2024


I am in need of a data type for holding direction information; 
one of 8 directions on a single axis. They are named in terms of 
compass directions. If D had a 4-bit datatype, I would just use 
this and do `+=2` whenever I want to change the datatype, but it 
doesn't.

Perhaps this would be a good programming challenge for someone 
more experienced than me. Make a data type (probably a struct) 
for holding one of 8 directional values using 3 bits. It should 
accept the use of increment operators to change the angle.

Ideally (but optionally), it should work as an enum of the same 
name; "Direction".

Here's a unittest that it should ideally pass:
```
unittest
{
     Direction direction = Direction.N;
     direction++;
     assert(direction == Direction.NE);
     direction+=3;
     assert(direction == Direction.S);
     direction--;
     assert(direction == Direction.SE);
     direction-=4;
     assert(direction == Direction.NW);
}
```


More information about the Digitalmars-d-learn mailing list