Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct CommonOfSorted<I1: Iterator, I2: Iterator> {
- first: std::iter::Peekable<I1>,
- second: std::iter::Peekable<I2>,
- }
- impl<T, I1, I2> Iterator for CommonOfSorted<I1, I2>
- where
- T: Ord,
- I1: Iterator<Item = T>,
- I2: Iterator<Item = T>,
- {
- type Item = T;
- fn next(&mut self) -> Option<T> {
- use std::cmp::Ordering;
- while let (Some(first), Some(second)) = (self.first.peek(), self.second.peek()) {
- match first.cmp(&second) {
- Ordering::Less => {
- self.first.next();
- }
- Ordering::Greater => {
- self.second.next();
- }
- Ordering::Equal => {
- self.second.next();
- return self.first.next();
- }
- }
- }
- None
- }
- }
- fn common_of_sorted<I1: Iterator, I2: Iterator>(first: I1, second: I2) -> CommonOfSorted<I1, I2> {
- CommonOfSorted {
- first: first.peekable(),
- second: second.peekable(),
- }
- }
- type Num = i64;
- fn least_common_of_three(a: &[Num], b: &[Num], c: &[Num]) -> Option<Num> {
- let a_b = common_of_sorted(a.iter(), b.iter());
- common_of_sorted(a_b, c.iter()).next().cloned()
- }
- fn main() {
- let a = [1, 5, 10, 11, 90];
- let b = [-10, 5, 7, 8, 40];
- let c = [0, 5, 6, 12, 20, 30];
- println!("{:?}", least_common_of_three(&a, &b, &c)); //Some(5)
- let b = [-10, /*5,*/ 7, 8, 40];
- println!("{:?}", least_common_of_three(&a, &b, &c)); //None
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement