-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay01.java
More file actions
109 lines (95 loc) · 3.08 KB
/
Day01.java
File metadata and controls
109 lines (95 loc) · 3.08 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.util.List;
public class Day01 {
public static void Run(List<String> input) {
DialMovement[] movements = new DialMovement[input.size()];
for (int i=0;i<input.size(); i++) {
movements[i] = new DialMovement(input.get(i));
}
//p1(movements);
p2(movements);
}
public static void p1(DialMovement[] movements)
{
Dial dial = new Dial();
int zeroCount=0;
for (DialMovement movement : movements){
int newPosition = dial.Move(movement);
if (newPosition == 0)
zeroCount++;
}
System.out.println("01.1: "+zeroCount);
}
public static void p2(DialMovement[] movements)
{
Dial dial = new Dial();
int zeroCount=0;
for (DialMovement movement : movements){
zeroCount += dial.MoveAndCountZeroes(movement);
}
System.out.println("01.2: "+zeroCount);
}
private static class DialMovement {
public char _direction;
public int _steps;
public DialMovement(String movement){
this._direction = movement.charAt(0);
this._steps = Integer.parseInt(movement.substring(1));
}
public char GetDirection(){
return this._direction;
}
public int GetSteps(){
return this._steps;
}
}
private static class Dial{
private int _position=50;
private final int _positionCount=100;
private final int _maxPosition=_positionCount-1;
public int Move(DialMovement movement){
int steps = movement.GetSteps() % _positionCount;
if (movement.GetDirection()=='R'){
_position += steps;
if (_position > _maxPosition)
_position -= _positionCount;
}
else if (movement.GetDirection()=='L'){
_position -= steps;
if (_position < 0)
_position += _positionCount;
}
return _position;
}
public int MoveAndCountZeroes(DialMovement movement) {
boolean startedAtZero = (_position == 0);
// count full revolutions:
int zeroCount = movement.GetSteps() / _positionCount;
// leftover steps after full revolutions:
int steps = movement.GetSteps() % _positionCount;
if (steps != 0) {
if (movement.GetDirection() == 'R') {
_position += steps;
if (_position > _maxPosition){
_position -= _positionCount;
if (!startedAtZero)
zeroCount++;
}
else if (_position == 0){
zeroCount++;
}
} else if (movement.GetDirection() == 'L') {
_position -= steps;
if (_position < 0){
_position += _positionCount;
if (!startedAtZero)
zeroCount++;
}
else if (_position == 0){
zeroCount++;
}
}
}
return zeroCount;
}
}
}