Check if two arrays have the same contents (in any order)
This doesn't require conversion to set:
a.sort == b.sort
How to know if two arrays have the same values
Sort the arrays and compare their values one by one.
function arrayCompare(_arr1, _arr2) {
if (
!Array.isArray(_arr1)
|| !Array.isArray(_arr2)
|| _arr1.length !== _arr2.length
) {
return false;
}
// .concat() to not mutate arguments
const arr1 = _arr1.concat().sort();
const arr2 = _arr2.concat().sort();
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
How to check if two arrays contain the same elements?
If the elements should be equal and in the same order, you can just compare the arrays with =.
If the elements should be equal and the order does not matter and there are no duplicates to be expected, use array1 asSet = arr2 asSet
.
Otherwise you can check out hasEqualElements:, and asBag as well.
If the elements should be identical and in the same order, how about this?
array1 with: array2 do:
[ :a :b | a == b ifFalse: [ ^ false ]].
^ true
It iterates over the two arrays simultaneously, comparing the identities of elements at the same indices. If any are not identical, return false. If no distinct elements were encountered, return true.
Checks if two arrays have elements in the same order
If an array is cyclic then array+array
has the the whole array of another part.
For example:
[2 3 4 1] append [2 3 4 1] = [2 3 4 1 2 3 4 1]
|-------|
as you can see [1 2 3 4]
is "somewhere" in the appending of the same array twice.
So by this logic you can do a O(n*m)
operation that checks every case to see if it is a match (n being array1 and m being array2):
//array1 has [2 3 4 1 2 3 4 1]
//array2 has [1 2 3 4]
boolean check = false;
for(int i = 0; i < array1.length(); i++) {
for(int j; j < array2.length(); j++) {
if((i+j) <= array1.length()) {
if(array1[i+j] == array2[j])
check = true;
else
check = false;
}
}
if(check)
return true; // returns true if all array2 == some part of array1
}
return false;
You can also check out the Boyer-Moore algorithm to improve on this. Its for string matching, but the same logic can be applied here.
The basic idea is having a lookup table of array2 and being able to "skip" values you know you don't have to check again.
1 2 3 4 5 6
3 4 5
^-------^ lookup table sees that the offset is 3 to match array2[0] with array1[2]
1 2 3 4 5 6
skip to--->3 4 5
would be the next iteration
Is there a way to check if two arrays have the same elements?
Using jQuery
You can compare the two arrays using jQuery
:
// example arrays:
var firstArray = [ 1, 2, 3, 4, 5 ];
var secondArray = [ 5, 4, 3, 2, 1 ];
// compare arrays:
var isSameSet = function( arr1, arr2 ) {
return $( arr1 ).not( arr2 ).length === 0 && $( arr2 ).not( arr1 ).length === 0;
}
// get comparison result as boolean:
var result = isSameSet( firstArray, secondArray );
Here is a JsFiddle Demo
See this question helpful answer
How do I check in Swift if two arrays contain the same elements regardless of the order in which those elements appear in?
Swift 3, 4
extension Array where Element: Comparable {
func containsSameElements(as other: [Element]) -> Bool {
return self.count == other.count && self.sorted() == other.sorted()
}
}
// usage
let a: [Int] = [1, 2, 3, 3, 3]
let b: [Int] = [1, 3, 3, 3, 2]
let c: [Int] = [1, 2, 2, 3, 3, 3]
print(a.containsSameElements(as: b)) // true
print(a.containsSameElements(as: c)) // false
Best way to check if two arrays have the same members
Given that you are doing a length check, I'm going to go with the assumption that implies that they are 1:1, just ordered differently.
You can do this in one pass (each) using a map[string]bool
to check existence in both. This utilizes the fact that the map
returns the zero value of a bool
, which is false
, when the key is not present.
Disclaimer: Technically this is order O(n)*O(map). The Go Programming Language Specification does not make any performance guarantees for map types.
https://play.golang.org/p/2LUjN5LkXLL
func unorderedEqual(first, second []string) bool {
if len(first) != len(second) {
return false
}
exists := make(map[string]bool)
for _, value := range first {
exists[value] = true
}
for _, value := range second {
if !exists[value] {
return false
}
}
return true
}
If you want to get nit-picky about memory usage, you could save yourself storing a bunch of bool
s (which is usually negligible, but to each their own) by using a map[string]struct{}
(the empty struct), and you just check existence a little differently, as in this example.
https://play.golang.org/p/MjwP_wCtYZV
Set
exists[value] = struct{}{}
Check
if _, ok := exists[value]; !ok {
return false
}
Check if two arrays have the same values
sort($a);
sort($b);
if ($a===$b) {//equal}
Check 2 arrays if they have the same content, ignoring order, no sorting. What is the most efficient algorithm
Here's a solution that can be implemented with O(n) complexity:
- Create a hash map for each array. The key is the array element. The value is the number of occurences.
- Iterate over the keys of the first hash
map and check if the value is the same for both hash maps. - If all values are the same, the arrays are equal.
Related Topics
Ruby Way to Check for String Palindrome
Ruby: How to Iterate Over an Array of Hashes and Return the Values in a Single String
Creating Signature and Nonce for Oauth (Ruby)
Rails: Money Gem Converts All Amounts to Zero
Should I Test Private Methods Using Rspec
Openid Support for Ruby on Rails Application
How to List Included Modules in a Ruby Class
After Gem Update: Test Fail with "Asset Was Not Declared to Be Precompiled in Production"
How to Write Negative Loop in Ruby Like For(I=Index; I >= 0; I --)
What's the Right Way to Implement Equality in Ruby
Undefined Method 'Devise' for User
How to Initialize an Array Inside a Hash in Ruby