Last active
April 14, 2026 21:32
-
-
Save maksverver/e1fefb559da2133fdea3c5804683c725 to your computer and use it in GitHub Desktop.
Floyd's sampling algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import random | |
| def floyd(n, k): | |
| s = set() | |
| for j in range(n - k + 1, n + 1): | |
| i = random.randint(1, j) | |
| if i in s: | |
| s.add(j) | |
| else: | |
| s.add(i) | |
| return s | |
| def floyd2(n, k): | |
| # maintain a linked list starting with `p` and successors in `s` | |
| p = None | |
| s = {} | |
| for j in range(n - k + 1, n + 1): | |
| i = random.randint(1, j) | |
| if i in s: | |
| # i already chosen: insert j after i instead | |
| s[j] = s[i] | |
| s[i] = j | |
| else: | |
| # add i at the front of the list | |
| s[i] = p | |
| p = i | |
| # convert the result to a plain python list | |
| res = [] | |
| while p is not None: | |
| res.append(p) | |
| p = s[p] | |
| return res | |
| if __name__ == '__main__': | |
| # Some simple tests | |
| n = 15 | |
| k = 7 | |
| for seed in range(20): | |
| random.seed(seed) | |
| a = floyd(n, k) | |
| random.seed(seed) | |
| b = floyd2(n, k) | |
| print(a, b) | |
| assert a == set(b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment