📜  使用Fisher-Yates随机播放算法随机播放给定的数组

📅  最后修改于: 2021-04-24 19:33:08             🧑  作者: Mango

给定一个数组,编写一个程序以生成数组元素的随机排列。还问这个问题为“洗牌”或“给定阵列随机化”。在这里,随机播放意味着数组元素的每个排列都应该具有相同的可能性。

随机排列

让给定数组为arr [] 。一个简单的解决方案是创建一个辅助数组temp [] ,该数组最初是arr []的副本。从temp []中随机选择一个元素,将随机选择的元素复制到arr [0],然后从temp []中删除选择的元素。重复相同的过程n次,并将元素复制到arr [1],arr [2],…。该解决方案的时间复杂度将为O(n ^ 2)。
Fisher-Yates混洗算法的工作时间为O(n)。这里的假设是,给我们一个函数rand(),它在O(1)时间内生成随机数。
这个想法是从最后一个元素开始,将其与整个数组(包括最后一个)中随机选择的元素交换。现在考虑从0到n-2的数组(大小减小1),并重复该过程,直到我们找到第一个元素为止。
以下是详细的算法

To shuffle an array a of n elements (indices 0..n-1):
  for i from n - 1 downto 1 do
       j = random integer with 0 <= j <= i
       exchange a[j] and a[i]

以下是该算法的实现。

C++
// C++ Program to shuffle a given array
#include
#include 
#include 
using namespace std;
 
// A utility function to swap to integers
void swap (int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
 
// A utility function to print an array
void printArray (int arr[], int n)
{
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << "\n";
}
 
// A function to generate a random
// permutation of arr[]
void randomize (int arr[], int n)
{
    // Use a different seed value so that
    // we don't get same result each time
    // we run this program
    srand (time(NULL));
 
    // Start from the last element and swap
    // one by one. We don't need to run for
    // the first element that's why i > 0
    for (int i = n - 1; i > 0; i--)
    {
        // Pick a random index from 0 to i
        int j = rand() % (i + 1);
 
        // Swap arr[i] with the element
        // at random index
        swap(&arr[i], &arr[j]);
    }
}
 
// Driver Code
int main()
{
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
    int n = sizeof(arr) / sizeof(arr[0]);
    randomize (arr, n);
    printArray(arr, n);
 
    return 0;
}
 
// This code is contributed by
// rathbhupendra


C
// C Program to shuffle a given array
 
#include 
#include 
#include 
 
// A utility function to swap to integers
void swap (int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
 
// A utility function to print an array
void printArray (int arr[], int n)
{
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
}
 
// A function to generate a random permutation of arr[]
void randomize ( int arr[], int n )
{
    // Use a different seed value so that we don't get same
    // result each time we run this program
    srand ( time(NULL) );
 
    // Start from the last element and swap one by one. We don't
    // need to run for the first element that's why i > 0
    for (int i = n-1; i > 0; i--)
    {
        // Pick a random index from 0 to i
        int j = rand() % (i+1);
 
        // Swap arr[i] with the element at random index
        swap(&arr[i], &arr[j]);
    }
}
 
// Driver program to test above function.
int main()
{
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
    int n = sizeof(arr)/ sizeof(arr[0]);
    randomize (arr, n);
    printArray(arr, n);
 
    return 0;
}


Java
// Java Program to shuffle a given array
import java.util.Random;
import java.util.Arrays;
public class ShuffleRand
{
    // A Function to generate a random permutation of arr[]
    static void randomize( int arr[], int n)
    {
        // Creating a object for Random class
        Random r = new Random();
         
        // Start from the last element and swap one by one. We don't
        // need to run for the first element that's why i > 0
        for (int i = n-1; i > 0; i--) {
             
            // Pick a random index from 0 to i
            int j = r.nextInt(i+1);
             
            // Swap arr[i] with the element at random index
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
        // Prints the random array
        System.out.println(Arrays.toString(arr));
    }
     
    // Driver Program to test above function
    public static void main(String[] args)
    {
         
         int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
         int n = arr.length;
         randomize (arr, n);
    }
}
// This code is contributed by Sumit Ghosh


Python
# Python Program to shuffle a given array
import random
 
# A function to generate a random permutation of arr[]
def randomize (arr, n):
    # Start from the last element and swap one by one. We don't
    # need to run for the first element that's why i > 0
    for i in range(n-1,0,-1):
        # Pick a random index from 0 to i
        j = random.randint(0,i+1)
 
        # Swap arr[i] with the element at random index
        arr[i],arr[j] = arr[j],arr[i]
    return arr
 
# Driver program to test above function.
arr = [1, 2, 3, 4, 5, 6, 7, 8]
n = len(arr)
print(randomize(arr, n))
 
 
# This code is contributed by Pratik Chhajer


C#
// C# Code for Number of digits
// in the product of two numbers
using System;
 
class GFG
{
// A Function to generate a
// random permutation of arr[]
    static void randomize(int []arr, int n)
    {
        // Creating a object
        // for Random class
        Random r = new Random();
         
        // Start from the last element and
        // swap one by one. We don't need to
        // run for the first element
        // that's why i > 0
        for (int i = n - 1; i > 0; i--)
        {
             
            // Pick a random index
            // from 0 to i
            int j = r.Next(0, i+1);
             
            // Swap arr[i] with the
            // element at random index
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
        // Prints the random array
        for (int i = 0; i < n; i++)
        Console.Write(arr[i] + " ");
    }
     
     
// Driver Code
static void Main()
{
    int[] arr = {1, 2, 3, 4,
                 5, 6, 7, 8};
    int n = arr.Length;
    randomize (arr, n);
}
}
 
// This code is contributed by Sam007


PHP
 0
    for($i = $n - 1; $i >= 0; $i--)
    {
        // Pick a random index
        // from 0 to i
        $j = rand(0, $i+1);
 
        // Swap arr[i] with the
        // element at random index
        $tmp = $arr[$i];
        $arr[$i] = $arr[$j];
        $arr[$j] = $tmp;
    }
    for($i = 0; $i < $n; $i++)
    echo $arr[$i]." ";
}
 
// Driver Code
$arr = array(1, 2, 3, 4,
             5, 6, 7, 8);
$n = count($arr);
randomize($arr, $n);
 
// This code is contributed by mits
?>


Javascript


输出 :

7 8 4 6 3 1 2 5

上面的函数假定rand()生成一个随机数。
时间复杂度: O(n),假设函数rand()花费O(1)时间。
这是如何运作的?
第i个元素(包括最后一个元素)到达最后位置的概率为1 / n,因为我们在第一次迭代中随机选择了一个元素。
通过将i元素分为两种情况,可以证明ith元素到达倒数第二个位置的概率为1 / n。
情况1:i = n-1(最后一个元素的索引)
最后一个元素到达第二个最后位置的概率为=(最后一个元素未停留在其原始位置的概率)x(上一个步骤中再次选择索引以交换最后一个元素的概率)
所以概率=((n-1)/ n)x(1 /(n-1))= 1 / n
情况2:0
第i个元素移至第二位置的概率=(在先前的迭代中未选择ith元素的概率)x(在此迭代中选择了ith元素的概率)
所以概率=((n-1)/ n)x(1 /(n-1))= 1 / n
我们可以轻松地将上述证明推广到其他任何位置。