功能将带有范围的随机数保存到数组而不重复

时间:2017-03-27 11:18:00

标签: c++ visual-studio

我遇到一个函数问题,该函数应该从用户传递的范围写入数组不可重复的随机数。我尝试发现错误,我意识到它必须是第二个循环(计数器j),我知道它是无限循环但我不知道为什么。我知道这是一个简单的练习,但我真的不知道。谢谢大家的帮助。

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <time.h>

using namespace std;

int main()
{
    srand(time(NULL));

    int n, from, to, range, random, term;
    int arr[100];
    cout << "Count of numbers" << endl;
    cin >> n; cout << endl;
    cout << "Down range" << endl;
    cin >> from; cout << endl;
    cout << "Up range" << endl;
    cin >> to; cout << endl;

    range = to - from;

    for (int i = 0; i < n; i++) {
        random = (rand() % range) + from;
        term = 1;
        //Check if repeat
        for (int j = 0; j < i; j++) {
            if (arr[j] == random) {
                term = 0;
            }
        }
        //Write in to the array
        if (term == 1) {
            arr[i] = random;
        }
        else {
            i = i - 1;
        }
    }
    for (int f = 0; f < n; f++) {
        cout << arr[f] << endl;
    }
    return 0;
}

1 个答案:

答案 0 :(得分:0)

如果您想在某个范围内使用非重复随机数,您可以这样做:

#include <random>
#include <iostream>
#include <set>

int main()
{
    int n, from, to; //, range, random, term; // The last three are not used

    cout << "Count of numbers" << endl;
    cin >> n; cout << endl;
    cout << "Down range" << endl;
    cin >> from; cout << endl;
    cout << "Up range" << endl;
    cin >> to; cout << endl;

    std::random_device rd; // Random seed
    std::mt19937 gen(rd()); // Create a random number geenrator, and seed it
    std::uniform_int_distribution<> dis(from, to); // Define the range

    std::vector<int> ints(1, dis(gen));

    while (ints.size() < n)
    {
        int t = dis(gen);
        if (t != ints.back())
            ints.push_back(t);
    }
}

<强>更新

抱歉,我想念您的帖子。这是我原来的答案。如果您想在某个范围内使用唯一随机数,您可以这样做:

#include <random>
#include <iostream>
#include <set>

int main()
{
    int n, from, to; //, range, random, term; // The last three are not used

    cout << "Count of numbers" << endl;
    cin >> n; cout << endl;
    cout << "Down range" << endl;
    cin >> from; cout << endl;
    cout << "Up range" << endl;
    cin >> to; cout << endl;

    std::random_device rd; // Random seed
    std::mt19937 gen(rd()); // Create a random number geenrator, and seed it
    std::uniform_int_distribution<> dis(from, to); // Define the range

    std::set<int> ints;

    while (ints.size() < n)
    {
        ints.insert(dis(gen));
    }
}