Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Euclidean calculations on one-dimensional array indices
- */
- class Euclid {
- /**
- * Calculate the euclidean distance between two array indices
- *
- * @param current index
- * @param goal index
- * @return the distance from current to goal
- */
- public int distance(int current, int goal) {
- int currentRow = current / width;
- int currentCol = current % height;
- int goalRow = goal / width;
- int goalCol = goal % height;
- return Math.abs(currentRow - goalRow) + Math.abs(currentCol - goalCol);
- }
- /**
- * A string representation of the distance calculation.
- *
- * @param current index
- * @param goal index
- * @return formatted string
- */
- public String distanceString(int current, int goal) {
- return String.format("Distance from %s to %s is %s", current, goal, distance(current, goal));
- }
- // default width
- private int width = 3;
- // default height
- private int height = width;
- // singleton object
- private static Euclid instance;
- /**
- * @return singleton
- */
- Euclid getInstance() {
- return getInstance(width);
- }
- /**
- * @return singleton
- */
- static Euclid getInstance(int n){
- return getInstance(n, n);
- }
- /**
- * @return singleton
- */
- static synchronized Euclid getInstance(int width, int height) {
- if (instance == null){
- instance = new Euclid(width, height);
- }
- return instance;
- }
- // private constructor
- private Euclid(int n) {
- this.width = n;
- this.height = n;
- }
- // private constructor
- private Euclid(int i, int j) {
- this.width = i;
- this.height = j;
- }
- // private constructor
- private Euclid() {}
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement