Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare a vector against a reversed version of itself?

Tags:

equality

rust

Why won't this compile?

fn isPalindrome<T>(v: Vec<T>) -> bool {
  return v.reverse() == v;
}

I get

error[E0308]: mismatched types
 --> src/main.rs:2:25
  |
2 |   return v.reverse() == v;
  |                         ^ expected (), found struct `std::vec::Vec`
  |
  = note: expected type `()`
             found type `std::vec::Vec<T>`
like image 564
mfirry Avatar asked Nov 27 '22 07:11

mfirry


1 Answers

Since you only need to look at the front half and back half, you can use the DoubleEndedIterator trait (methods .next() and .next_back()) to look at pairs of front and back elements this way:

/// Determine if an iterable equals itself reversed
fn is_palindrome<I>(iterable: I) -> bool
where
    I: IntoIterator,
    I::Item: PartialEq,
    I::IntoIter: DoubleEndedIterator,
{
    let mut iter = iterable.into_iter();
    while let (Some(front), Some(back)) = (iter.next(), iter.next_back()) {
        if front != back {
            return false;
        }
    }

    true
}

(run in playground)

This version is a bit more general, since it supports any iterable that is double ended, for example slice and chars iterators.

It only examines each element once, and it automatically skips the remaining middle element if the iterator was of odd length.

like image 156
5 revs, 2 users 86% Avatar answered Jun 06 '23 03:06

5 revs, 2 users 86%