获取数组中的随机不同数字 [英] get random defferent numbers in an array

查看:69
本文介绍了获取数组中的随机不同数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我想获取0-8范围内的随机数(例如)
没有重复的号码.
我不知道代码应该如何,但是如果数字在
中分开 一个数组,对我来说,获得对代码的控制会容易得多.
所以我想要的是:
例如:
范围[0-4]
结果:
没有重复数字a [3,2,1,0,4]的数组

在此先谢谢您.

解决方案

您可以使用以下代码

int t = rand.Next(10);

上面的代码将给出0到10之间的随机值.
使用for循环可以存储值.同样,您可以检查先前存储的数组的唯一性.

请参见下面的示例

 公共 静态  int  [] GenerateRandomNumbers()
        {
            // 初始化整数变量
             int  num =  0 ;
            // 初始化int临时数组
             int  [] tempArr =   int  [  1001 ];
            // 初始化一个int数组
             int  [] randomNum =   int  [  1001 ];
            // 初始化随机数字变量
            随机rnd =  Random();


            // 遍历以将随机数存储到数组
             for ( int  i =  0 ; i <  =  1000 ; i ++)
            {

                num = rnd.Next( 1  1000 );
                tempArr [i] = num;

                // 仅在数字尚未输入时才插入
                // 生成的vlaue 
                 for ( int  j =  0 ; j <  i; j ++)
                {
                    如果(tempArr [j]!= num)
                    {
                        randomNum [i] = num;
                    }
                }
                // 数组中的输出元素
                Console.WriteLine(num);
            }

            返回 randomNum;
        } 


两个选择:

1)依次初始化数组:[0,1,2,3,4],然后按以下顺序对数组进行混洗:

for (int i = 0; i < MAX; i++)
    array[i] = i;

for (int i = 0; i < MAX; i++) {
    int tmp = array[i];
    int r = arc4random() % MAX;
    array[i] = array[r];
    array[r] = tmp;
}



如果发现需要,可以将其随机播放几次.

2)或随机初始化数组,但请确保不要重复数字.

有几种不同的方法可以做到这一点,但是最明显的就是保留一组布尔值以指示是否已经使用过一个数字,并保持随机调用,直到得到尚未使用的答案为止.然后将该数字放入数组中,并将其标记为在布尔数组中使用.

for (int i = 0; i < MAX; i++) 
   used[i] = false;

for (int i = 0; i < MAX; i++) {

   int r = arc4random() % MAX;
   while (used[r])
      r = arc4random() % MAX;

    array[i] = r;
    used[r] = true;

}



在第二种方法上,执行时间要长得多,因为在选择尚未选择的数字之前,必须一直调用随机数(但是如果数组很小,它将在相当短的时间内终止). /blockquote>

使用类System.Random,请参见 http://msdn.microsoft.com/en-us/library/system.random.aspx [ ^ ].

记住:不要犯一个常见的致命错误:每个应用程序运行时(每个Application Domain)仅获取一次类实例.将方法System.Random.Next与参数9一起使用.
强制唯一性的可能方法之一:
创建词典System.Collections.Generic.Dictionary<System.Int32, System.Int32> dictionary;的实例时,仅当在dictionary中尚未找到新生成的随机整数值时才使用它,在这种情况下,请将其添加到dictionary中.当字典实例的Count达到9的值时,您就完成了.您已在dictionary.Keys中进行排列.

如果您需要一个数组,则将Keys复制到某个数组中:

  int  []结果=   0 );
返回结果; 



—SA


Hello,

I want to get random numbers from the range 0-8 (for example)
without getting duplicated numbers .
I don''t know how is the code has to be but If the numbers are separated in
an array it would be a lot easier for me to gain control over the code.
so what I want is:
example:
range[0-4]
the result:
an array with no duplicated numbers a[3,2,1,0,4]

Thanks in advance.

解决方案

You can use the following code

int t = rand.Next(10);

The above code will give the random values between 0 and 10.
Using for loop you can store the value. Similarly you can check the previously stored arrays for uniqueness.

See below example

public static int[] GenerateRandomNumbers()
        {
            //Initialize an integer variable
            int num = 0;
            //Initialize an int temp Array
            int[] tempArr = new int[1001];
            //Initialize an int array
            int[] randomNum = new int[1001];
            //Initialize random Number variable
            Random rnd = new Random();


            //Loop through to store Random Numbers to Array
            for (int i = 0; i <= 1000; i++)
            {

                num = rnd.Next(1, 1000);
                tempArr[i] = num;

                //Insert only if the number is not already in the previouly
                //generated vlaue
                for (int j = 0; j < i; j++)
                {
                    if (tempArr[j] != num)
                    {
                        randomNum[i] = num;
                    }
                }
                //output elements in Array
                Console.WriteLine(num);
            }

            return randomNum;
        }


Two choices:

1) Initialize the array sequentially: [0,1,2,3,4], then shuffle the array by:

for (int i = 0; i < MAX; i++)
    array[i] = i;

for (int i = 0; i < MAX; i++) {
    int tmp = array[i];
    int r = arc4random() % MAX;
    array[i] = array[r];
    array[r] = tmp;
}



You can shuffle several times if you find it''s needed.

2) Or initialize the array randomly but make sure you don''t duplicate numbers.

There are several different ways to do that, but the most obvious is just keep an array of booleans to indicate whether a number has been used yet, and keep calling random until you get an answer that isn''t yet used. Then put that number in the array and mark it as used in your boolean array.

for (int i = 0; i < MAX; i++) 
   used[i] = false;

for (int i = 0; i < MAX; i++) {

   int r = arc4random() % MAX;
   while (used[r])
      r = arc4random() % MAX;

    array[i] = r;
    used[r] = true;

}



Execution time is a lot longer on this second method since you have to keep calling random until you choose the number you haven''t chosen yet (but if your array is small, it will terminate in a fairly short period of time).


Use the class System.Random, see http://msdn.microsoft.com/en-us/library/system.random.aspx[^].

Remember: don''t do a common fatal mistake: get the class instance only once per you application run time (per Application Domain). Use the method System.Random.Next with the parameter 9.

One of the possible methods to enforce uniqueness:
Create an instance of a dictionary System.Collections.Generic.Dictionary<System.Int32, System.Int32> dictionary; use a newly generated random integer value only if it is not already found in a dictionary, in this case add it to a dictionary. When the Count of dictionary instance reaches the value of 9, you''re done. You got your permutation in dictionary.Keys.

If you need an array, copy Keys in some array:

int[] result = new int[dictionary.Keys.Count];
dictionary.Keys.CopyTo(result, 0);
return result;



—SA


这篇关于获取数组中的随机不同数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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