Advertisement
Guest User

Untitled

a guest
May 22nd, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. /**
  2. * Euclidean calculations on one-dimensional array indices
  3. */
  4. class Euclid {
  5. /**
  6. * Calculate the euclidean distance between two array indices
  7. *
  8. * @param current index
  9. * @param goal index
  10. * @return the distance from current to goal
  11. */
  12. public int distance(int current, int goal) {
  13. int currentRow = current / width;
  14. int currentCol = current % height;
  15.  
  16. int goalRow = goal / width;
  17. int goalCol = goal % height;
  18.  
  19. return Math.abs(currentRow - goalRow) + Math.abs(currentCol - goalCol);
  20. }
  21.  
  22. /**
  23. * A string representation of the distance calculation.
  24. *
  25. * @param current index
  26. * @param goal index
  27. * @return formatted string
  28. */
  29. public String distanceString(int current, int goal) {
  30. return String.format("Distance from %s to %s is %s", current, goal, distance(current, goal));
  31. }
  32.  
  33. // default width
  34. private int width = 3;
  35.  
  36. // default height
  37. private int height = width;
  38.  
  39. // singleton object
  40. private static Euclid instance;
  41.  
  42. /**
  43. * @return singleton
  44. */
  45. Euclid getInstance() {
  46. return getInstance(width);
  47. }
  48.  
  49. /**
  50. * @return singleton
  51. */
  52. static Euclid getInstance(int n){
  53. return getInstance(n, n);
  54. }
  55.  
  56. /**
  57. * @return singleton
  58. */
  59. static synchronized Euclid getInstance(int width, int height) {
  60. if (instance == null){
  61. instance = new Euclid(width, height);
  62. }
  63.  
  64. return instance;
  65. }
  66.  
  67. // private constructor
  68. private Euclid(int n) {
  69. this.width = n;
  70. this.height = n;
  71. }
  72.  
  73. // private constructor
  74. private Euclid(int i, int j) {
  75. this.width = i;
  76. this.height = j;
  77. }
  78.  
  79. // private constructor
  80. private Euclid() {}
  81.  
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement