简体   繁体   English

如何从数组创建一个随机数

[英]How to create a random number from array

I'm doing a C# coding. 我在做C#编码。 In my coding, I need to generate a random list of numbers. 在我的编码中,我需要生成一个随机的数字列表。 Normally, if we create a random, we need to select the range of the number. 通常,如果我们创建一个随机数,我们需要选择数字的范围。 However for my case, I need to create a random number from an array. 但是对于我的情况,我需要从数组中创建一个随机数。 Any idea? 任何想法? I am using XAML and C#. 我正在使用XAML和C#。

private void Submit_Click(object sender, RoutedEventArgs e)
    {         
        int[] numbers = new int[5] {32, 67, 88, 13, 50};
        Random rd = new Random();
        //int myNo = rd.Next(numbers[])?                    
    }

EXTRA : Each time i click the submit button, a random number of numbers[] will selected. 额外 :每次单击提交按钮,将选择随机数字[] How can i make sure the number is not repeated. 我怎样才能确保不重复这个数字。 For example: 1st click, myNo = 67; 例如:第一次点击,myNo = 67; 2nd click, myNo = 50; 第二次点击,myNo = 50; 3rd click, myNo = 88; 第3次点击,myNo = 88; 4th click, myNo = 32; 第4次点击,myNo = 32; 5th click, myNo = 13. Thanks! 第5次点击,myNo = 13.谢谢!

You can create a random number whihch would represent the index from the array. 您可以创建一个随机数字,表示数组中的索引。 Access the array element from that random index and you will get your number, since all your numbers in the array seems to be distinct. 从该随机索引访问数组元素,您将得到您的数字,因为数组中的所有数字似乎都是不同的。

int[] numbers = new int[5] { 32, 67, 88, 13, 50 };
Random rd = new Random();
int randomIndex = rd.Next(0, 5);
int randomNumber = numbers[randomIndex];

EDIT: (Thanks to @Corak ) You can generate random Index based on array length, that would make it dynamic and work for any array's length. 编辑:(感谢@Corak )您可以根据数组长度生成随机索引,这将使其动态化并适用于任何数组的长度。

int randomIndex = rd.Next(0, numbers.Length);

Edit 2: (For extra part of question). 编辑2 :(对于问题的其他部分)。

You need to maintain a list of unique index numbers at class level. 您需要在类级别维护一个唯一索引号列表。 So your code would be something like: 所以你的代码将是这样的:

Random rd = new Random(); //At class level
List<int> uniqueIndices = new List<int>(); //At class level
private void Submit_Click(object sender, RoutedEventArgs e)
{         
    int[] numbers = new int[5] {32, 67, 88, 13, 50};
    int randomIndex = rd.Next(0, numbers.Length);
    while(list.Contains(randomIndex)) //check if the item exists in the list or not. 
    {
        randomIndex = rd.Next(0, numbers.Length);
    }
    list.Add(randomInex);
    //...rest of your code. 


}
Random r = new Random();
int index = r.Next(0, 5);

int randomNum = numbers[index];

This will give you random numbers between 0 and 4 which can be used to index your array and in turn pull random values from the array 这将为您提供0到4之间的随机数,可用于索引数组,然后从数组中提取随机值

Here is a parametric way: 这是一种参数化方式:

randIndex = rd.Next(0, numbers.Length);
int myNo = numbers[randIndex];

I would create a class that would represent an random enumerable and than use then extension methond First to generate the first index you should use in the array. 我会创建一个代表随机可枚举的类,然后使用扩展名methond First生成你应该在数组中使用的第一个索引。 It would look something like this: 它看起来像这样:

class Program
{
    static void Main(string[] args)
    {
        int[] numbers = new int[5] { 32, 67, 88, 13, 50 };
        var randomEnumerable = new RandomEnumerable(0, numbers.Length);
        int i = 0;
        while (i < numbers.Length)
        {
            var nextIndex = randomEnumerable.First();
            var number = numbers[nextIndex];
            Console.WriteLine(number);
            i++;
        }
        Console.ReadLine();
    }
}

class RandomEnumerable : IEnumerable<int>
{
    private readonly int _max;
    private readonly int _min;
    private Random _random;

    public RandomEnumerable(int min, int max)
    {
        _max = max;
        _min = min;
        _random = new Random();
    }

    public IEnumerator<int> GetEnumerator()
    {
        while (true)
        {
            yield return _random.Next(_min, _max);
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

只需像往常一样创建一个随机索引,并使用该值索引到数组中,而不是直接返回它。

You have to generate array index randomly to get a random number from your array. 您必须随机生成数组索引以从数组中获取随机数。

just apply the random function to generate numbers between the range of the array index( 0, array.length - 1) 只需应用随机函数生成数组索引范围之间的数字( 0, array.length - 1)

You could create a Random number and then use the mod operator % by 5 and use that as the index for your array. 您可以创建一个随机数,然后使用mod运算符%by 5并将其用作数组的索引。

Eg. 例如。 modRd = rd % 5; randomNumber = numbers[modRd];

This will create a random and unique number from array 这将从数组中创建一个随机且唯一的数字

 public class Shuffler
 {
    Random randomNumber;
    public Shuffler()
    {
        randomNumber = new Random();
    }

    /// <summary>
    /// Shuffling the elements of Array
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="array"></param>
    public void Shuffle<T>(IList<T> array)
    {
        for (int n = array.Count; n > 1; )
        {
            int k = randomNumber.Next(n); //returning random number less than the value of 'n'
            --n; //decrease radom number generation area by 1 
             //swap the last and selected values
            T temp = array[n];
            array[n] = array[k];
            array[k] = temp;
        }
    }
 }

You could create a string with all the values combined and then obtain the hashcode of it. 您可以创建一个包含所有值的字符串,然后获取它的哈希码。 This hashcode can then be used to seed the random. 然后可以使用该哈希码对随机种子进行种子处理。

Using the HashCode approach makes the seed more dependent on a data of you array. 使用HashCode方法使种子更依赖于数组的数据

    public static void Main()
    {
        int[] numbers = new int[5] { 32, 67, 88, 13, 50 };


        StringBuilder valuesToBeHashed = new StringBuilder();
        for (int i = 0; i < numbers.Length; i++)
        {
            valuesToBeHashed.Append(numbers[i] + ",");
        }

        Random rd = new Random(valuesToBeHashed.GetHashCode());
        Console.WriteLine("Hashcode of Array : {0} ",valuesToBeHashed.GetHashCode());
        Console.WriteLine("Random generated based on hashcode : {0}", rd.Next());
    }

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

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