-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
implement reservoir sampling algorithm
- Loading branch information
Yingyi Zhang
committed
Sep 6, 2017
1 parent
78df0cb
commit f356305
Showing
1 changed file
with
24 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
/* Problem: | ||
* From an array or stream with N size (the N can be very large or stream can be endless), | ||
* choose k (k < N) elements randomly from array or stream. | ||
* Make sure each element is selected with same probability k/N | ||
* */ | ||
|
||
import java.util.*; | ||
public class ReservoirSampling{ | ||
public int[] sample(int[] nums, int k){ | ||
int[] res = new int[k]; | ||
for(int i = 0; i < k; ++i){ | ||
res[i] = nums[i]; | ||
} | ||
Random rand = new Random(); | ||
int index = 0; | ||
for(int i = k; i < nums.length; ++i){ | ||
index = rand.nextInt(i + 1); // [0, i+1) prob = k/(k + 1) * (k + 1)/(k + 2) * ... (N - 1)/N = k/N | ||
if(index < k){ | ||
res[index] = nums[i]; // swap the element | ||
} | ||
} | ||
return res; | ||
} | ||
} |