使用我的数组值生成随机数而不重复

时间:2013-01-13 15:10:30

标签: c# arrays shuffle

我是C#的新手,我正在使用数组创建应用程序。我有一个数组,其数字如下所示:

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

我需要做的是在不重复的情况下更改数组中这些数字的顺序,因为当我使用随机函数时,这会显示重复的数字。

我看到了这种方法,但不知道如何将其应用于数字:http://www.dotnetperls.com/shuffle

4 个答案:

答案 0 :(得分:5)

您可以使用以下LINQ链:

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提升到其索引的幂,然后将它们加在一起并将结果转换为整数。另请注意,我没有为您的Random实例提供有用的种子。您可能希望这样做,以产生伪随机结果。

您可能还想使用描述here的取幂方法,以避免必须转换为整数。

编辑:正如Rhumborl指出的那样,你可能只需要洗牌阵列。在那种情况下:

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

应该适合你。

答案 1 :(得分:1)

如果您使用C#,最好使用C#结构。

您可以使用此通用功能

using System;
using System.Collections.Generic;

public static class ListExtensions
{
    public static void Shuffle<T>(this IList<T> list)
    {
        var randomNumber = new Random(DateTime.Now.Millisecond);
        var n = list.Count;
        while (n > 1)
        {
            n--;
            var k = randomNumber.Next(n + 1);
            var value = list[k];
            list[k] = list[n];
            list[n] = value;
        }
    }
}

然后您的代码应如下所示:

List<int> list2 = new List<int>(){1, 3, 5, 7, 9};
Shuffle(list2);

答案 2 :(得分:0)

正如你所说的那样,你已经拥有了一个可以使用数字的数组。因此,我不打算向您展示如何使用唯一数字填充数组。

这是你洗牌的方式。

  1. 弄清楚如何生成介于0和数组长度之间的随机数。
  2. 写一个从length_of_the_array-1到0的循环。(将此索引用作idx1)
  3. 在循环内部执行以下操作:

    一个。使用步骤1中的方法生成0到idx1(含)之间的随机数。(让随机数为idx2。)
    湾在idx1和idx2中交换数组中的元素。

    通过这样做可以完成简单的交换:

      

    int tmp = array [idx1];
        array [idx1] = array [idx2];
         array [idx2] = tmp;

    循环结束,你留下一个洗牌阵列。

答案 3 :(得分:0)

我不太清楚你的意思是通过改变顺序而不重复。如果你只是想生成一个永远不会重复的随机数,你就可以做这样的事情

private Random rand = new Random();
private List<int> used = new List<int>;
protected int randomNonrepeating() {
   int i = rand.next();
   while(used.contains(i))
       i = rand.next();
   used.add(i);
   return i;
}

我的猜测是,这并不是你想要的。如果您只想在提供的链接上修改算法以使用整数数组而不是字符串。您只需要更改类型。像这样的东西

using System;

使用System.Collections.Generic; 使用System.Linq;

静态类RandomStringArrayTool {     static Random _random = new Random();

public static string[] RandomizeStrings(int[] arr)
{
List<KeyValuePair<int, int>> list = new List<KeyValuePair<int, int>>();
// Add all strings from array
// Add new random int each time
foreach (var s in arr)
{
    list.Add(new KeyValuePair<int, int>(_random.Next(), s));
}
// Sort the list by the random number
var sorted = from item in list
         orderby item.Key
         select item;
// Allocate new string array
int[] result = new string[arr.Length];
// Copy values to array
int index = 0;
foreach (KeyValuePair<int, int> pair in sorted)
{
    result[index] = pair.Value;
    index++;
}
// Return copied array
return result;
}

}

希望这有帮助。

相关问题