Skip to content

Instantly share code, notes, and snippets.

@lucasuyezu
Created June 18, 2018 19:24
Show Gist options
  • Save lucasuyezu/9ce01db4b2723a3325470fb514de8ae8 to your computer and use it in GitHub Desktop.
Save lucasuyezu/9ce01db4b2723a3325470fb514de8ae8 to your computer and use it in GitHub Desktop.
use std::collections::HashMap;
// Given a list of integers, use a vector and return the mean (the average value)
pub fn vec_mean(vec: &Vec<i32>) -> f64 {
let sum = vec_sum(&vec);
sum as f64 / vec.len() as f64
}
// Given a list of integers, use a vector and return the median (when sorted, the value in the middle position)
pub fn vec_median(sorted_vec: &Vec<i32>) -> f64 {
if sorted_vec.len() == 0 {
return 0.0
}
let middle_position = sorted_vec.len() / 2;
if sorted_vec.len() % 2 == 0 {
let middle_upper_position = sorted_vec[middle_position];
let middle_lower_position = sorted_vec[middle_position - 1];
return (middle_lower_position as f64 + middle_upper_position as f64) / 2.0
}
sorted_vec[middle_position] as f64
}
// Given a list of integers, return the mode (the value that occurs most often; a hash map will be helpful here) of the list.
pub fn vec_mode(vec: &Vec<i32>) -> i32 {
let mut occurrences: HashMap<i32, i32> = HashMap::with_capacity(vec.len());
let mut current_max_value = i32::min_value();
let mut current_max_occurrences = 0;
for current_value in vec {
let current_value_occurrences = occurrences.entry(current_value.clone()).or_insert(0);
*current_value_occurrences += 1;
if current_value_occurrences > &mut current_max_occurrences {
current_max_occurrences = current_value_occurrences.clone();
current_max_value = current_value.clone();
}
}
current_max_value
}
fn vec_sum(vec: &Vec<i32>) -> i32 {
let mut sum = 0;
for i in vec {
sum += i;
}
sum
}
pub fn pig_latin(text: &str) -> String {
let mut result = String::new();
let mut add_space = false;
for word in text.split_whitespace() {
if add_space {
result.push(' ');
}
let mut word_chars = word.chars();
if let Some(first_chr) = word_chars.next() {
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' {
result.push_str(&format!("{}-hay", word))
}
else {
result.push_str(&format!("{}-{}ay", word_chars.as_str(), first_chr))
}
}
add_space = true;
}
result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment