Bot Saves Princess

See the original problem on HackerRank.

Solutions

Here is a possible C++ solution:

 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
void displayPathtoPrincess(const vector<string>& grid)
{
    // find mario and peach
    pair<short, short> mario, peach;
    for (auto i=0; i<grid.size(); ++i)
    {
        for (auto j=0; j<grid.size(); ++j)
        {
            if (grid[i][j] == 'm')
                mario = {i, j};
            if (grid[i][j] == 'p')
                peach = {i, j};
        }    
    }
    
    auto move = [](int& delta, const char* direction, auto compare, auto incr){
      while (compare(delta, 0))
      {
          cout << direction << "\n";
          delta = incr(delta, 1);
      }              
    };
    
    auto deltaX = mario.first - peach.first;
    auto deltaY = mario.second - peach.second;
    move(deltaX, "UP", greater<int>{}, minus<int>{});
    move(deltaX, "DOWN", less<int>{}, plus<int>{});
    move(deltaY, "LEFT", greater<int>{}, minus<int>{});
    move(deltaY, "RIGHT", less<int>{}, plus<int>{});
}

int main(void) {

    int m; cin >> m;
    vector<string> grid(m);
    copy_n(istream_iterator<string>(cin), m, begin(grid));
    displayPathtoPrincess(grid);
}
We've worked on this challenge in these gyms: modena 
comments powered by Disqus