如何建立从阵列的随机数 [英] How to create a random number from array

查看:152
本文介绍了如何建立从阵列的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做一个C#代码。在我的编码,我需要生成数字的随机列表。通常情况下,如果我们创建一个随机的,我们需要选择号码的范围。然而,对于我来说,我需要从阵列中创建一个随机数。任何想法?我使用XAML和C#。

I'm doing a C# coding. 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#.

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 :每次我点击提交按钮,号码[] 的选择将一个随机数。我怎样才能确保不重复的次数。例如:第1点击,myNo = 67;第2点击,myNo = 50; 3点击,myNo = 88; 4点击,myNo = 32; 5点击,myNo = 13。谢谢!

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; 2nd click, myNo = 50; 3rd click, myNo = 88; 4th click, myNo = 32; 5th click, myNo = 13. Thanks!

推荐答案

您可以创建whihch将代表从数组索引的随机数。从随机指标访问数组元素,你会得到你的电话号码,因为阵列中的所有你的数字似乎是截然不同的。

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];



编辑:
(感谢的 @ Corak
你可以生成基于数组长度随机指标,这将使它的动态和工作任何数组的长度。

(Thanks to @Corak) You can generate random Index based on array length, that would make it dynamic and work for any array's length.

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



编辑2:(有关问题的额外的一部分)。

Edit 2: (For extra part of question).

您需要在保持一流水平的唯一索引号的列表。所以,你的代码将是这样的:

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. 


}

这篇关于如何建立从阵列的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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