随机数生成器中的异常 [英] Exceptions in random number generator

查看:171
本文介绍了随机数生成器中的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,
如果我想为更多变量生成随机数,但是其中一些变量会生成值(除了保存在其他变量中的值),该怎么办?可能很难理解我想要的:D,所以我将向您展示一些代码(这是错误的,但它可以更好地解释我的意思).

Hello,
What to do if I want to generate random numbers to more variables but some of them will have generated value except value which is saved in some other variables? It may be hard to understand what I want :D so I will show you some code (which is wrong but it can explain better what I mean).

int variable_1 = rand.Next(1,14)
int variable_2 = rand.Next(1,14.Except(variable_1)) //So what I want is to save value to variable_2 which minimum is 1 and maximum is 14 but the value of variable_2 can''t be equal to value in variable_1



解决方案将适用于更多的变量将是最好的:).你能帮我么?我试图自己考虑一些算法,并尝试了google和MSDN,但没有任何帮助.感谢您提供任何帮助!



The sollution which will work for even more variables would be best :). Can you please help me? I tried to think about some algorithms myself and tried google and MSDN and nothing helped me. Thanks for any kind of help!

推荐答案

我不知道是否有直接的方法可以立即执行此操作,但是您可以生成循环内的第二个随机数,当它与上一个不同时会中断.

我的意思是(以您的代码为例):

I don''t know if there is a direct way to do that at once, but you could do the generation of the second random number inside a loop that breaks when it is different of the previous one.

I mean something like (getting your code as example):

int variable_1;
int variable_2;
variable_1 = rand.Next(1,14)
do
{
   variable_2 = rand.Next(1,14)
} while (variable_2 == variable_1) // If the first try gets the same value it repeats until it generate one that is not equal



但是,只有在接受新变量之前要检查的变量数量不多,这样的解决方案才可以考虑在内,因此条件不会变得太多.使用递归功能检查先前的内容并在不匹配时调用自己,这是另一种可能性.

问题在于:要创建的变量数量越多,找到下一个变量的正确值的时间就越大.

您在说多少个变量?以及随机数的范围?所有变量都必须具有唯一"值吗?
如果变量很多且所有变量都必须具有唯一值,则可以做另一件事,例如创建一个数组来保存从1到range_limit的值,对它们进行随机排序并从那里获取它们.



But this solution can only be taken into consideration if the number of variables to check before accepting the new one is not big, so the conditions don''t get too much. Using a recursive function that checks the previous ones and recalls itself if not matching would be another possibility.

Problem with that is: the bigger the number of variables you want to create, the bigger time it gets to find a correct value for the next.

how many variables are you speaking about? And the range for the random numbers? Must all variables have "unique" value?
If there are many variables and all of them must have a unique value you could do another thing, like creating an array to hold the values from 1 to range_limit, sorting them randomally and getting them from there.


这篇关于随机数生成器中的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆