-
-
Save kindlychung/725da856136258cc1a3eddb3781aaa11 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
error: no method named `max_elem` found for type `[{integer}; 6]` in the current scope | |
--> src/max_elem.rs:34:17 | |
| | |
34 | let m = array.max_elem(); | |
| ^^^^^^^^ | |
| | |
= help: items from traits can only be used if the trait is implemented and in scope; the following trait defines an item `max_elem`, perhaps you need to implement it: | |
= help: candidate #1: `max_elem::MaxElem` | |
error: aborting due to previous error | |
Build failed, waiting for other jobs to finish... | |
error: Could not compile `algorithms_in_a_nutshell`. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait MaxElem<T> { | |
fn max_elem<'a>(&'a self) -> &'a T; | |
} | |
impl<'u, T> MaxElem<T> for &'u [T] where T: Ord { | |
fn max_elem<'a>(&'a self) -> &'a T { | |
max_elem_helper(self, 0, self.len()) | |
} | |
} | |
fn max_elem_helper<'a, T>(vec: &'a &[T], left: usize, right: usize) -> &'a T | |
where T: Ord | |
{ | |
if right - left == 1 { | |
return &vec[left]; | |
} | |
let mid = (left + right) / 2; | |
let max1 = max_elem_helper(vec, left, mid); | |
let max2 = max_elem_helper(vec, mid, right); | |
if max1 > max2 { | |
max1 | |
} else { | |
max2 | |
} | |
} | |
#[cfg(test)] | |
mod test { | |
use max_elem::MaxElem; | |
#[test] | |
fn test_max_elem() { | |
let array = [11, 2, 9, 1, 3, 88]; | |
let m = array.max_elem(); | |
assert_eq!(m, 88); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment