3 ms·
fn put_string(array: &mut Vec<String>, input: String) { array.push(input) } fn find_string(array: &[String], input: &str) -> Option<usize>
by umanwizard 5y ago
fn put_string(array: &mut Vec<String>, input: String) {
array.push(input)
}
fn find_string(array: &[String], input: &str) -> Option<usize> {
for i in 0..array.len() {
if &array[i] == input {
return Some(i);
}
}
None
// or perhaps more idiomatically:
// array.iter().position(|s| s.as_str() == input)
}
#[test]
fn test_find_string() {
let mut array = vec![];
put_string(&mut array, “foo”.to_string());
put_string(&mut array, “bar”.to_string());
assert_eq!(find_string(&array, “foo”), Some(0));
assert_eq!(find_string(&array, “bar”), Some(1));
assert_eq!(find_string(&array, “quux”), None);
}
If our array is sorted, the performance of the function should improve due to better branch prediction. But we’d be better of rewriting it as binary search in that case.
What kind of salary are you offering?
- fridif 5y agoIn the USA you're worth at least 100k. However, like many others who conduct interviews, I'm not the one who signs the paycheck :)