You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.6 KiB

  1. public class Ship{
  2. public static final int X = 0;
  3. public static final int Y = 1;
  4. private boolean vertical;
  5. private int[] start;
  6. private int[] end;
  7. private int length;
  8. public Ship(int[] start,int[] end){
  9. boolean vertical = start[Y] == end[Y];
  10. this.vertical = vertical;
  11. int cord;
  12. if (vertical) {
  13. cord = X;
  14. }
  15. else {
  16. cord = Y;
  17. }
  18. if (start[cord] < end[cord]){
  19. this.start = start;
  20. this.end = end;
  21. }
  22. else {
  23. this.start = end;
  24. this.end = start;
  25. }
  26. this.length = this.end[cord] - this.start[cord]+1;
  27. }
  28. public void print() {
  29. System.out.println("Start: " + "(" + this.start[X] + ", " + this.start[Y] + ")");
  30. System.out.println("End: " + "(" + this.end[X] + ", " + this.end[Y] + ")");
  31. }
  32. public int getLength() {
  33. return this.length;
  34. }
  35. public boolean intersects(Ship other){
  36. boolean cond1;
  37. boolean cond2;
  38. int cord1;
  39. int cord2;
  40. // <necessary bit, ensures algorithm works both when other is oriented horizontally or vertically>
  41. if (other.vertical) {
  42. cord1 = X;
  43. cord2 = Y;
  44. }
  45. else {
  46. cord1 = Y;
  47. cord2 = X;
  48. }
  49. // </necessary bit>
  50. // lines are parallel
  51. if (this.vertical == other.vertical) {
  52. // System.out.println("parallel");
  53. // overlaps
  54. cond1 = this.start[cord1] == other.start[cord1];
  55. // intersects
  56. cond2 = (other.start[cord2] <= this.end[cord2]) || (this.start[cord2] <= other.end[cord2]);
  57. return cond1 && cond2;
  58. }
  59. // lines are perpendicular
  60. else{
  61. // System.out.println("perpendicular");
  62. // other in range of this with respect to axis cord1
  63. cond1 = (this.start[cord1] >= other.start[cord1]) && (this.end[cord1] <= other.end[cord1]);
  64. // this in range of other with respect to axis cord2
  65. cond2 = (other.start[cord2] >= this.start[cord2]) && (other.end[cord2] <= this.end[cord2]);
  66. return cond1 && cond2;
  67. }
  68. }
  69. public static void main(String[] args){
  70. Ship placedShip1 = new Ship(new int[]{0,0},new int[]{0,2});
  71. Ship placedShip2 = new Ship(new int[]{1,0},new int[]{1,3});
  72. placedShip1.print();
  73. placedShip2.print();
  74. System.out.println(placedShip1.intersects(placedShip2));
  75. System.out.println(placedShip1.getLength());
  76. System.out.println(placedShip2.intersects(placedShip1));
  77. System.out.println(placedShip2.getLength());
  78. }
  79. }