Search code examples
smalltalkpharosqueak

How to check if two arrays contain the same elements?


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

Solution

  • 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.