Problem
/*
I need a function that takes the name of the movie to look up and
the width of the letter grid, and computes the key presses that
will enter that string on the DVR grid. The output should be a
string, with "u", "d", "l", "r", and "!" corresponding to up,
down, left, right, and select.
For example, with a grid of width 5,
a b c d e
f g h i j
k l m n o
p q r s t
u v w x y
z
the movie "up" would be "dddd!u!".
*/
Solution
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class SelectMovie
{
public:
SelectMovie(string& name):_x(0), _y(0) { _movie = name; _msg.clear();}
SelectMovie(string&& name):_x(0), _y(0) { _movie = name; _msg.clear(); }
void PrintMsg()
{
CalcPath();
cout << _msg << endl;
}
private:
void CalcPath()
{
for(auto c: _movie){
Next(_tolower(c));
}
}
void Next(char target)
{
int target_x = (target - 'a') / 5;
int target_y = (target - 'a') % 5;
char vc = (_x > target_x) ? 'U' : 'D';
string vstr(abs(_x - target_x), vc);
char hc = (_y > target_y) ? 'L' : 'R';
string hstr(abs(_y - target_y), hc);
if(target_x == 6){
_msg.append(hstr);
_msg.append(vstr);
}
else{
_msg.append(vstr);
_msg.append(hstr);
}
_msg.push_back('!');
_x = target_x;
_y = target_y;
}
private:
int _x;
int _y;
string _msg;
string _movie;
};
int main(int argc, char* argv[])
{
cout << "up" << endl;
SelectMovie sm1("up");
sm1.PrintMsg();
cout << "yzy" << endl;
SelectMovie sm2("yzy");
sm2.PrintMsg();
return 0;
}
Output
up
DDDD!U!
yzy
DDDDRRRR!DLLLL!URRRR!
Press any key to continue . . .