将范围随机数保存到数组而不重复的函数



我有一个函数的问题,该函数应该从用户传递的范围内写入数组中不可重复的随机数。我尝试发现错误,我意识到它一定是第二个循环(计数器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;
}

如果你想要某个范围内的非重复随机数,你可以这样做:

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

最新更新