invariants - 如何找到从中心开始的方阵螺旋遍历的循环不变量
问题描述
我们知道不变量是表达式,在循环之前、每次迭代中和循环之后都是如此。所以我们应该找出下面的方阵螺旋遍历代码的所有不变量,从它的中心开始。
循环探索:
int iInd = N / 2;
int jInd = N / 2;
int iStep = 1;
int jStep = 1;
printf("%d ", A[iInd][jInd]);
for (int i = 0; i < N; i++) {
for (int h = 0; h < i; h++)
printf("%d ", A[iInd][jInd += jStep]);
for (int v = 0; v < i; v++)
printf("%d ", A[iInd += iStep][jInd]);
jStep = -jStep;
iStep = -iStep;
}
for (int h = 0; h < N - 1; h++)
printf("%d ", A[iInd][jInd += jStep]);
整个C++
程序:
#include <stdio.h>
#define N 13
void main() {
int A[N][N];
for (int i = 0; i<N; i++)
for (int j = 0; j<N; j++)
A[i][j] = i * 13 + j; //simple filling of matrix
int iInd = N / 2;
int jInd = N / 2;
int iStep = 1;
int jStep = 1;
printf("%d ", A[iInd][jInd]); //the starting of spiral printing
for (int i = 0; i < N; i++) {
for (int h = 0; h < i; h++)
printf("%d ", A[iInd][jInd += jStep]);
for (int v = 0; v < i; v++)
printf("%d ", A[iInd += iStep][jInd]);
jStep = -jStep;
iStep = -iStep;
}
for (int h = 0; h < N - 1; h++)
printf("%d ", A[iInd][jInd += jStep]);
//the ending of spiral printing
}
程序的输出和内部结构: 图片在这里
我向老师展示了我的想法 - 不变量是:
- 我 < N+1
- h < N
- v < N
老师告诉我,它不是不变量。它应该是表达式,包含iInd
和jInd
。
解决方案
推荐阅读
- java - Firebase 在本地存储 access_token
- java - 使用自定义适配器在 Android Studio 中设置图像源
- redis - ELK 堆栈配置
- android - Gridlayout中均匀定位的Cardviews
- javascript - 如何在反应中从履行的承诺中获得价值
- flutter - 从资产或文件中显示图片 Flutter
- swiftui - SwiftUI:没有奇怪的解决方法,@State 属性不会更新
- python - python Selenium --headless 参数触发网页端的安全特性
- android - 不确定 react-native start 命令是否正常工作
- django - Django:当令牌存储在 HttpOnly cookie 中时,如何更新 SimpleJWT 访问令牌?