Skip to content

Instantly share code, notes, and snippets.

@alwarren
Last active May 12, 2019 14:26
Show Gist options
  • Save alwarren/95c9a61b28a6a7975d19a2b148c51a84 to your computer and use it in GitHub Desktop.
Save alwarren/95c9a61b28a6a7975d19a2b148c51a84 to your computer and use it in GitHub Desktop.
Euclidean calculations on one-dimensional array indices. A work in progress.
/**
* 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() {}
}
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
Distance from 0 to 0 is 0
Distance from 0 to 1 is 1
Distance from 0 to 2 is 2
Distance from 0 to 3 is 3
Distance from 0 to 4 is 1
Distance from 0 to 5 is 2
Distance from 0 to 6 is 3
Distance from 0 to 7 is 4
Distance from 0 to 8 is 2
Distance from 0 to 9 is 3
Distance from 0 to 10 is 4
Distance from 0 to 11 is 5
Distance from 0 to 12 is 3
Distance from 0 to 13 is 4
Distance from 0 to 14 is 5
Distance from 0 to 15 is 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment