Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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