简体   繁体   English

我的代码有什么问题(需要帮助修复)

[英]What's wrong with my code (Need help fixing)

So I'm trying to create a square matrix of random integer numbers of size N=6. 所以我正在尝试创建一个随机整数的方阵,大小为N = 6。 For example, for N=4 a possible matrix would be: 例如,对于N = 4,可能的矩阵为:

1 4 9 3
6 3 9 3
4 5 1 2
0 1 3 4

Then I would sort and store back the numbers into the matrix filling each row: 然后,我将这些数字排序并存储回填充每一行的矩阵中:

0 1 1 1
2 3 3 3
3 4 4 4
5 6 9 9

I've written some code, but still getting a small amount of errors regarding generating the random numbers. 我已经编写了一些代码,但是在生成随机数方面仍然出现少量错误。 Any help would be appreciated. 任何帮助,将不胜感激。

#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;
}

您可能需要

#include <cstdlib>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM