我如何用其他值替换索引值

时间:2019-06-12 19:26:01

标签: c#

假设我有一个由6个int类型的元素组成的数组。

看起来像这样

var array = new int [] { 0, 1, 2, 3, 4, 5 };

我如何随机调整数组以确保每个索引都有一个新值。

// Bad
// The number at index 3 did not change and still has a value of 3
new int [] { 1, 0, 5, 3, 2, 4 } 

// Good:
// All the index have a new value
new int [] { 4, 2, 0, 5, 3, 1 } 

我尝试随机播放,但有时某些值的索引位置相同

1 个答案:

答案 0 :(得分:1)

您可以遍历数组,并始终与随机选择的索引交换,该索引大于当前索引。这样,数字就可以混洗,但是任何元素都不能混洗。

编辑:此方法可以正常工作,请尝试:

using System;

class Program {
    private static Random rnd = new Random();

    public static void Main() {

        for (var i = 0; i < 10000; i++) {
            int[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            Shuffle(array);
            Console.WriteLine(String.Join(", ", array));
        }
    }

    public static void Shuffle(int[] array) {
        for (var i = 0; i + 1 < array.Length; i++) {
            // generate j so that i < j < length
            int j = rnd.Next(i + 1, array.Length);

            // swap elements at i and j
            var tmp = array[j];
            array[j] = array[i];
            array[i] = tmp;

            // check
            if (array[i] == i) {
                throw new Exception(":(");
            }
        }
    }
}

它与Sattolo's algorithm非常相似,也可以使用。