shuffle a given array of elements 28fisher e2 80 93yates shuffle 29

Solutions on MaxInterview for shuffle a given array of elements 28fisher e2 80 93yates shuffle 29 by the best coders in the world

showing results for - "shuffle a given array of elements 28fisher e2 80 93yates shuffle 29"
Valentina
16 Jul 2019
1from random import randrange
2 
3 
4# Utility function to swap elements `A[i]` and `A[j]` in a list
5def swap(A, i, j):
6 
7    temp = A[i]
8    A[i] = A[j]
9    A[j] = temp
10 
11 
12# Function to shuffle a list `A`
13def shuffle(A):
14 
15    # read list from the lowest index to highest
16    for i in range(len(A) - 1):
17        # generate a random number `j` such that `i <= j < n`
18        j = randrange(i, len(A))
19 
20        # swap the current element with the randomly generated index
21        swap(A, i, j)