Advertisement
Guest User

Untitled

a guest
May 22nd, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. struct CommonOfSorted<I1: Iterator, I2: Iterator> {
  2. first: std::iter::Peekable<I1>,
  3. second: std::iter::Peekable<I2>,
  4. }
  5.  
  6. impl<T, I1, I2> Iterator for CommonOfSorted<I1, I2>
  7. where
  8. T: Ord,
  9. I1: Iterator<Item = T>,
  10. I2: Iterator<Item = T>,
  11. {
  12. type Item = T;
  13.  
  14. fn next(&mut self) -> Option<T> {
  15. use std::cmp::Ordering;
  16.  
  17. while let (Some(first), Some(second)) = (self.first.peek(), self.second.peek()) {
  18. match first.cmp(&second) {
  19. Ordering::Less => {
  20. self.first.next();
  21. }
  22. Ordering::Greater => {
  23. self.second.next();
  24. }
  25. Ordering::Equal => {
  26. self.second.next();
  27. return self.first.next();
  28. }
  29. }
  30. }
  31.  
  32. None
  33. }
  34. }
  35.  
  36. fn common_of_sorted<I1: Iterator, I2: Iterator>(first: I1, second: I2) -> CommonOfSorted<I1, I2> {
  37. CommonOfSorted {
  38. first: first.peekable(),
  39. second: second.peekable(),
  40. }
  41. }
  42.  
  43. type Num = i64;
  44.  
  45. fn least_common_of_three(a: &[Num], b: &[Num], c: &[Num]) -> Option<Num> {
  46. let a_b = common_of_sorted(a.iter(), b.iter());
  47. common_of_sorted(a_b, c.iter()).next().cloned()
  48. }
  49.  
  50. fn main() {
  51. let a = [1, 5, 10, 11, 90];
  52. let b = [-10, 5, 7, 8, 40];
  53. let c = [0, 5, 6, 12, 20, 30];
  54.  
  55. println!("{:?}", least_common_of_three(&a, &b, &c)); //Some(5)
  56.  
  57. let b = [-10, /*5,*/ 7, 8, 40];
  58.  
  59. println!("{:?}", least_common_of_three(&a, &b, &c)); //None
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement