Find The Common Elements In Two Arrays In Rust
Code snippet for how to Find The Common Elements In Two Arrays In Rust with sample and detail explanation
Finding common elements in two arrays is a fundamental task in any programming language, which often comes up in contexts such as data analysis, and algorithm development. In this article, we’ll demonstrate a simple way to tackle this task using Rust, an increasingly popular language known for its performance and safety.
Code Snippet: Finding Common Elements in Rust
fn main() {
let arr1 = [1, 2, 3, 4, 5];
let arr2 = [4, 5, 6, 7, 8];
let common: Vec<i32> = arr1.iter().filter(|&num| arr2.contains(num)).cloned().collect();
println!("{:?}", common);
}
Code Explanation for Finding Common Elements in Rust
Let’s break down the code to understand it better.
- We’re defining two arrays
arr1
andarr2
which contain 5 elements each. We’ll find the common elements in these two arrays.
let arr1 = [1, 2, 3, 4, 5];
let arr2 = [4, 5, 6, 7, 8];
-
We use the
filter
method to identify the common elements.filter
is a method provided by Rust that applies a specified function or condition to each item in an array and returns an array that contains items where the provided function will returntrue
. -
We create a closure
|&num| arr2.contains(num)
which will check whether each number inarr1
exists inarr2
or not. -
filter
method will return an iterator, but we need to turn it back into a collection. So, we will usecloned
method, which creates a copy of value and thencollect
method to get our result as a vector.
let common: Vec<i32> = arr1.iter().filter(|&num| arr2.contains(num)).cloned().collect();
- Finally, we are printing the common elements using
println!
.
println!("{:?}", common);
That’s all! Run the program, and you will see [4,5]
printed to the console, which are the common elements in arr1
and arr2
. This approach is perfect for finding common elements in two arrays containing a smaller number of elements. However, for larger arrays, an optimized approach using hashsets would be recommended.
In this tutorial, you’ve learned how to find common elements of two arrays in Rust language using the filter
method. Happy coding!