Den*_*ash 2 smalltalk squeak pharo
有没有简单的方法来检查两个数组是否包含相同的元素?
true如果数组不相同,这是我返回的尝试:
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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.
| 归档时间: |
|
| 查看次数: |
107 次 |
| 最近记录: |