Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::iter::Iterator;
- use std::borrow::Borrow;
- trait SequencePositionExt : Iterator
- where Self: Sized
- {
- fn sequence_position<T>(mut self, seq: &[T]) -> Option<usize>
- where Self::Item : Borrow<T>, T: PartialEq
- {
- let mut pos = 0;
- let mut ring = Vec::with_capacity(seq.len());
- for _ in seq {
- ring.push(None);
- }
- let mut ring_pos = 0;
- while let Some(item) = self.next() {
- pos += 1;
- ring[ring_pos] = Some(item);
- ring_pos += 1;
- if ring_pos == ring.len() {
- ring_pos = 0;
- }
- if ring.iter().cycle().skip(ring_pos).take(ring.len()).map(|x| x.as_ref().map(|x| x.borrow())).eq(seq.iter().map(Some)) {
- return Some(pos - seq.len());
- }
- }
- None
- }
- }
- impl<T: Iterator + Sized> SequencePositionExt for T {}
- fn main() {
- println!("{:?}", [2,4,6,3].iter().sequence_position(&[2,4]));
- }
Add Comment
Please, Sign In to add comment