Best way to randomize an array with .NET

后端 未结 17 886
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 01:55

What is the best way to randomize an array of strings with .NET? My array contains about 500 strings and I\'d like to create a new Array with the same strings b

17条回答
  •  再見小時候
    2020-11-22 02:37

    You're looking for a shuffling algorithm, right?

    Okay, there are two ways to do this: the clever-but-people-always-seem-to-misunderstand-it-and-get-it-wrong-so-maybe-its-not-that-clever-after-all way, and the dumb-as-rocks-but-who-cares-because-it-works way.

    Dumb way

    • Create a duplicate of your first array, but tag each string should with a random number.
    • Sort the duplicate array with respect to the random number.

    This algorithm works well, but make sure that your random number generator is unlikely to tag two strings with the same number. Because of the so-called Birthday Paradox, this happens more often than you might expect. Its time complexity is O(n log n).

    Clever way

    I'll describe this as a recursive algorithm:

    To shuffle an array of size n (indices in the range [0..n-1]):

    if n = 0
    • do nothing
    if n > 0
    • (recursive step) shuffle the first n-1 elements of the array
    • choose a random index, x, in the range [0..n-1]
    • swap the element at index n-1 with the element at index x

    The iterative equivalent is to walk an iterator through the array, swapping with random elements as you go along, but notice that you cannot swap with an element after the one that the iterator points to. This is a very common mistake, and leads to a biased shuffle.

    Time complexity is O(n).

提交回复
热议问题