Guest User

Untitled

a guest
Jun 20th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. use std::collections::HashMap;
  2.  
  3. // Given a list of integers, use a vector and return the mean (the average value)
  4. pub fn vec_mean(vec: &Vec<i32>) -> f64 {
  5. let sum = vec_sum(&vec);
  6.  
  7. sum as f64 / vec.len() as f64
  8. }
  9.  
  10. // Given a list of integers, use a vector and return the median (when sorted, the value in the middle position)
  11. pub fn vec_median(sorted_vec: &Vec<i32>) -> f64 {
  12. if sorted_vec.len() == 0 {
  13. return 0.0
  14. }
  15.  
  16. let middle_position = sorted_vec.len() / 2;
  17.  
  18. if sorted_vec.len() % 2 == 0 {
  19. let middle_upper_position = sorted_vec[middle_position];
  20. let middle_lower_position = sorted_vec[middle_position - 1];
  21. return (middle_lower_position as f64 + middle_upper_position as f64) / 2.0
  22. }
  23.  
  24.  
  25. sorted_vec[middle_position] as f64
  26.  
  27. }
  28.  
  29. // Given a list of integers, return the mode (the value that occurs most often; a hash map will be helpful here) of the list.
  30. pub fn vec_mode(vec: &Vec<i32>) -> i32 {
  31. let mut occurrences: HashMap<i32, i32> = HashMap::with_capacity(vec.len());
  32.  
  33. let mut current_max_value = i32::min_value();
  34. let mut current_max_occurrences = 0;
  35.  
  36. for current_value in vec {
  37. let current_value_occurrences = occurrences.entry(current_value.clone()).or_insert(0);
  38. *current_value_occurrences += 1;
  39.  
  40. if current_value_occurrences > &mut current_max_occurrences {
  41. current_max_occurrences = current_value_occurrences.clone();
  42. current_max_value = current_value.clone();
  43. }
  44. }
  45.  
  46. current_max_value
  47. }
  48.  
  49. fn vec_sum(vec: &Vec<i32>) -> i32 {
  50. let mut sum = 0;
  51.  
  52. for i in vec {
  53. sum += i;
  54. }
  55.  
  56. sum
  57. }
  58.  
  59.  
  60. pub fn pig_latin(text: &str) -> String {
  61. let mut result = String::new();
  62.  
  63. let mut add_space = false;
  64. for word in text.split_whitespace() {
  65.  
  66. if add_space {
  67. result.push(' ');
  68. }
  69.  
  70. let mut word_chars = word.chars();
  71.  
  72. if let Some(first_chr) = word_chars.next() {
  73. if first_chr == 'a' || first_chr == 'e' || first_chr == 'i' || first_chr == 'o' || first_chr == 'u' || first_chr == 'A' || first_chr == 'E' || first_chr == 'I' || first_chr == 'O' || first_chr == 'U' {
  74. result.push_str(&format!("{}-hay", word))
  75. }
  76. else {
  77. result.push_str(&format!("{}-{}ay", word_chars.as_str(), first_chr))
  78. }
  79. }
  80.  
  81. add_space = true;
  82. }
  83.  
  84. result
  85. }
Add Comment
Please, Sign In to add comment