Browse Source

Intersect method works

shiptest
school 7 years ago
parent
commit
30c3ba8239
  1. 11
      Ship.java
  2. 37
      ShipTest.java

11
Ship.java

@ -50,7 +50,7 @@ public class Ship{
int cord1;
int cord2;
// <necessary bit, ensures algorithm works both when other is oriented horizontally or vertically>
if (other.isVertical()) {
if (other.vertical) {
cord1 = X;
cord2 = Y;
}
@ -65,20 +65,19 @@ public class Ship{
int o_s1 = other.start[cord1];
int o_e1 = other.end[cord1];
int t_s2 = t_s2;
int t_s2 = this.start[cord2];
int t_e2 = this.end[cord2];
int o_s2 = other.start[cord2];
int o_e2 = other.end[cord2];
// lines are parallel
if (this.vertical == other.isVertical()) {
if (this.vertical == other.vertical) {
// overlaps
cond1 = t_s2 == o_s2;
// intersects
cond2 = o_e1 <= t_s1;
cond3 = t_e1 <= o_s1;
cond2 = o_e1 >= t_s1;
cond3 = t_e1 >= o_s1;
return cond1 && (cond2 || cond3);
}

37
ShipTest.java

@ -1,6 +1,39 @@
import java.util.Scanner;
public class ShipTest{
public testShips(Ship ship1, Ship ship2){
public static void testShips(Ship ship1, Ship ship2,String name){
System.out.println("Testing " + name);
ship1.print();
System.out.println();
ship2.print();
System.out.println(ship1.intersects(ship2)+"=="+ship2.intersects(ship1));
}
public static void main(String[] args){
Ship test_intersect0 = new Ship(new int[]{
int[] ship1start = new int[2];
int[] ship1end = new int[2];
int[] ship2start = new int[2];
int[] ship2end = new int[2];
String name;
while (true) {
Scanner input = new Scanner(System.in);
System.out.print("Enter test name: ");
name = input.nextLine();
System.out.print("Enter ship1 start: ");
ship1start[0] = input.nextInt();
ship1start[1] = input.nextInt();
System.out.print("Enter ship1 end: ");
ship1end[0] = input.nextInt();
ship1end[1] = input.nextInt();
System.out.print("Enter ship2 start: ");
ship2start[0] = input.nextInt();
ship2start[1] = input.nextInt();
System.out.print("Enter ship2 end: ");
ship2end[0] = input.nextInt();
ship2end[1] = input.nextInt();
testShips(new Ship(ship1start,ship1end),new Ship(ship2start,ship2end),name);
}
}
}
Loading…
Cancel
Save