Skip to content

Instantly share code, notes, and snippets.

@jingz8804
Created May 31, 2015 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jingz8804/53955bbaf817a6c2e179 to your computer and use it in GitHub Desktop.
Save jingz8804/53955bbaf817a6c2e179 to your computer and use it in GitHub Desktop.
public Set<Integer> pickDistinctNumbers(int k, int[] numbers){
if(numbers == null || numbers.length == 0) return null;
int len = numebrs.length;
if(k <= 0 || k > len) return null; // ask about these situations. this is just an example
Set<Integer> result = new HashSet<Integer>(); // Sets.newHashSet() if you use Google Guava
int size = 0;
while(size < k){
int picked = (int) (Math.random() * len);
if(result.add(numbers[picked])) size++;
}
return result;
}
public Set<Integer> pickDistinctNumbers(int k, int[] numbers){
if(numbers == null || numbers.length == 0) return null;
int len = numebrs.length;
if(k <= 0 || k > len) return null; // ask about these situations. this is just an example
Set<Integer> result = new HashSet<Integer>(); // Sets.newHashSet() if you use Google Guava
int size = 0;
while(size < k){
int picked = (int) (Math.random() * len);
result.add(numbers[picked]);
size++;
numbers[picked] = numbers[len-1];
len--;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment