首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何用其他索引值替换索引值

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

Stack Overflow用户
提问于 2019-06-13 03:26:02
回答 1查看 45关注 0票数 1

假设我有一个包含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 } 

我尝试过Shuffle,但有时有些值会有相同的索引位置

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-13 03:57:56

你可以迭代数组,并且总是交换一个随机选择的索引,这个索引比当前的索引大。这样,数字就会被打乱,但没有元素可以被打乱回来。

编辑:这确实有效,试一下:

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,它也可以工作。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56569122

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档