Advertisement
omphen

Untitled

Jul 8th, 2024
516
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.92 KB | None | 0 0
  1. use rand::Rng;
  2.  
  3. const MIN_LENGTH: usize = 3;
  4. const MAX_LENGTH: usize = 10;
  5. const MIN_DATA: usize = 1;
  6. const MAX_DATA: usize = 100;
  7.  
  8. fn main() {
  9.     let length = rand::thread_rng().gen_range(MIN_LENGTH..=MAX_LENGTH);
  10.     let list = generate_list(&length);
  11.     println!("the list i generated is here: {list:?}");
  12.  
  13.     let median = find_median(list, length);
  14.     println!("the median of this list is: {median}");
  15. }
  16.  
  17. fn generate_list(length: &usize) -> Vec<usize> {
  18.     let mut list = Vec::new();
  19.     for _i in 0..*length {
  20.         let point = rand::thread_rng().gen_range(MIN_DATA..=MAX_DATA);
  21.         list.push(point);
  22.     }
  23.     list
  24. }
  25.  
  26. fn find_median(list: Vec<usize>, length: usize) -> f32 {
  27.     let pivot_index = get_pivot(length);
  28.     if length % 2 == 0 {
  29.         (quickselect(&list, (length - 1) / 2, pivot_index) + quickselect(&list, ((length - 1) / 2) + 1, pivot_index)) / 2.0
  30.     } else {
  31.         quickselect(&list, (length - 1) / 2, pivot_index)
  32.     }
  33. }
  34.  
  35. fn quickselect(list: &Vec<usize>, k: usize, pivot_index: usize) -> f32 {
  36.     // base case
  37.     if list.len() == 1 {
  38.         list[0] as f32
  39.     } else {
  40.         // recurse
  41.         let mut lesser_list: Vec<usize> = Vec::new();
  42.         let mut greater_list: Vec<usize> = Vec::new();
  43.         let pivot = list[pivot_index];
  44.         for i in list {
  45.             if i <= &pivot {
  46.                 lesser_list.push(*i);
  47.             } else {
  48.                 greater_list.push(*i);
  49.             }
  50.         }
  51.         println!("pivot: {pivot} k: {k} lesser list: {lesser_list:?} greater list: {greater_list:?}");
  52.         let len_lesser = lesser_list.len();
  53.         if &len_lesser > &k {
  54.             quickselect(&lesser_list, k, get_pivot(len_lesser))
  55.         } else {
  56.             quickselect(&greater_list, k - &len_lesser, get_pivot(greater_list.len()))
  57.         }
  58.     }
  59. }
  60.  
  61. fn get_pivot(length: usize) -> usize {
  62.     rand::thread_rng().gen_range(0..length)
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement