On Jan 31, 2009, at 2:10 PM, Tom Russell wrote:
I am trying to remove duplicates in an array but not sure how to
handle once I get down to below 0. TheDocs is an array of strings.
My code:
dim i as Integer
TheDocs.Sort
for i = UBound(TheDocs) downto 0
if TheDocs(i) = TheDocs(i-1) then
TheDocs.Remove i
end if
Next
Once i gets to 0 then it will throw an out of bounds exception and
this is where I am not sure how to handle this.
Rewrite your code so that it doesn't call TheDocs(i - 1) when i = 0.
Here is your code, fixed.
TheDocs.Sort
for i as Integer = UBound(TheDocs) - 1 downto 0
if TheDocs(i + 1) = TheDocs(i) then
TheDocs.Remove i + 1
end if
next
Someone else suggested using a Dictionary object. I suggest using it
as follows.
Function RemoveDuplicates(theList() as Integer) as Integer()
dim d as new Dictionary
dim newList() as Integer
for i as Integer = 0 to UBound(theList)
if not d.HasKey(theList(i)) then
newList.Append theList(i)
d.Value(theList(i) = nil
end if
next
return newList
End Function
This code should preserve the order of the original array. And I
would expect it to be faster for sufficiently large arrays.
Charles Yeomans
_______________________________________________
Unsubscribe or switch delivery mode:
<http://www.realsoftware.com/support/listmanager/>
Search the archives:
<http://support.realsoftware.com/listarchives/lists.html>
|