Created
August 6, 2014 04:01
-
-
Save zpconn/f2ec0e22e2ed8d00a78e to your computer and use it in GitHub Desktop.
Any finite list of integers has a maximum element. There may be multiple occurrences of this maximum. This finds uniformly and randomly the index of one of the occurrences of the maximum element with a single pass over the array using reservoir sampling.
This file contains 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 rand_max(arr): | |
curr_max = 0 | |
curr_max_idx = 0 | |
curr_max_count = 1 | |
for i,x in enumerate(arr): | |
if x > curr_max: | |
curr_max = x | |
curr_max_idx = i | |
curr_max_count = 1 | |
elif x == curr_max: | |
curr_max_count = curr_max_count + 1 | |
if random.random() < 1.0 / curr_max_count: | |
curr_max_idx = i | |
return curr_max_idx | |
print(rand_max([3,2,4,6,5,6,4,6,5,4,2,3,6,5,4,3,4,6])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment