2011-02-03 2 views
1

내가 VB6에서 중복을 제거 느린이 기능을제거 빠른 VB6 복제

내가 더 빨리 실행하려면이 기능을 최적화해야
Function FilterDuplicates(Arr As Variant) As Long 
    Dim col  As Collection, index As Long, dups As Long 
    Set col = New Collection 

    On Error Resume Next 

    For index = LBound(Arr) To UBound(Arr) 
     ' build the key using the array element 
     ' an error occurs if the key already exists 
     col.Add 0, CStr(Arr(index)) 
     If Err Then 
      ' we've found a duplicate 
      Arr(index) = Empty 
      dups = dups + 1 
      Err.Clear 
     ElseIf dups Then 
      ' if we've found one or more duplicates so far 
      ' we need to move elements towards lower indices 
      Arr(index - dups) = Arr(index) 
      Arr(index) = Empty 
     End If 
    Next 

    ' return the number of duplicates 
    FilterDuplicates = dups 

End Function 

, 내가 추가 내 대답을 업데이트

+0

도움을 주시기 바랍니다가 마지막 비트. 그래도 숙제를해야할까요? –

+0

아니 숙제가 아니지만 왜 그런 질문을 했습니까? – Smith

답변

1
Function FilterDuplicates(Arr As Variant) As Long 
    Dim col  As Dictionary, index As Long, dups As Long 
    Set col = New Dictionary 

    On Error Resume Next 

    For index = LBound(Arr) To UBound(Arr) 
     ' build the key using the array element 
     ' an error occurs if the key already exists 
     If col.Exists(Arr(index)) Then 
      ' we've found a duplicate 
      dups = dups + 1 
     Else 
      Call col.Add(Arr(index), vbNullstring) 
     End If 
    Next 

    Dim newArr(1 to col.Keys.Count) As Variant 
    Dim newIndex As Long 
    For index = LBound(Arr) To UBound(Arr) 
     If col(Arr(index)) = vbNullstring Then 
      newIndex = newIndex + 1 
      col(Arr(index)) = "Used" 
      newArr(newIndex) = Arr(index) 
     End If 
    Next index 
    Arr = newArr 

    ' return the number of duplicates 
    FilterDuplicates = dups 

End Function 
+0

함수가 완전하지 않습니다. 어떻게 사용합니까? – Smith

+2

두 가지. 먼저 프로젝트/참조 대화 상자를 사용하여 사전을 사용할 수 있도록 "Microsoft Scripting Runtime"에 대한 참조를 프로젝트에 추가해야합니다. 둘째,'If col.Exists ...'줄에'Then'이 없습니다. 불완전한 경우, For/Next가 완료되면'col'에있는 항목을 제외하고 배열을 다시 빌드하면됩니다. 너는 그걸 처리 할 수있어, 내가 생각할 것 같은 ...? 힌트 : 다른 For/Next 루프? – JeffK

+0

컬렉션을 사용하는 대신 일반 배열을 사용할 수 없습니까? – Smith