-
-
Notifications
You must be signed in to change notification settings - Fork 456
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Sample #195
Merged
Merged
Sample #195
Changes from 2 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
3e9eac0
close #194: add Sample trait and rename sample -> sample_reservoir
vitiral 74df6c0
fixing comments
vitiral 4f78755
rename sample_reservoir -> sample_iter
vitiral dbb1059
clean up some warts
vitiral 6de365d
add distribution test
vitiral 15c1d86
make sample_iter return Result<Vec, Vec> and fix docs
vitiral 3a4015a
bump cargo version
vitiral 70ffaaa
clarify Err in sample_iter
vitiral 201ec34
clean up len docs
vitiral File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
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
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 |
---|---|---|
|
@@ -13,33 +13,33 @@ | |
use super::Rng; | ||
use std::collections::hash_map::HashMap; | ||
|
||
/// Randomly sample *up to* `amount` elements from a finite iterator. | ||
/// Randomly sample `amount` elements from a finite iterator. | ||
/// | ||
/// The values are non-repeating but the order of elements returned is *not* random. | ||
/// The following can be returned: | ||
/// - `Ok`: `Vec` of `amount` non-repeating randomly sampled elements. The order is not random. | ||
/// - `Err`: `Vec` of *less than* `amount` elements in sequential order. This is considered an | ||
/// error since exactly `amount` elements is typically expected. | ||
/// | ||
/// This implementation uses `O(len(iterable))` time and `O(amount)` memory. | ||
/// | ||
/// > If `len(iterable) <= amount` then the values will be in sequential order. In all other | ||
/// > cases the order of the elements is neither random nor guaranteed. | ||
/// | ||
/// # Example | ||
/// | ||
/// ```rust | ||
/// use rand::{thread_rng, seq}; | ||
/// | ||
/// let mut rng = thread_rng(); | ||
/// let sample = seq::sample_iter(&mut rng, 1..100, 5); | ||
/// let sample = seq::sample_iter(&mut rng, 1..100, 5).unwrap(); | ||
/// println!("{:?}", sample); | ||
/// ``` | ||
pub fn sample_iter<T, I, R>(rng: &mut R, iterable: I, amount: usize) -> Vec<T> | ||
pub fn sample_iter<T, I, R>(rng: &mut R, iterable: I, amount: usize) -> Result<Vec<T>, Vec<T>> | ||
where I: IntoIterator<Item=T>, | ||
R: Rng, | ||
{ | ||
let mut iter = iterable.into_iter(); | ||
let mut reservoir = Vec::with_capacity(amount); | ||
reservoir.extend(iter.by_ref().take(amount)); | ||
|
||
// continue unless the iterator was exhausted | ||
// Continue unless the iterator was exhausted | ||
// | ||
// note: this prevents iterators that "restart" from causing problems. | ||
// If the iterator stops once, then so do we. | ||
|
@@ -50,12 +50,13 @@ pub fn sample_iter<T, I, R>(rng: &mut R, iterable: I, amount: usize) -> Vec<T> | |
*spot = elem; | ||
} | ||
} | ||
Ok(reservoir) | ||
} else { | ||
// Don't hang onto extra memory. There is a corner case where | ||
// `amount <<< len(iterable)` that we want to avoid. | ||
// `amount` was much less than `len(iterable)`. | ||
reservoir.shrink_to_fit(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. So you're not going with your own advice in #194 to make this fallible? I'm not sure personally; this is an iterator so shrinking to available data is common behaviour. |
||
Err(reservoir) | ||
} | ||
reservoir | ||
} | ||
|
||
/// Randomly sample exactly `amount` values from `slice`. | ||
|
@@ -224,11 +225,13 @@ mod test { | |
|
||
let mut r = thread_rng(); | ||
let vals = (min_val..max_val).collect::<Vec<i32>>(); | ||
let small_sample = sample_iter(&mut r, vals.iter(), 5); | ||
let large_sample = sample_iter(&mut r, vals.iter(), vals.len() + 5); | ||
let small_sample = sample_iter(&mut r, vals.iter(), 5).unwrap(); | ||
let large_sample = sample_iter(&mut r, vals.iter(), vals.len() + 5).unwrap_err(); | ||
|
||
assert_eq!(small_sample.len(), 5); | ||
assert_eq!(large_sample.len(), vals.len()); | ||
// no randomization happens when amount >= len | ||
assert_eq!(large_sample, vals.iter().collect::<Vec<_>>()); | ||
|
||
assert!(small_sample.iter().all(|e| { | ||
**e >= min_val && **e <= max_val | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For the
Err
case I'd prefer more precise documentation: in case less thanamount
elements are available, aVec
of exactly the elements initerable
is returned. The order is not random.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
the order is actually guaranteed to be sequential. I've updated the doc, let me know if that is better.