-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTurtleCossing.java
61 lines (46 loc) · 1.32 KB
/
TurtleCossing.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import java.awt.geom.Line2D;
import java.util.*;
class TurtleCossing {
public boolean intersectionFound(List<Line2D> segments){
Line2D last = segments.get(segments.size()-1);
for (Line2D line:segments){
if (last.intersectsLine(line)){
return true;
}
}
return false;
}
public int solution(int[] A) {
int currentMove = 1;
float previousX = 0.0f;
float previousY = 0.0f;
List<Line2D> segments = new ArrayList<>();
segments.add(new Line2D.Float(previousX,previousY,previousX,previousY+A[0]));
previousY = previousY+A[0];
for (int i=1;i<A.length;i++)
{
float newX= previousX;
float newY= previousY;
if (i % 4 == 0){
newY+=A[i];
}
if (i % 4 == 1){
newX+=A[i];
}
if (i % 4 == 2){
newY-=A[i];
}
if (i % 4 == 3){
newX-=A[i];
}
segments.add(new Line2D.Float(previousX,previousY,newX,newY));
previousX = newX;
previousY = newY;
if (intersectionFound(segments)){
break;
}
currentMove++;
}
return currentMove;
}
}