October 2025
Intermediate to advanced
485 pages
13h 2m
English
You may be wondering why we need a special algorithm for shuffling. What’s wrong with, say, the following alternative approach that I’ve invented off the top of my head? Here’s my proposed algorithm:
Similar to the Fisher-Yates Shuffle, let’s point to each of the array’s values and swap them with other values. However, we won’t constrain ourselves and only choose a value to the right of the pointer. Rather, we can swap each value with any other value—even those to the left of the pointer.
Here would be the code for this approach, which I’ll call “naïve shuffling”:
| | import random |
| | |
| | |
| | def naive_shuffle(array): |
| | for i in range(0, len(array) - 1): |
| | j = random.randint(0, len(array) - 1) |
| | array[i], array[j] ... |
Read now
Unlock full access