C++ 如何用范围内的随机值填充数组?(重复是可以的。)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26051101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fill an array with random values from a range? (Duplicates are OK.)
提问by codelop
I am new to C++, I have a problem of array manipulation. I have an array of X with length 100, I need to fill the value of X with integer value of 1 to 10 (1,2,3,4,5,6,7,8,9,10) randomly. I know that there will be duplicate, maybe like 1 printed ten times, etc, but that's really what I want.
我是 C++ 新手,我有数组操作的问题。我有一个长度为 100 的 X 数组,我需要用整数值 1 到 10 (1,2,3,4,5,6,7,8,9,10) 随机填充 X 的值。我知道会有重复的,可能像 1 打印十次等等,但这确实是我想要的。
Here is what I have:
这是我所拥有的:
an array of X:
X 的数组:
int X[100];
Here is my code snippet:
这是我的代码片段:
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);
}
}
Code above makes the array X from index 0 to 99 has value of 0, then index 0 to 99 has value of 1 and so the other index until the index 0 to 99 has value of 9.
上面的代码使数组 X 从索引 0 到 99 的值为 0,然后索引 0 到 99 的值为 1,因此其他索引直到索引 0 到 99 的值为 9。
This is not what I want, what I want is to make it (if it is not random) index 0 to 9 has value of 0, then 10 to 19 has value of 1 ... until index 90 to 99 has value of 9. Hope my explanation clear.
这不是我想要的,我想要的是让它(如果它不是随机的)索引 0 到 9 的值为 0,然后 10 到 19 的值为 1 ...直到索引 90 到 99 的值为 9 . 希望我的解释清楚。
I have come to a question in stackoverflow: How would you make an array of 10000 with only values of 1-1000 inclusive?
我在 stackoverflow 中遇到了一个问题:你将如何制作一个 10000 的数组,其中只有 1-1000 的值?
But still can't resolve my problem my self. Can someone please give me solution to this.
但仍然无法解决我自己的问题。有人可以给我解决这个问题。
Thank you in advance
先感谢您
回答by Darren Stone
#include <stdlib.h>
int main(int argc, char **argv) {
int r[100];
for (int i = 0; i < 100; ++i) {
r[i] = rand() % 10 + 1;
}
}
For some output, you can #include <iostream>
and then std::cout << "r[" << i << "] = " << r[i] << "\n"
inside the loop after each assignment.
对于某些输出,您可以在每次分配后#include <iostream>
然后std::cout << "r[" << i << "] = " << r[i] << "\n"
在循环内。
If you want to seed the random number generator for a different sequence each time, then #include <time.h>
and then srand(time(NULL))
before your first call to rand
.
如果您想每次都为不同的序列设置随机数生成器的种子#include <time.h>
,那么srand(time(NULL))
在您第一次调用rand
.
回答by w.b
You can also use generate
function:
您还可以使用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 << " ";
}
回答by user2864740
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.
如果最终结果中每个数字的数量不需要相同(例如 2 可能出现 17 次),则考虑以下循环分配随机方法。标准的 C for-each 循环就足够了。
# 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
If the amount of numbers needto be the same, then consider filling the array and then shuffling it. The modulus operatoris 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
For the shuffle see Fisher-Yates, which even shows a C implementation - there are "more C++" ways, but this is a good technique to learn and practice with loops. (One cool property about Fisher-Yates is that as soon an item is swapped into the current index it is at the final swap location - thus the shuffle loop can be modified to shuffle andimmediately perform an action such as displaying the value.)
对于随机播放,请参阅Fisher-Yates,它甚至显示了 C 实现 - 有“更多 C++”方式,但这是学习和练习循环的好技术。(Fisher-Yates 的一个很酷的特性是,一旦将项目交换到当前索引中,它就会位于最终交换位置 - 因此可以修改 shuffle 循环以进行 shuffle并立即执行诸如显示值之类的操作。)
In both cases a randomfunctionshould be used; else the numbers will not be .. random.
在这两种情况下都应该使用随机函数;否则数字不会是..随机的。
回答by Cheers and hth. - Alf
To loop over the items of a collection the most natural C++ loop is the range based forloop.
要循环遍历集合的项目,最自然的 C++ 循环是基于范围的 for循环。
In order to assign something to each item, the formal item name should be a reference, thus:
为了给每个项目分配一些东西,正式的项目名称应该是一个参考,因此:
for( auto& item : X )
{
// E.g. assign to item here.
}
This serves up each item of the array, in order, to the code marked by a comment.
这将按顺序将数组的每个项目提供给由注释标记的代码。
There are two different random generators in C++, the old C library one, which is just a pair of functions, and the more general and modern but also not-so-easy-to-grok C++11 thingy. I suggest you google it and try out things. Ask new more specific question if/when stuck.
C++ 中有两种不同的随机生成器,一个是旧的 C 库,它只是一对函数,另一个是更通用和现代但也不太容易理解的 C++11 东西。我建议你谷歌它并尝试一下。如果/何时卡住,请提出新的更具体的问题。
回答by Arturo
I think others have pointed it out but you have to first write the pre-compiler directive #include <ctime>
and then use the srand function. Most would say don't use that but since you and I are at the basics our teachers, respectively, start us off with that. And it might work with your compiler as well.
Here is a link to learn more about it. I would have commented but I can't.
http://www.cplusplus.com/reference/cstdlib/srand/
我认为其他人已经指出了这一点,但您必须先编写预编译器指令#include <ctime>
,然后再使用 srand 函数。大多数人会说不要使用那个,但是因为你和我分别是我们的老师的基础知识,所以我们从那个开始。它也可能适用于您的编译器。这是一个链接以了解更多信息。我会评论,但我不能。
http://www.cplusplus.com/reference/cstdlib/srand/