2

Is there any simple way to check if two arrays contain the same elements?

Here is my try were I return true if arrays are not the same:

arr1 := #(1 3 5 6).
arr2 := #(1 2 3 4).
arr2Copy := arr2 copyFrom: 1 to: arr2 size.
arr1 size ~= arr2 size
    ifTrue: [^ true].
arr1
    do: [:a | (arr2copy removeFirst = a)
        ifFalse: [^ true]].
^false
0

2 Answers 2

8

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.

2
  • Two objects can be equal (like arrays with the same contents), but they are still distinct instances and thus not identical. You check for identity with == and for equality with =.
    – JayK
    Commented Jun 8, 2019 at 11:41
  • SmallIntegers as used in your example are also identical when they are equal. The same does not hold for Strings, Points, and Rectangles, for example.
    – JayK
    Commented Jun 8, 2019 at 11:45
3

As a side comment, please note that your code was almost right. Just change:

arr2Copy := arr2 copyFrom: 1 to: arr2 size.  

with the following:

arr2copy := arr2 asOrderedCollection.  

and your code will work. The reason is that you cannot removeFirst from an Array. This is why you need an OrderedCollection instead. (Note b.t.w. that there was a mismatch between the capitalizations of arr2copy).

Of course, this implementation is not as efficient as the one in the accepted answer, but I thought it might be useful to also give you some feedback about your approach.

Not the answer you're looking for? Browse other questions tagged or ask your own question.