Skip to content

Instantly share code, notes, and snippets.

@ford-prefect
Last active March 28, 2017 13:52
Show Gist options
  • Save ford-prefect/5a9bf946d4d18fe6bcc52185bd987dd1 to your computer and use it in GitHub Desktop.
Save ford-prefect/5a9bf946d4d18fe6bcc52185bd987dd1 to your computer and use it in GitHub Desktop.
Collections exercise
// Given a list of integers, use a vector and return the mean (average), median (when sorted,
// the value in the middle position), and mode (the value that occurs most often; a hash map
// will be helpful here) of the list.
// Convert strings to Pig Latin, where the first consonant of each word is moved to the end
// of the word with an added “ay”, so “first” becomes “irst-fay”. Words that start with a
// vowel get “hay” added to the end instead (“apple” becomes “apple-hay”).
// Remember about UTF-8 encoding!
fn avg_and_median(v: &Vec<i32>) -> (i32, i32) {
let mut copy = v.clone();
let mut sum: i32 = 0;
let len: usize = v.len();
for i in v {
sum += *i
}
// or sum = v.iter().fold(0, |acc, &x| acc + x);
copy.sort();
(sum / len as i32, copy[len / 2])
}
fn is_vowel(c: char) -> bool {
match c {
'a' | 'e' | 'i' | 'o' | 'u' => true,
_ => false
}
}
fn piggify(s: &str) -> String {
let mut r = String::new();
let mut chars = s.chars();
let first = s.chars().nth(0);
match first {
Some(c) if !is_vowel(c) => {
chars.next();
r.push_str(chars.as_str());
r.push('-');
r.push(c);
r.push_str("ay");
},
Some(c) if is_vowel(c) => {
r.push_str(chars.as_str());
r.push('-');
r.push_str("hay");
}
_ => (),
}
r
}
fn main() {
let vec = vec![6, 1, 5];
let (avg, median) = avg_and_median(&vec);
let strs = ["first", "apple", ""];
println!("avg: {}, median: {}", avg, median);
println!("first: {}, apple: {}, \"\": {}", piggify(strs[0]), piggify(strs[1]), piggify(strs[2]));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment