fischer yates shuffle Algorithm

The Fisher-Yates Shuffle Algorithm, also known as the Knuth Shuffle, is an algorithm for generating a random permutation of a finite sequence, essentially shuffling the elements in a given array or list. This efficient and unbiased algorithm was first introduced by Ronald A. Fisher and Frank Yates in 1938, and later popularized by the computer scientist Donald Knuth. The Fisher-Yates Shuffle Algorithm is widely used in various applications, such as in card games, computer simulations, and data science, where generating a random arrangement of elements is necessary. The Fisher-Yates Shuffle Algorithm works by iterating through the array from the last element to the first, and for each element, swapping it with a randomly chosen element that comes before it, including itself. The random choice is made using a uniformly distributed random number generator. In this way, each element has an equal probability of ending up in any position in the shuffled array. The algorithm has a time complexity of O(n), making it highly efficient for large datasets. Furthermore, it can be easily implemented in various programming languages, making it a popular choice for developers and researchers when a random permutation of elements is required.
#!/usr/bin/python
"""
The Fisher–Yates shuffle is an algorithm for generating a random permutation of a finite sequence.
For more details visit
wikipedia/Fischer-Yates-Shuffle.
"""
import random


def FYshuffle(list):
    for i in range(len(list)):
        a = random.randint(0, len(list) - 1)
        b = random.randint(0, len(list) - 1)
        list[a], list[b] = list[b], list[a]
    return list


if __name__ == "__main__":
    integers = [0, 1, 2, 3, 4, 5, 6, 7]
    strings = ["python", "says", "hello", "!"]
    print("Fisher-Yates Shuffle:")
    print("List", integers, strings)
    print("FY Shuffle", FYshuffle(integers), FYshuffle(strings))

LANGUAGE:

DARK MODE: