fork download
  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4.  
  5. // range : [min, max]
  6. int random(int min, int max) {
  7. static bool first = true;
  8. if (first) {
  9. srand(time(NULL)); //seeding for the first time only!
  10. first = false;
  11. }
  12. return min + rand() % (max - min + 1);
  13. }
  14.  
  15. std::pair<int,int> rand_heading_point(int start_x, int start_y, int max_x, int max_y, int heading_dir) {
  16. int turn_x = 0;
  17. int turn_y = 0;
  18.  
  19. // if heading_dir == 0 --> object moves horicontally towards max_x, increment x
  20. // if heading_dir == 90 --> object moves vertically towards max_y, increment y
  21. if (heading_dir <= 90) {
  22. turn_x = random(start_x, max_x);
  23. turn_y = random(start_y, max_y);
  24. } else if (heading_dir <= 180) {
  25. turn_x = random(0, start_x);
  26. turn_y = random(start_y, max_y);
  27. } else if (heading_dir <= 270) {
  28. turn_x = random(0, max_y);
  29. turn_y = random(0, start_y);
  30. } else {
  31. turn_x = random(start_x, max_x);
  32. turn_y = random(0, start_y);
  33. }
  34.  
  35. return std::make_pair(turn_x, turn_y);
  36. }
  37.  
  38. void change_heading_dir(int curr_x, int curr_y, int turn_x, int turn_y, int &heading_dir) {
  39. if (curr_x == turn_x || curr_y == turn_y) {
  40. heading_dir *= 2;
  41. }
  42. }
  43.  
  44. // edit: use floats
  45. void move(int &curr_x, int &curr_y, int heading_dir) {
  46. int heading_rad = heading_dir * (M_PI / 180);
  47. int inc_len = 1;
  48. int x_inc = Math.cos(heading_rad) * inc_len;
  49. int y_inc = Math.sin(heading_rad) * inc_len;
  50.  
  51. curr_x += x_inc;
  52. curr_y += y_inc;
  53. }
  54.  
  55. int main() {
  56. // your code goes here
  57.  
  58. int start_x = 100;
  59. int start_y = 100;
  60. int width = 500;
  61. int height = 500;
  62. int dir = 0;
  63.  
  64. auto heading_point = rand_heading_point(start_x, start_y, width, height, dir);
  65.  
  66. cout << "x: " << heading_point.first << ", y: " << heading_point.second << endl;
  67.  
  68. return 0;
  69. }
Success #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
x: 306, y: 345