-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmarsrover.js
96 lines (84 loc) · 2.05 KB
/
marsrover.js
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
// Rover Object Goes Here
// ======================
const north = "N";
const west = "W";
const east = "E";
const south = "S";
let marsRover = {
direction: north,
x: 0,
y: 0,
travelLog:[],
};
// ======================
function turnLeft(rover) {
switch(rover.direction) {
case north:
rover.direction = west;
break;
case west:
rover.direction = south;
break;
case south:
rover.direction = east;
break;
case east:
rover.direction = north;
break;
}
console.log(`Rover is now facing ${rover.direction}`);
}
function turnRight(rover){
switch(rover.direction) {
case north:
rover.direction = east;
break;
case east:
rover.direction = south;
break;
case south:
rover.direction = west;
break;
case west:
rover.direction = north;
break;
}
console.log(`Rover is now facing ${rover.direction}`);
}
function moveForward(rover){
let coordinates = [rover.x, rover.y];
rover.travelLog.push(coordinates);
if(rover.direction == north){
rover.y--;
} else if(rover.direction == south){
rover.y++;
} else if(rover.direction == east){
rover.x++;
} else if(rover.direction == west){
rover.x--;
}
if(rover.x < 0 || rover.x > 9 || rover.y < 0 || rover.y > 9 ){
rover.x = coordinates[0];
rover.y = coordinates[1];
console.log("stop moving");
}
console.log(`x = ${rover.x} and y = ${rover.y}`);
}
const forward = "f";
const right = "r";
const left = "l";
function executeCommands(commands, rover){
for(let i=0; i < commands.length; i++){
if(commands[i] == left){
turnLeft(rover);
} else if(commands[i] == right){
turnRight(rover);
} else if(commands[i] == forward){
moveForward(rover);
}
}
for(let i = 0; i < rover.travelLog.length; i++ ){
console.log(`${rover.travelLog[i]}`)
}
}
executeCommands('rffrfflfrfffffffffffffffffff', marsRover);