【发布时间】:2017-09-28 10:37:52
【问题描述】:
我编写了一个简单的算法,这样当用户输入一个 int N 时,它会创建一个 N×N 网格,其中在同一行或同一列中没有重复项。该算法有时适用于较小的数字,但通常会引发分段错误。错误发生在设置网格数组元素的行中的 noRowDuplicates 函数中。
我不确定为什么会发生这种情况,希望能提供任何帮助。提前致谢!
// Author: Eric Benjamin
// This problem was solved using recursion. fill() is the recursive function.
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
void fillOptions();
void fill(int arrayPosition);
int inputNum;
int gridSize;
int *grid;
int allOptionsSize = 0;
int *allOptions;
int main() {
cout << "Please enter a number!" << endl;
cin >> inputNum;
gridSize = inputNum * inputNum;
grid = new int[gridSize];
allOptions = new int[inputNum];
for (int i = 0; i < inputNum; i++) {
allOptions[i] = i + 1;
allOptionsSize++;
}
srand((unsigned)time(0));
fill(0);
delete[] grid;
delete[] allOptions;
return 0;
}
bool noColumnDuplicates(int arrPosition, int valueToCheck) {
for (int i = 1; i < inputNum; i++) {
if (arrPosition - (inputNum * i) >= 0) {
if (grid[arrPosition - (inputNum * i)] == valueToCheck) {
return false;
}
}
}
return true;
}
bool noRowDuplicates(int arrPosition, int valueToCheck) {
int rowPosition = arrPosition % inputNum; // 0 to num - 1
if (rowPosition > 0) {
for (int p = 1; p < rowPosition + 1; p++) {
if (grid[arrPosition - p] == valueToCheck) {
return false;
}
}
}
return true;
}
void fill(int arrayPosition) {
if (arrayPosition < gridSize) {
int randomPosition = rand() % allOptionsSize;
grid[arrayPosition] = allOptions[randomPosition];
if (noColumnDuplicates(arrayPosition, grid[arrayPosition])) {
if (noRowDuplicates(arrayPosition, grid[arrayPosition])) {
if (arrayPosition % inputNum == 0) {
cout << endl;
}
cout << grid[arrayPosition] << " ";
fill(arrayPosition + 1);
} else {
fill (arrayPosition);
}
} else {
fill(arrayPosition);
}
}
}
【问题讨论】:
-
提示:在 C++ 中停止使用 C 风格的数组,而改用
std::vector。 -
警告:使用
rand()is considered harmful,强烈建议您使用适当的random number generator facility in the Standard Library,它会产生实际随机值。您使用time(NULL)作为随机数种子意味着如果在同一秒内运行,这将产生相同的结果,并且在许多平台上rand()是barely random at all。 -
是时候学习如何调试代码了
-
去掉所有的全局变量。
-
不清楚
fill做了什么,你没有显示代码,但我敢打赌你的问题出在某个地方。