I’m sorry for the lack of posts over the last few months – what can I say, I’ve been busy. I had meant to continue the series on data access patterns from here and I put a revision of the code here, but I haven’t had the time to do much more. I may get back to it eventually, but in the meantime I thought I’d post something else which I’ve found dictionaries to be quite useful for.
The below is a function which gives a count of the distinct items in an array. As items are added, the dictionary will prevent duplication of key values – and the Count method gives the number of keys in the dictionary.
Public Function CountDistinct(ByRef vArr As Variant) As Variant Dim dict As Scripting.Dictionary Dim lVal As Long Set dict = New Scripting.Dictionary For lVal = LBound(vArr) To UBound(vArr) dict(vArr(lVal)) = vArr(lVal) Next lVal CountDistinct = dict.Count End Function ?CountDistinct(array(1,2,3,3,4)) 4
A much simpler implementation is available in Python, using the set datatype:
>>> def CountDistinct(vals): ... return len(set(vals)) ... >>> CountDistinct([1, 2, 3, 3, 4]) 4