diff --git a/Ship.java b/Ship.java new file mode 100644 index 0000000..267551c --- /dev/null +++ b/Ship.java @@ -0,0 +1,87 @@ +public class Ship{ + public static final int X = 0; + public static final int Y = 1; + private boolean vertical; + private int[] start; + private int[] end; + private int length; + public Ship(int[] start,int[] end){ + + boolean vertical = start[Y] == end[Y]; + this.vertical = vertical; + int cord; + if (vertical) { + cord = X; + } + else { + cord = Y; + } + if (start[cord] < end[cord]){ + this.start = start; + this.end = end; + } + else { + this.start = end; + this.end = start; + } + this.length = this.end[cord] - this.start[cord]+1; + } + + public void print() { + System.out.println("Start: " + "(" + this.start[X] + ", " + this.start[Y] + ")"); + System.out.println("End: " + "(" + this.end[X] + ", " + this.end[Y] + ")"); + } + public int getLength() { + return this.length; + } + + public boolean intersects(Ship other){ + boolean cond1; + boolean cond2; + int cord1; + int cord2; + // + if (other.vertical) { + cord1 = X; + cord2 = Y; + } + else { + cord1 = Y; + cord2 = X; + } + // + + // lines are parallel + if (this.vertical == other.vertical) { + // System.out.println("parallel"); + + // overlaps + cond1 = this.start[cord1] == other.start[cord1]; + + // intersects + cond2 = (other.start[cord2] <= this.end[cord2]) || (this.start[cord2] <= other.end[cord2]); + return cond1 && cond2; + } + // lines are perpendicular + else{ + // System.out.println("perpendicular"); + + // other in range of this with respect to axis cord1 + cond1 = (this.start[cord1] >= other.start[cord1]) && (this.end[cord1] <= other.end[cord1]); + // this in range of other with respect to axis cord2 + cond2 = (other.start[cord2] >= this.start[cord2]) && (other.end[cord2] <= this.end[cord2]); + return cond1 && cond2; + } + } + public static void main(String[] args){ + Ship placedShip1 = new Ship(new int[]{0,0},new int[]{0,2}); + Ship placedShip2 = new Ship(new int[]{1,0},new int[]{1,3}); + placedShip1.print(); + placedShip2.print(); + System.out.println(placedShip1.intersects(placedShip2)); + System.out.println(placedShip1.getLength()); + System.out.println(placedShip2.intersects(placedShip1)); + System.out.println(placedShip2.getLength()); + } + +} \ No newline at end of file diff --git a/Ships.java b/Ships.java deleted file mode 100644 index c9080f8..0000000 --- a/Ships.java +++ /dev/null @@ -1,9 +0,0 @@ -public class Ship{ - private int[2] start; - private int[2] end; - public Ship(int[2] start,int[2] end){ - this.start = start; - this.end = end; - } - - public int[][] \ No newline at end of file