通过Random.Next排序() [英] Sorting by Random.Next()

查看:280
本文介绍了通过Random.Next排序()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题的建议之一是排序列表中Random.Next()。

In this question one of the suggestions is to sort a list by Random.Next().

我认为(也许不正确地)他暗示这个

I assume (maybe incorrectly) he's suggesting this

    public static IEnumerable<T> RandomSort<T>(this IEnumerable<T> items)
    {
        Random r = new Random();
        var a = items.ToArray();
        Array.Sort(a, (t1, t2) => (r.Next()%2==0)?-1 : 1);
        return a;
    }

(是的,已经是一个Array.RandomShuffle功能,你显然会使用代替。那不是问题)

(Yes, there already is an Array.RandomShuffle function which you would obviously use instead. That's not the question)

编辑:海报已经明确答案。他建议使用排序依据条款,这显然是安全的

现在的问题是,在上述code(使用的Array.Sort())的安全运行?

The question is, is the above code (Using Array.Sort()) safe to run?

我的问题是,这将是突破整理predicates的一个基本规律:

My issue is that it will be breaking a fundamental law of sorting predicates:

如果(一个&所述;​​ b)和(二c为C),那么(一个c为C)

if (a < b) and (b < c) then (a < c)

它甚至没有保证,如果(A&LT; B),然后(A&LT; B),下一次你问

It's not even guaranteeing that if (a < b) then ( a < b) the next time you ask.

请问这会带您进入未定义行为的领土?

Would this would take you into "undefined behaviour" territory?

例如,它可能会崩溃或陷入死循环,这取决于数字的序列随机()返回?

For example, it could crash or fall into an infinite loop depending upon the sequence of numbers that Random() returns?

推荐答案

这是创建一个随机排列的列表的有用的工具。对于给定的排列是绝对真实的,如果 A 是前 B B 是前 C 然后 A 是前 C

This is a useful device for creating a random permutation of the list. For a given permutation it is absolutely true that if a is before b and b is before c then a is before c.

另一种方式想起来是这样的:如果你每次播种随机数生成器使用相同的种子,然后它总是会产生相同的顺序。所以,你能想到的随机数发生器产生的列表的(可能)不同的排序的每一个种子。

Another way to think of it is like this: if you seed a random number generator with the same seed each time then it will always produce the same ordering. So you can think of every seed of the random number generator as producing a (possibly) different ordering of the list.

它甚至没有保证,如果(A&LT; B),然后(A&LT; B),下一次你问

It's not even guaranteeing that if (a < b) then ( a < b) the next time you ask.

这很好。但是,如果我们使用相同的种子和present为的Array.Sort 种子随机数发生器作为样品code在相同的状态按照上面的说明时,会产生相同的顺序

That's fine. But as explained above if we seed the random number generator with the same seed and present it to Array.Sort as in your sample code in the same state, it will produce the same ordering.

这篇关于通过Random.Next排序()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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