r/javaexamples • • Nov 29 '17

Advent of Code - Helper Series: Direction Enum Class

Advent of Code - Helper Series: Direction Enum Class

This is part of a series of code for making your life easier in the yearly Advent of Code competitive coding challenge. It starts every year (since 2015) on December 1st, and posts a new, 2-part challenge every day until Christmas. We don't know what challenges are coming, but based on past years, we can form some idea. I will be posting some of the tools I developed and how to use them.

Handling movement on a 2-d grid:

Many of the challenges for the first two years involved moving an object on a 2d X-Y grid, such as a maze, where the object can be moved one or more units at a time in the 4 non-diagonal directions. This can be easily and gracefully handled in Java using an enum class. You can see my simple example here.

Class Direction

Our Direction enum has four names: NORTH, EAST, SOUTH and WEST.

To use in your class you will probably want a variable like:

Direction.current = Direction.NORTH; // start facing north

Here are the methods available:

Return valueMethodDescription
integergetDx()Return the value to move the object on the X-axis in the current direction by 1 unit
integergetDy()Return the value to move the object on the Y-axis in the current direction by 1 unit
DirectiongetOpposite()Return the opposite of the current direction, i.e. NORTH opposite = SOUTH
DirectiongetRight()Return the next direction in a clockwise rotation, wrapping around infinitely
DirectiongetLeft()Return the next direction in a counter-clockwise rotation, wrapping around infinitely
StringgetAlternate()Return the alternate designation for the current direction, i.e NORTH alternate is UP and EAST alternate is RIGHT
chargetAlternateChar()Return just the first letter of the alternate designation of the current direction, i.e. 'U' for Up (North)
DirectiongetDirectionFromAlternate(String or char)get the proper direction associated with the characters UDRL for up/down/left/right. For String will only use the first character.
booleanrangeCheck(int x, int y, int upper)Simplest range check: Both x and y use same range. Lower bound is zero, inclusive. Upper bound is exclusive. returns true if both x and y within bounds.
booleanrangeCheck(int x, int y, int lower, int upper)range check, x and y use same range. lower bound is inclusive, upper bound is exclusive.
booleanrangeCheck(int x, int y, int xLow, int yLow, int xHigh, int yHigh)range check, x and y can have different upper AND lower bounds.

Here is an example in action, Day 1 from 2016. SPOILER ALERT Note this uses some of my other libraries that I will post here also.

Here is the Direction class. https://gist.github.com/snarkbait/f69045bf2285bc37c7076c6b5f522dbc

2 Upvotes

0 comments sorted by