Skip to content

Commit

Permalink
Possible fix pharo-project#6758
Browse files Browse the repository at this point in the history
Changes removeDuplicate complexity from O(N^2) to O(N) by keeping track of the elements already seen.
  • Loading branch information
weslleymberg committed Jul 6, 2020
1 parent b3d801c commit e3590ff
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
13 changes: 6 additions & 7 deletions src/Collections-Sequenceable/OrderedCollection.class.st
Original file line number Diff line number Diff line change
Expand Up @@ -713,17 +713,16 @@ OrderedCollection >> removeDuplicates [
"#(7 42 7 42 9) asOrderedCollection removeDuplicates asArray >>> #(7 42 9)"
"#(1 2 3) asOrderedCollection removeDuplicates asArray >>> #(1 2 3)"

| iterator |
| iterator seen |
self ifEmpty: [ ^ self ].
iterator := 1.
seen := Set new.
[ iterator <= self size ]
whileTrue: [ | each newIndex |
whileTrue: [ | each |
each := self at: iterator.
newIndex := iterator + 1.
[ newIndex := (self indexOf: each startingAt: newIndex).
newIndex > 0 ]
whileTrue: [ self removeAt: newIndex ].
iterator := iterator + 1.
(seen includes: each)
ifTrue: [ self removeAt: iterator ]
ifFalse: [ seen add: each. iterator := iterator + 1. ].
]
]

Expand Down
6 changes: 6 additions & 0 deletions src/Collections-Tests/OrderedCollectionTest.class.st
Original file line number Diff line number Diff line change
Expand Up @@ -995,6 +995,12 @@ OrderedCollectionTest >> testRemoveAt [

]

{ #category : #'tests - removing' }
OrderedCollectionTest >> testRemoveDuplicates [
self assert: #(7 42 7 42 9) asOrderedCollection removeDuplicates equals: #(7 42 9) asOrderedCollection.
self assert: #(1 2 3) asOrderedCollection removeDuplicates equals: #(1 2 3) asOrderedCollection
]

{ #category : #'tests - removing' }
OrderedCollectionTest >> testRemoveFirst [
"Allows one to remove n element of a collection at the first"
Expand Down

0 comments on commit e3590ff

Please sign in to comment.