繁体   English   中英

如何按升序或降序生成随机数

[英]How to generate random numbers in ascending or descending order

#include <cstdlib>
#include <iostream>
using namespace std;

int main()
{
    int n,c;

    cout<<"Enter number of items to be sorted: ";
    cin>>n;

    int data[n];

    cout<<"Unsorted Array: \n";
    for (int x=0;x<n;x++)
    {
        data[x]=rand();
        cout<<data[x]<<"\t";
    }
    cout<<endl;
}

此代码在这里生成没有特定顺序的随机数。 如何使此代码按升序或降序生成随机数。

我已经尝试在此论坛中搜索,但是发现的只是生成无序的随机数。

任何帮助将不胜感激。 先感谢您。

您不能:它们被称为随机是有原因的。 如果需要排序的随机数数组,则应先填充数组,然后再对其进行排序。 另外,如果您使用c ++ 11,我建议将std::array用于固定大小的数组。

std::vector<int> data;
for (int x=0;x<n;x++)
{
    data.push_back(rand());
}

std::sort(data.begin(), data.end());

我认为没有内置的解决方案。 根据所需的统计属性,您可以生成n个数字,然后对其进行排序,也可以将ne随机数添加到前一个数字。

B ++ rand在c ++ 11中或多或少不推荐使用。 您应该改为使用随机标头中的工具。

int main() {
    //init generator with number from true random device
    mt19937 gen(random_device{}());
    //define desired distribution equal to what you would get with rand()
    uniform_int_distribution<> dist(0, RAND_MAX);

    int n;
    cout << "Enter number of items to be sorted: ";
    cin >> n;

    //generate numbers
    vector<int> data;
    for (int x = 0; x < n; x++) {
        data.push_back(dist(gen));
    }
    //sort numbers
    sort(begin(data), end(data));

    //print numbers
    for (auto& e : data) {
        cout << e << "\t";
    }
    cout << endl;
}

您可以使用:

sum=0;
for(i=1;i<=n;++i)
{ 
   sum+=random(100);
   arr[i]=sum;
}

这是在Java上不进行排序的一种方法,假设您想要所有正整数(显然可以调整数组长度):

public static void main(String[] args) {

    Random rndm = new Random();
    int arrayLength = 10;
    int randOutput;
    int checkAscend;
    //determining array size
    int[] array = new int[arrayLength];
    //populating array with random ascending integers
    for(int i = 0;i < arrayLength;i++) {
        if(i == 0) {
            checkAscend = 0;
        }
        else {
            checkAscend = array[i - 1];
        }
        randOutput = rndm.nextInt();
        if(randOutput > checkAscend) {
            array[i] = randOutput;
        }
        else {
            i--;
            continue;
        }
    }
    System.out.println(Arrays.toString(array));
}

暂无
暂无

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

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