如何在C++中使矩阵中的圆运动?

edqdpe6u  于 2024-01-09  发布在  其他
关注(0)|答案(1)|浏览(148)

我有一个代码,其中数字1必须由行替换0,如下所示:


的数据
下面是它的代码:

  1. int field[y][x] =
  2. {
  3. {0, 0, 0},
  4. {0, 0, 0},
  5. {0, 0, 0}
  6. };
  7. int main()
  8. {
  9. showField(); //Show field
  10. cout << endl;
  11. again:
  12. for (int i = 0; i < y; i++)
  13. {
  14. for (int j = 0; j < x; j++)
  15. {
  16. if (j > 0)
  17. {
  18. field[i][j - 1] = 0;
  19. }
  20. field[i][j] = 1;
  21. countTimeSec(); //updates the board per second
  22. }
  23. if (i == 2)
  24. {
  25. field[i][y - 1] = 0;
  26. goto again;
  27. }
  28. else
  29. {
  30. field[i][y - 1] = 0;
  31. }
  32. }
  33. showField();
  34. return 0;
  35. }
  36. void countTimeSec()
  37. {
  38. int oneSec = 0;
  39. while (oneSec < 15)
  40. {
  41. showField();
  42. oneSec++;
  43. system("cls");
  44. }
  45. }

字符串
我想知道如何修改代码,使算法像这样:

如果会有任何逻辑如何使它,我也将赞赏,

yfwxisqw

yfwxisqw1#

首先,考虑如何旋转1D数组中的数字。当旋转图片中显示的矩阵时,基本上是旋转:

  1. input: [1, 0, 0, 0, 0, 0, 0, 0, 0]
  2. output: [0, 1, 0, 0, 0, 0, 0, 0, 0]

字符串
对于单元素旋转,方法为:
1.设x为最后一个元素
1.将所有元素右移一位
1.将第一个元素设置为x
在2D中,你做的是完全相同的事情,除了你必须将2D位置Map到1D位置:

  1. enum { x = 3, y = 3 };
  2. int matrix[y][x] = {
  3. {1, 2, 3},
  4. {8, 0, 4},
  5. {7, 6, 5}
  6. };
  7. int* at_circumference(int i) {
  8. // {a, a, b}
  9. // {d, -, b}
  10. // {d, c, c}
  11. if (i < x - 1) return &matrix[0][ i]; // a
  12. i -= x - 1;
  13. if (i < y - 1) return &matrix[i][x - 1]; // b
  14. i -= y - 1;
  15. if (i < x - 1) return &matrix[y - 1][x - i - 1]; // c
  16. i -= x - 1;
  17. if (i < y - 1) return &matrix[y - i - 1][0]; // d
  18. exit(1); // index out of bounds
  19. }


这样,旋转可以在1D中实现:

  1. const int circumference = (y - 1 + x - 1) * 2;
  2. void rotate(void) {
  3. int last = *at_circumference(circumference - 1);
  4. for (int i = circumference - 1; i > 0; --i) {
  5. *at_circumference(i) = *at_circumference(i - 1);
  6. }
  7. *at_circumference(0) = last;
  8. }


最后是驱动程序代码:

  1. void print_circumference(void) {
  2. for (int i = 0; i < circumference; ++i) {
  3. printf("%d ", *at_circumference(i));
  4. }
  5. puts("");
  6. }
  7. int main(void) {
  8. print_circumference();
  9. rotate();
  10. print_circumference();
  11. }


程序输出(https://godbolt.org/z/Ghr5bqbGc):

进一步说明

如果可能的话,避免向后-goto。在原始代码中,其形式为:

  1. again:
  2. for (/* ... */) {
  3. // ...
  4. if (/* ... */) goto again;
  5. }


.你本可以这样写:

  1. while (1) {
  2. for (/* ... */) {
  3. if (/* ... */) goto again;
  4. }
  5. break;
  6. again: continue;
  7. }


虽然这看起来可能更复杂,但while (1)循环可以立即清楚地表明重复正在进行,以及在什么范围内。
在这种情况下,您还可以通过创建一个

  1. bool is_continue = false;


.变量,您可以在for循环期间更新该变量,并在周围的while循环中进行检查。

展开查看全部

相关问题