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

Richard (Rikki) Andrew Cattermole richard at cattermole.co.nz
Tue Mar 12 06:38:28 UTC 2024


By taking advantage of integer wrapping and a bitwise and, its quite a 
simple problem to solve!

Challenge for the reader: add support for binary operations and toString 
support.

https://dlang.org/spec/operatoroverloading.html

```d
struct Direction {
     private int value;

     Direction opUnary(string op:"++")() {
         value++;
         value &= 7;
         return this;
     }

     Direction opUnary(string op:"--")() {
         value--;
         value &= 7;
         return this;
     }

     void opOpAssign(string op:"+")(int amount) {
         value += amount;
         value &= 7;
     }

     void opOpAssign(string op:"-")(int amount) {
         value -= amount;
         value &= 7;
     }

     enum Direction N = Direction(0);
     enum Direction NE = Direction(1);
     enum Direction E = Direction(2);
     enum Direction SE = Direction(3);
     enum Direction S = Direction(4);
     enum Direction SW = Direction(5);
     enum Direction W = Direction(6);
     enum Direction NW = Direction(7);
}

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