From f36b234e02b1a64ce0fca853bee7861594ab8b6a Mon Sep 17 00:00:00 2001 From: AlexanderKabui Date: Mon, 28 Nov 2022 02:46:25 +0300 Subject: add custom sorter function --- src/sorter.rs | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) (limited to 'src') diff --git a/src/sorter.rs b/src/sorter.rs index fd88e9c..1515b69 100644 --- a/src/sorter.rs +++ b/src/sorter.rs @@ -64,3 +64,60 @@ pub fn sort_write_to_file( pub fn create_large_file(filename: &str) { File::create(filename).unwrap(); } + +pub fn float_sorter(unsorted:& mut [f64]){ + // custom function to sort floats with nan and inf descending order + unsorted.sort_by(|&a, &b| { + match (a.is_nan()| a.is_infinite(), b.is_nan()|b.is_infinite()) { + (true, true) => Ordering::Equal, + (true, false) => Ordering::Greater, + (false, true) => Ordering::Less, + (false, false) => b.partial_cmp(&a).unwrap(), + } + }); +} + + +mod tests{ + + + //custom function to to be able to compare vec with floats + + fn eq_with_nan_eq(a: f64, b: f64) -> bool { + ((a.is_nan()| a.is_infinite()) && + (b.is_nan()| b.is_infinite())) || (a == b) + } + + fn vec_compare(va: &[f64], vb: &[f64]) -> bool { + (va.len() == vb.len()) && + va.iter() + .zip(vb) + .all(|(a,b)| eq_with_nan_eq(*a,*b)) + } + + #[test] + + fn test_float_sorter(){ + use super::float_sorter; + + + + let mut test_cases:[(Vec, Vec);6] = [( vec![f64::NAN,12.1,11.1,1.1],vec![12.1,11.1,1.1,f64::NAN]), + (vec![2.1,1.1,2.3,f64::NAN],vec![2.3,2.1,1.1,f64::NAN]), + (vec![f64::NAN,f64::NAN,9.1],vec![9.1,f64::NAN,f64::NAN]), + (vec![f64::INFINITY,1.12,f64::INFINITY,42.1],vec![42.1,1.12,f64::INFINITY,f64::INFINITY]), + (vec![1.1,1.4,1.5,12.1],vec![12.1,1.5,1.4,1.1]), + (vec![ f64::INFINITY,f64::INFINITY,2.13,5.3,f64::NAN,12.1,f64::INFINITY,5.6,f64::NAN,f64::NAN,8.32], + vec![12.1, 8.32, 5.6, 5.3, 2.13, f64::INFINITY, f64::INFINITY, f64::NAN, f64::INFINITY, f64::NAN, f64::INFINITY] + ) + ]; + + for (test_case,expected_case) in &mut test_cases{ + + float_sorter(test_case); + assert!(vec_compare(test_case, expected_case),"testcase failed for {:?}=={:?}",expected_case,test_case) + } + + } + +} \ No newline at end of file -- cgit 1.4.1