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
|
#advent of code 2020
#day 12
#Im experimenting with different parsing,
#the [:-1] is for skipping the empty line
#big mistake: giving north a negative value,
#which meant that my left and right turns where flipped
#changed it after getting the correct value
navigationInstructions = [line for line in open("12.in","r").read().split("\n")][:-1];
directions = dict();
directions[0] = (0,1); #east
directions[1] = (-1,0); #south
directions[2] = (0,-1); #west
directions[3] = (1,0); #north
#part 1
def actions(act,val,face):
if act == "N":
return (val,0,face);
elif act =="S":
return (-val,0,face);
elif act == "E":
return (0,val,face);
elif act == "W":
return (0,-val,face);
elif act == "L":
turn = val//90;
tempF = (4+face-turn)%4;
return (0,0,tempF);
elif act == "R":
turn = val//90;
tempF = (4+face+turn)%4
return (0,0,tempF);
elif act == "F":
mody,modx = directions[face];
return (mody*val,modx*val,face);
#part 2
def NewActions(act,val,wayY,wayX):
if act == "N":
return (0,0,wayY+val,wayX);
elif act =="S":
return (0,0,wayY-val,wayX);
elif act == "E":
return (0,0,wayY,wayX+val);
elif act == "W":
return (0,0,wayY,wayX-val);
elif act == "L":
turn = val//90;
tempW = (wayY,wayX);
for t in range(turn):
tempW = (tempW[1],-tempW[0]);
return (0,0,tempW[0],tempW[1]);
elif act == "R":
turn = val//90;
tempW = (wayY,wayX);
for t in range(turn):
tempW = (-tempW[1],tempW[0]);
return (0,0,tempW[0],tempW[1]);
elif act == "F":
return (wayY*val,wayX*val,wayY,wayX);
else:
return False;
#ship coordinates, part 1
X1 = 0;
Y1 = 0;
D1 = 0; #direction
#ship coordinates, part 2
X2,Y2,D2 = 0,0,0;
WX, WY = 10,1; #waypoint relative coordinates
for instr in navigationInstructions:
action = instr[0];
value = int(instr[1:]);
dy1,dx1,dd1 = actions(action,value,D1); #part 1
Y1 += dy1;
X1 += dx1;
D1 = dd1;
dy2,dx2,dwy,dwx = NewActions(action,value,WY, WX); #part 2
Y2 += dy2;
X2 += dx2;
WY = dwy;
WX = dwx;
if X1 < 0: X1 = -X1;
if Y1 < 0: Y1 = -Y1;
p1 = X1 + Y1;
if X2 < 0: X2 = -X2;
if Y2 < 0: Y2 = -Y2;
p2 = X2 + Y2;
print("part 1 =",p1);
print("part 2 =",p2);
|