3 ms·
I think that is pretty much the alternative approach dan spoke of at the end, but without saving the cycle in a data structure (worse for testing): > In practi
by davemp 9y ago
I think that is pretty much the alternative approach dan spoke of at the end, but without saving the cycle in a data structure (worse for testing):
> In practice, you probably don’t “need” to know how these algorithms work because the standard library for most modern languages will have some way of producing a random shuffle. And if you have a function that will give you a shuffle, you can produce a permutation with exactly one cycle.
```python
def cycle_frm_shuffle(shuffled, cycle, n):
for i in range(n - 1):
key = shuffled[i]
value = shuffled[i + 1]
cycle[key] = value
cycle[shuffled[n]] = shuffled[0]
```
This method has more memory and cpu overhead than sattolo's by O(n).
The proof is pretty simple:
Each assignment inside the loop is uniformly distributed, but the last assignment is determine strictly by the first n - 1. Giving us (n - 1)! permutations.