@@ -418,22 +418,44 @@ fn sorted_by() {
418418}
419419
420420qc:: quickcheck! {
421- fn k_smallest_range( n: u64 , m: u16 , k: u16 ) -> ( ) {
421+ fn k_smallest_range( n: i64 , m: u16 , k: u16 ) -> ( ) {
422422 // u16 is used to constrain k and m to 0..2¹⁶,
423423 // otherwise the test could use too much memory.
424- let ( k, m) = ( k as u64 , m as u64 ) ;
424+ let ( k, m) = ( k as usize , m as u64 ) ;
425425
426+ let mut v: Vec <_> = ( n..n. saturating_add( m as _) ) . collect( ) ;
426427 // Generate a random permutation of n..n+m
427- let i = {
428- let mut v: Vec <u64 > = ( n..n. saturating_add( m) ) . collect( ) ;
429- v. shuffle( & mut thread_rng( ) ) ;
430- v. into_iter( )
431- } ;
428+ v. shuffle( & mut thread_rng( ) ) ;
432429
433- // Check that taking the k smallest elements yields n..n+min(k, m)
430+ // Construct the right answers for the top and bottom elements
431+ let mut sorted = v. clone( ) ;
432+ sorted. sort( ) ;
433+ // how many elements are we checking
434+ let num_elements = min( k, m as _) ;
435+
436+ // Compute the top and bottom k in various combinations
437+ let smallest_by_smallest : Vec <_> = v. iter( ) . cloned( ) . k_smallest( k) . collect( ) ;
438+ let smallest_by_largest : Vec <_> = v. iter( ) . cloned( ) . k_largest_by_key( k, |x| -x) . collect( ) ;
439+
440+ let largest_by_smallest : Vec <_> = v. iter( ) . cloned( ) . k_smallest_by( k, |a, b| b. cmp( a) ) . collect( ) ;
441+ let largest_by_largest : Vec <_> = v. iter( ) . cloned( ) . k_largest_by( k, Ord :: cmp) . collect( ) ;
442+
443+ // Check the variations produce the same answers and that they're right
444+ assert_eq!(
445+ smallest_by_smallest,
446+ smallest_by_largest
447+ ) ;
448+ assert_eq!(
449+ largest_by_smallest,
450+ largest_by_largest
451+ ) ;
452+ assert_eq!(
453+ sorted[ ..num_elements] ,
454+ smallest_by_smallest[ ..] ,
455+ ) ;
434456 it:: assert_equal(
435- i . k_smallest ( k as usize ) ,
436- n..n . saturating_add ( min ( k , m ) )
457+ sorted [ sorted . len ( ) -num_elements.. ] . iter ( ) . rev ( ) ,
458+ largest_by_smallest [ .. ] . iter ( )
437459 ) ;
438460 }
439461}
0 commit comments