-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay9a.java
More file actions
109 lines (98 loc) · 2.29 KB
/
Day9a.java
File metadata and controls
109 lines (98 loc) · 2.29 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
107
108
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
import java.io.File;
public class Day9a {
public static String myRead(Scanner scanner) {
String line;
try {
line = scanner.nextLine().trim();
} catch (Exception e) {
line = null;
}
return line;
}
public static Scanner myScanner(File text) {
Scanner scanner;
try {
scanner = new Scanner(text);
} catch (Exception e) {
System.out.println("No Scanner");
return null;
}
return scanner;
}
public static void main(String[] args) {
File text = new File("/Users/axelteo/Desktop/AdventofCode/Day9input.txt");
Scanner scanner = myScanner(text);
if (scanner == null) {
return;
}
ArrayList<Point> tailPos = new ArrayList<>();
Point head = new Point(0, 0);
Point tail = new Point(0, 0);
tailPos.add(tail);
String line;
String[] tokens;
while ((line = myRead(scanner)) != null) {
tokens = line.split(" ", 0);
int moves = Integer.valueOf(tokens[1]);
for (int i = 0; i < moves; ++i) {
Point oldHead = head;
head = head.move(tokens[0]);
if (!head.isAdj(tail)) {
tail = oldHead;
if (!tailPos.contains(tail)) {
tailPos.add(tail);
}
}
}
}
System.out.println("Num of points tail visited is: " + tailPos.size());
}
}
class Point {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public boolean isAdj(Point pt) {
int xDiff = this.x - pt.x;
int yDiff = this.y - pt.y;
if (xDiff <= 1 && xDiff >= -1) {
if (yDiff <= 1 && yDiff >= -1) {
return true;
}
}
return false;
}
public Point move(String dir) {
if (dir.equals("U")) {
return new Point(this.x, this.y + 1);
}
if (dir.equals("D")) {
return new Point(this.x, this.y - 1);
}
if (dir.equals("L")) {
return new Point(this.x - 1, this.y);
}
if (dir.equals("R")) {
return new Point(this.x + 1, this.y);
}
System.out.println("error with move");
return null;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Point)) {
return false;
}
Point tmp = (Point) obj;
if (this.x == tmp.x && this.y == tmp.y) {
return true;
}
return false;
}
}