fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <utility>
  4. #include <cctype>
  5. using namespace std;
  6.  
  7. constexpr int brdsze = 8; //Size of board
  8.  
  9. //Validate input and convert to co-ordinates
  10. //Returns true if OK and false if problem
  11. bool inpval(const string& inp, pair<int, int>& coord)
  12. {
  13. return (inp.size() == 2) && ((coord.first = toupper(inp[0]) - 'A') >= 0) && (coord.first < brdsze) && ((coord.second = inp[1] - '1') >= 0) && (coord.second < brdsze);
  14. }
  15.  
  16. int main()
  17. {
  18. //Offsets for knights possible moves - determines order of display
  19. constexpr int kgtpos = 8;
  20. constexpr pair<int, int> kgtmov[kgtpos] = { {-2, -1}, {-2, 1}, {-1, -2}, {-1, 2}, {1, -2}, {1, 2}, {2, -1}, {2, 1} };
  21.  
  22. string inp;
  23. pair<int, int> pos;
  24.  
  25. //Get and validate starting position
  26. do {
  27. cout << "Enter starting position: ";
  28. getline(cin, inp);
  29. } while (!inpval(inp, pos) && (cout << "\nInvalid starting position.\nInput format is CR where\nC is A to " << (char)('A' + brdsze - 1) << "\nR is 1 to " << brdsze << endl));
  30.  
  31. //Find last valid position
  32. int last = kgtpos - 1;
  33.  
  34. for (int got = false, rw, cl; !got; --last)
  35. got = ((cl = pos.first + kgtmov[last].first) >= 0) && (cl < brdsze) && ((rw = pos.second + kgtmov[last].second) >= 0) && (rw < brdsze);
  36.  
  37. cout << "\nAvailable positions from " << inp << " are" << endl;
  38.  
  39. //Find positions from first up to found last position and output in required format
  40. for (int pst = 0, first = 0, lst = last + 1, rw, cl; pst <= lst; ++pst)
  41. if (((cl = pos.first + kgtmov[pst].first) >= 0) && (cl < brdsze) && ((rw = pos.second + kgtmov[pst].second) >= 0) && (rw < brdsze))
  42. cout << (first++ ? ((pst == lst) ? ", and " : ", ") : "") << char(cl + 'A') << rw + 1;
  43.  
  44. cout << endl;
  45. }
  46.  
Success #stdin #stdout 0s 15240KB
stdin
g1
stdout
Enter starting position: 
Available positions from g1 are
E2, F3, and H3