本文介绍了生成随机数有没有重复我的数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的C#和我正在与阵列的应用程序。我有一个数字数组如下:

I'm new to C# and I'm making an application with arrays. I have an array with the numbers shown below:

int[] array2 = new int[] { 1, 3, 5, 7, 9 };

我需要做的是改变这些数字的顺序数组中没有重复的,因为当我使用随机函数,这说明我重复的数字。

What I need to do is change the order of these numbers in the array without repetitions, because when I use Random Function, this shows me repeated numbers.

我看到了这个方法,但不知道如何与数字应用它:

I saw this method, but do not know how to apply it with numbers: http://www.dotnetperls.com/shuffle

推荐答案

您可以使用下面的LINQ链:

You can use the following LINQ chain:

int[] array2 = new int[] { 1, 3, 5, 7, 9 };
var random = new Random();
var total = (int)array2.
    OrderBy(digit => random.Next()).
    Select((digit, index) => digit*Math.Pow(10, index)).
    Sum();

首先,它命令该元件中随机地,然后它选择乘以10上升到其索引的功率的每个元素,然后对其求和在一起并将结果转换为整数。另外,请注意,我没有为你的随机实例提供了一个有用的种子。你可能会想这样做,产生伪随机结果。

First, it orders the elements randomly, then it selects each element multiplied by 10 raised to the power of its index, then sums them together and casts the result to an integer. Also, please note that I didn't provide an useful seed for your Random instance. You might want to do that, to produce pseudo-random results.

您可能还需要在这里使用的方法描述幂,以避免强制转换为整数。

You might also want to use a method for exponentiation described here, to avoid having to cast to an integer.

编辑:Rhumborl指出的那样,你可能只需要洗牌数组。在这种情况下:

As Rhumborl pointed out, you may just need the shuffled array. In that case:

var shuffledArray = array2.OrderBy(n => random.Next()).
   ToArray();

应该为你工作。

这篇关于生成随机数有没有重复我的数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 18:58
查看更多