1

I've been hunting for what I would hope would be a std function, but can't find it. I'm looking for function or method that gives vector overlaps. So, assuming the two vectors:

let my_vector1 = ["snake", "bird", "fish", "cat", "dog"];

and

let my_vector2 = ["tiger", "cat", "bear", "dog", "coyote"];

I'm searching for the indexes over the overlaps.

enter image description here

I'd assume a function like...

let values1 = my_vector1.overlaps(my_vector2);
// values1 = [3, 4]
let values2 = my_vector2.overlaps(my_vector1);
// values2 = [1, 3]

I'd expect for something as commonplace as getting the index of an inner-join of vectors would be simple and standard as a common data flow. However, the join that does exist for vectors is about turning the vector into a string, and honestly I'm at a loss, and my own functions I've attempted are big, bulky, and just don't work well.

What would be the idiomatic way to do this?

1
  • 2
    Sticking to Vec like this, but if those get "large", use a temporary HashSet<&T>. Commented Jun 28 at 14:43

1 Answer 1

3

It should be pretty straightforward to write your own function to do this, just as you would in any other language. All you need are the indices of elements in the first vector that are also in the second vector.

One arguably "idiomatic" way to do this would be to

  • Accept slices, so any contiguous sequence (like an array) can be used, not just a Vec
  • Use iterators
  • Make the function generic over any comparable element type
  • Return the indices as a lazily evaluated Iterator:
fn overlaps<T: Eq>(a: &[T], b: &[T]) -> impl Iterator<Item = usize> {
    a.iter()
        .enumerate()
        .filter_map(|(i, x)| b.contains(x).then_some(i))
}

The returned Iterator can be directly iterated through without allocating additional memory (if the indices are only meant to be used once) or can be collected into a Vec for storage.

Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.