|
| 1 | +#!/usr/bin/python |
| 2 | +# encoding=utf8 |
| 3 | +""" |
| 4 | +The Fisher–Yates shuffle is an algorithm for generating a random permutation of a finite sequence. |
| 5 | +Time complexity: O(n) |
| 6 | +
|
| 7 | +For more details visit |
| 8 | +https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle |
| 9 | +""" |
| 10 | + |
| 11 | +import random |
| 12 | + |
| 13 | + |
| 14 | +# The modern version of the Fisher–Yates shuffle, |
| 15 | +# designed for computer use, was introduced by Richard Durstenfeld in 1964 |
| 16 | +def fisher_yates_shuffle(sequence: []) -> []: |
| 17 | + for i in range(len(sequence) - 1, 0, -1): |
| 18 | + j = random.randint(0, i) |
| 19 | + sequence[i], sequence[j] = sequence[j], sequence[i] |
| 20 | + |
| 21 | + return sequence |
| 22 | + |
| 23 | + |
| 24 | +# was published in 1986 by Sandra Sattolo |
| 25 | +# for generating uniformly distributed cycles of (maximal) length n |
| 26 | +def sattoloCycle(sequence: []) -> []: |
| 27 | + for i in range(len(sequence) - 1, 0, -1): |
| 28 | + j = random.randint(0, i - 1) |
| 29 | + sequence[i], sequence[j] = sequence[j], sequence[i] |
| 30 | + |
| 31 | + return sequence |
| 32 | + |
| 33 | + |
| 34 | +if __name__ == "__main__": |
| 35 | + integers = [0, 1, 2, 3, 4, 5, 6, 7] |
| 36 | + strings = ["python", "says", "hello", "!"] |
| 37 | + print("Fisher-Yates Shuffle:") |
| 38 | + print("List", integers, strings) |
| 39 | + print("FY Shuffle", fisher_yates_shuffle(integers), fisher_yates_shuffle(strings)) |
| 40 | + print("Sattolo's algorithm", sattoloCycle(integers), sattoloCycle(strings)) |
0 commit comments