-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPart1.java
More file actions
106 lines (89 loc) · 3.09 KB
/
Copy pathPart1.java
File metadata and controls
106 lines (89 loc) · 3.09 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package y2016.d01;
import common.Geometry;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Part1 {
private static enum Directions {
NORTH, EAST, SOUTH, WEST
}
private static Set<String> seen = new HashSet<>();
public static void main(String[] args) throws Exception {
String[] chainOfCommand = readFile();
int posX = 0;
int posY = 0;
Directions heading = Directions.NORTH;
//storePosition(posX, posY);
for (String command: chainOfCommand) {
// System.out.println(pos + " " + command);
heading = turn(command, heading);
int distance = Integer.parseInt(command.substring(1));
switch (heading) {
case NORTH:
for (int i = 0; i < distance; i++) {
storePosition(posX, posY);
posY++;
}
break;
case EAST:
for (int i = 0; i < distance; i++) {
storePosition(posX, posY);
posX++;
}
break;
case SOUTH:
for (int i = 0; i < distance; i++) {
storePosition(posX, posY);
posY--;
}
break;
case WEST:
for (int i = 0; i < distance; i++) {
storePosition(posX, posY);
posX--;
}
break;
}
}
System.out.println(Geometry.taxiDistance(0, 0, posX, posY));
}
private static void storePosition(int posX, int posY) {
String pos = "" + posX + ":" + posY;
System.out.println(pos);
if (!seen.add(pos)) {
System.out.println(Geometry.taxiDistance(0, 0, posX, posY));
System.exit(0);
}
}
private static Directions turn(String command, Directions current) throws Exception {
if (command.charAt(0) == 'R') {
switch (current) {
case NORTH: return Directions.EAST;
case EAST: return Directions.SOUTH;
case SOUTH: return Directions.WEST;
case WEST: return Directions.NORTH;
}
}
switch (current) {
case NORTH: return Directions.WEST;
case EAST: return Directions.NORTH;
case SOUTH: return Directions.EAST;
case WEST: return Directions.SOUTH;
}
throw new Exception("Whaaaaaaaaa....???!!!!");
}
public static String[] readFile() {
File file = new File("src/main/java/y2016/d01/in.txt");
String rawLine = "";
try {
Scanner scanner = new Scanner(file);
rawLine = scanner.nextLine();
return rawLine.trim().split(", ");
} catch (Exception e) {
System.out.println(e.getMessage());
}
return new String[]{""};
}
}