[Codewars] Path Finder #4: where are you?

Path Finder #4: where are you?

  • Time :
  • Space :
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
using namespace std;

int dx[4]{-1, 0, 1, 0}, dy[4]{0, 1, 0, -1};

struct State {
int x = 0,y = 0;
int dir = 0;
}state;

std::vector<int> i_am_here(std::string path) {
int step = 0;
for(char x : path) {
if(!isdigit(x)) {
state.x += dx[state.dir] * step;
state.y += dy[state.dir] * step;
step = 0;
} else step = step * 10 + (x - '0');

if(x == 'r') state.dir = (state.dir + 1) % 4;
else if(x == 'l') state.dir = (state.dir - 1 + 4) % 4;
else if(x == 'R') state.dir = (state.dir + 2) % 4;
else if(x == 'L') state.dir = (state.dir + 2) % 4;
}
state.x += dx[state.dir] * step;
state.y += dy[state.dir] * step;
return {state.x,state.y};
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/06/05/PS/Codewars/path-finder-4-where-are-you/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.