Create an array, each element of which is associated with a block of 30 degrees:
Car::EDirection dirlist[] = {
Car::EDirection::RIGHT,
Car::EDirection::UP_RIGHT,
Car::EDirection::UP,
Car::EDirection::UP,
Car::EDirection::UP_LEFT,
Car::EDirection::LEFT,
Car::EDirection::LEFT,
Car::EDirection::DOWN_LEFT,
Car::EDirection::DOWN,
Car::EDirection::DOWN,
Car::EDirection::DOWN_RIGHT,
Car::EDirection::RIGHT
};
Then you can index the array with the angle / 30:
this->_car.edir = dirlist[(this->_car.getAbsoluteAngle() % 360) / 30];
No comparisons or branching required.
The result however is slightly off from the original. Values on the borders, i.e. 30, 60, 120, etc. are placed in the next category. For example, in the original code the valid values for UP_RIGHT
are 31 to 60. The above code assigns 30 to 59 to UP_RIGHT
.
We can get around this by subtracting 1 from the angle:
this->_car.edir = dirlist[((this->_car.getAbsoluteAngle() - 1) % 360) / 30];
This now gives us RIGHT
for 30, UP_RIGHT
for 60, etc.
In the case of 0, the expression becomes (-1 % 360) / 30
. This is valid because -1 % 360 == -1
and -1 / 30 == 0
, so we still get an index of 0.
Section 5.6 of the C++ standard confirms this behavior:
4 The binary /
operator yields the quotient, and the binary %
operator yields the remainder from the division of the first
expression by the second. If the second operand of /
or %
is zero
the behavior is undefined. For integral operands the /
operator
yields the algebraic quotient with any fractional part discarded. if
the quotient a/b
is representable in the type of the result,
(a/b)*b + a%b
is equal to a
.
EDIT:
There were many questions raised regarding the readability and maintainability of a construct like this. The answer given by motoDrizzt is a good example of simplifying the original construct that is more maintainable and isn't quite as "ugly".
Expanding on his answer, here's another example making use of the ternary operator. Since each case in the original post is assigning to the same variable, using this operator can help increase readability further.
int angle = ((this->_car.getAbsoluteAngle() % 360) + 360) % 360;
this->_car.edir = (angle <= 30) ? Car::EDirection::RIGHT :
(angle <= 60) ? Car::EDirection::UP_RIGHT :
(angle <= 120) ? Car::EDirection::UP :
(angle <= 150) ? Car::EDirection::UP_LEFT :
(angle <= 210) ? Car::EDirection::LEFT :
(angle <= 240) ? Car::EDirection::DOWN_LEFT :
(angle <= 300) ? Car::EDirection::DOWN:
(angle <= 330) ? Car::EDirection::DOWN_RIGHT :
Car::EDirection::RIGHT;
this->_car.getAbsoluteAngle()
once before the whole cascade.this
(this->
) is not needed and doesn't really do anything good to the readability..>
tests; they aren't needed, since each of them has already been tested (in the opposite direction) in the previousif
statement.else if
.