about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorAlexanderKabui <alexanderkabua@gmail.com>2022-11-28 02:46:25 +0300
committerAlexanderKabui <alexanderkabua@gmail.com>2022-11-28 02:46:25 +0300
commitf36b234e02b1a64ce0fca853bee7861594ab8b6a (patch)
tree3f9c56dbd4463bee11a026facb1a25948c2571da /src
parentb82a93b691bb86e9dcf4ed30a4011a159857bba5 (diff)
downloadcorrelation_rust-f36b234e02b1a64ce0fca853bee7861594ab8b6a.tar.gz
add custom sorter function
Diffstat (limited to 'src')
-rw-r--r--src/sorter.rs57
1 files changed, 57 insertions, 0 deletions
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<f64>, Vec<f64>);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