To check if two arrays have the same elements regardless of order in Rust, you can sort both arrays and then compare them element by element.
In this example,
arr1
and arr2
with the same elements but in different order.sort
method.arrays_equal
that checks if the sorted arrays are equal.arrays_equal
to compare the arrays and print the result to the console.fn arrays_equal(arr1: &mut [i32], arr2: &mut [i32]) -> bool {
arr1.sort();
arr2.sort();
arr1 == arr2
}
fn main() {
let mut arr1 = [1, 2, 3];
let mut arr2 = [3, 1, 2];
let is_equal = arrays_equal(&mut arr1, &mut arr2);
println!("{}", is_equal);
}
true
In this example,
arr3
and arr4
with different elements.sort
method.arrays_equal
that checks if the sorted arrays are equal.arrays_equal
to compare the arrays and print the result to the console.fn arrays_equal(arr1: &mut [i32], arr2: &mut [i32]) -> bool {
arr1.sort();
arr2.sort();
arr1 == arr2
}
fn main() {
let mut arr3 = [1, 2, 3];
let mut arr4 = [4, 5, 6];
let is_equal = arrays_equal(&mut arr3, &mut arr4);
println!("{}", is_equal);
}
false
In this tutorial, we learned How to check if Two Arrays have Same Elements (Regardless of Order) in Rust language with well detailed examples.