如何使用范围中的随机值填充数组?(重复没问题.)

cod*_*lop 1 c++ arrays random

我是C++的新手,我有一个数组操作的问题.我有一个长度为100的X数组,我需要随机填充整数值为1到10(1,2,3,4,5,6,7,8,9,10)的X值.我知道会有重复,也许就像打印十次一样,但这真的是我想要的.

这是我有的:

一个X数组:

int X[100];
Run Code Online (Sandbox Code Playgroud)

这是我的代码片段:

int* X = NULL;
int* val = NULL;
int length1= 100;
int length2= 10;
X = new int[length1];
val = new int[length2];
int i;
int j;

for (i = 0; i < isi; i++) {
    val[i] = i;
    for (j = 0; j < length1; j++) {
        if (j > i) {
            X[j] = val[i];
        } else {
            X[j] = val[0];
        }
        cout << "X[" << j << "] = " << X[j] << "\n";
        Sleep(1);
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码使得从索引0到99的数组X的值为0,然后索引0到99的值为1,因此另一个索引直到索引0到99的值为9.

这不是我想要的,我想要的是它(如果它不是随机的)索引0到9的值为0,那么10到19的值为1 ......直到索引90到99的值为9希望我的解释清楚.

我在stackoverflow中遇到了一个问题:如何使用仅包含1-1000的值来生成10000的数组?

但仍然无法解决我自己的问题.有人可以给我解决这个问题.

先感谢您

Dar*_*one 8

#include <stdlib.h>

int main(int argc, char **argv) {
  int r[100];
  for (int i = 0; i < 100; ++i) {
    r[i] = rand() % 10 + 1;
  }
}
Run Code Online (Sandbox Code Playgroud)

对于一些输出,你可以#include <iostream>std::cout << "r[" << i << "] = " << r[i] << "\n"每次分配后的循环中.

如果您希望每次为随机数生成器播种不同的序列#include <time.h>,那么srand(time(NULL))在您第一次调用之前rand.


w.b*_*w.b 7

你也可以使用generate功能:

#include <iostream>
#include <algorithm>
#include <random>

using namespace std;

int main()
{
    int arr[100];
    random_device rd;
    default_random_engine dre(rd());
    uniform_int_distribution<int> uid(0,9);

    generate(arr, arr + sizeof(arr) / sizeof(int), [&] () { return uid(dre); });

    for (int a : arr)
        cout << a << " "; 
}
Run Code Online (Sandbox Code Playgroud)


use*_*740 5

Here are two ways to solve this problem - since this is a learning experience, only pseudo code (and relevant links) are provided. Each "task" can be looked up and solved separately. Note that neither method uses a secondary array.

If the amount of each number in the final result does not need to be the same (eg. 2 might appear 17 times) then consider the following loop-and-assign-random approach. A standard C for-each loop is sufficient.

# for every index pick a random value in [0, 10) and assign it
for i in 0 to last array index:
    array[i] = random in range 0, 10
Run Code Online (Sandbox Code Playgroud)

If the amount of numbers need to be the same, then consider filling the array and then shuffling it. The modulus operator is very handy here. (This assumes the array length is a multiple of the group size.)

# fill up array as 0,1,2,3,4,5,6,7,8,9,0,1,2.. (will be 10 groups)
for i in 0 to last array index:
    array[i] = i % 10
# and randomly rearrange order
shuffle array
Run Code Online (Sandbox Code Playgroud)

对于shuffle,请参阅Fisher-Yates,它甚至展示了C 实现——有“更多C++”方式,但这是学习和练习循环的好技术。(Fisher-Yates 的一个很酷的特性是,一旦将项目交换到当前索引中,它就会位于最终交换位置 - 因此可以修改 shuffle 循环以进行 shuffle立即执行诸如显示值之类的操作。)

在这两种情况下都应该使用随机函数;否则数字不会是..随机的。