1

I have x_min and x_max, both i16 and x_coordinates, which is a Vec<i16>. Now, I want to check whether every x_coordinate lies between x_min and x_max.

I came up with the following solution, which does indeed work, I think.

!x_coordinates.iter().map(|x| (x_min..=x_max).contains(&x)).collect::<Vec<bool>>().contains(&false)

But this does O(n) passes thrice before giving an answer. Is there a way to short-circuit the Iterator as soon as it finds something that returns a falsey condition?

2
  • 1
    doc.rust-lang.org/stable/std/iter/… Commented Jun 23 at 13:04
  • 1
    Note that this code only goes through the data twice not three times: once for the collect and once for the final contains. (x_min..=x_max).contains (&x) is O(1) and the other operations are all lazy. Commented Jun 23 at 18:33

1 Answer 1

3

Thanks to Chayim in the comments, I have now a better solution:

x_coordinates.iter().all(|x| (x_min..=x_max).contains(&x))
Sign up to request clarification or add additional context in comments.

2 Comments

I mean, even a for loop will do. all() is just nicer and shorter.
Of course, it is just I prefer solutions which are more functional in style.

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.