所以我试图创建一个大小为N = 6的随机整数的方阵。例如,对于N = 4,可能的矩阵将是:
1 4 9 3
6 3 9 3
4 5 1 2
0 1 3 4
然后我会将数字排序并存储到填充每一行的矩阵中:
0 1 1 1
2 3 3 3
3 4 4 4
5 6 9 9
我已经编写了一些代码,但在生成随机数时仍然会收到少量错误。任何帮助将不胜感激。
#include <iostream>
#include <iomanip>
#include <ctime>
#include <cassert>
using namespace std;
const size_t N = 6;
const int MIN_VAL = 10;
const int MAX_VAL = 99;
unsigned random(double rangeMin, double rangeMax);
void print2d(int **, size_t, size_t);
void selectionSort2d(int **, size_t, size_t);
void selectionSort2d(int **a, size_t rows, size_t cols) {
size_t minX, minY, x = 0, y = 0, i, k;
int t;
while (x < rows) {
minX = x; minY = y;
i = x; if ((k = (y+1) % cols) == 0) ++i;
while (i < rows) {
while (k < cols) {
if (a[i][k] < a[minX][minY]) {
minX = i; minY = k;
}
++k;
}
++i; k = 0;
}
t = a[minX][minY];
a[minX][minY] = a[x][y];
a[x][y] = t;
if ((y = (y + 1) % cols) == 0) ++x;
}
}
void print2d(int **a, size_t rows, size_t cols) {
cout << endl;
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
cout << setw(3) << a[i][j];
}
cout << endl;
}
cout << endl;
}
unsigned random(double rangeMin, double rangeMax) {
double maxN;
assert(rangeMin <= rangeMax);
maxN = rangeMax - rangeMin + 1;
return (unsigned)(((rand() / (double)RAND_MAX) * maxN) + rangeMin);
}
int main(int argc, char *argv[]) {
int **intArray;
time_t t;
// Allocate
intArray = new int*[N];
for (size_t i = 0; i < N; i++) {
intArray[i] = new int[N];
}
// Randomize
srand((unsigned)time(&t));
for (size_t i = 0; i < N; i++) {
for (size_t j = 0; j < N; j++) {
intArray[i][j] = random(MIN_VAL, MAX_VAL);
}
}
// Display
cout << endl << "Random:";
print2d(intArray, N, N);
// Sort
selectionSort2d(intArray, N, N);
// Display
cout << "Sorted:";
print2d(intArray, N, N);
// Free
for (size_t i = 0; i < N; i++) {
delete [] intArray[i];
}
delete [] intArray;
return 0;
}
答案 0 :(得分:0)
您可能需要
#include <cstdlib>