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

问题描述:

函数应该从用户传递的范围中写入数组不可重复的随机数。我试过发现错误,并且我意识到它必须是第二个循环的东西(计数器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; 
} 
+5

“我试图找到错误”是非常,非常从一个“明确的问题陈述”为止。 –

+0

生成少量非重复随机数的一种简单方法是用数字序列填充数组,然后使用随机数对来交换数组元素多次。 –

+0

解决这个问题的另一种方法是生成所有数字,然后使用Fisher-Yates对数字进行洗牌http://*.com/questions/22850316/how-to-shuffle-elements-in-a-vector-randomly –

如果你想不重复的在一定范围内的随机数,你能做到这一点,像这样:

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

UPDATE

对不起,我想读您的文章。这是我的原始答案。如果你想在一定范围内独特随机数,你能做到这一点,像这样:

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