Finding most common number in array

chemosabe

New member
Local time
Today, 13:16
Joined
Sep 10, 2008
Messages
7
Hi

Anyone have a quick way of finding the most common number in a array?
The array is all one dimensional, with variable length, and all integers.
 
how big is the array

1. either step through the array counting the frequency of each item

2. sort it first, then do the same (easier now its sorted)

3. iterate the array, generating a two dimensional array as you go (index,frequency) then find the highest frequency

4. or move the array into another structure (collection, table)

depends what you want to do with it next
 
Thanks

All i want is to find the number that repeats most often in the array. The length varies, the array that results from this opperation is disposable. I have a sorted array already.
 
Here is a function I quickly whipped up to carry out the task for Single Dimensional Arrays only:

Code:
Public Function MostCommonInArray(ByRef SrcArray() As Variant) As String

[COLOR="DarkGreen"]'*********************************************************************************
   'Returns the most common item in a single dimensional array   **
   'and the number of those items delimited by a Pipe (|) symbol **
   '
   'Example of how to use:
   '=====================
   '
   'Dim MyArray(20) As Variant
   'Dim StrgResult As String, Cnt As Long, StrgItem As String
   
   'MyArray(0) = 1: MyArray(1) = "": MyArray(2) = 3: MyArray(3) = 3: MyArray(4) = 3
   'MyArray(5) = 3: MyArray(6) = 4: MyArray(7) = 5: MyArray(8) = 6: MyArray(9) = 6
   'MyArray(10) = 3: MyArray(11) = 4: MyArray(12) = 4: MyArray(13) = 6: MyArray(14) = 7
   'MyArray(15) = 3: MyArray(16) = 4: MyArray(17) = 5: MyArray(18) = 6: MyArray(19) = 3
   'MyArray(20) = 8
   
   'StrgResult = MostCommonInArray(MyArray())
   'StrgItem = Left$(StrgResult, InStr(StrgResult, " |") - 1)
   'Cnt = CLng(Mid$(StrgResult, InStr(StrgResult, "| ") + 2))
   
   'MsgBox "The Item " & StrgItem & " is most common within the Array." & _
   '       vbCr & "It is found within " & Cnt & " Array elements.", vbInformation, _
   '       "Most Common In Array"
   '*********************************************************************************[/COLOR]
   Dim TmpArray() As Variant
   Dim i As Long, j As Long, x As Long
   Dim Index As Long
   Dim CntArray() As String
   
  [COLOR="DarkGreen"] 'Set the mouse pointer to Busy for Arrays larger than 300 elements.
   'You can set this to whatever you want.[/COLOR]
   If UBound(SrcArray) > 300 Then Screen.MousePointer = 11
   
   [COLOR="DarkGreen"]'Trap Errors[/COLOR]
   On Error Resume Next
   For i = LBound(SrcArray) To UBound(SrcArray)
      [COLOR="DarkGreen"]'If there is a problem with the array passed then get
      'outta here and return "-1 | -1" to indicate a error.[/COLOR]
      If Err <> 0 Then Err.Clear: MostCommonInArray = "-1 | -1": Exit For
      
      [COLOR="DarkGreen"]'Trim any leading or trailing spaces (if any)
      'from the Array element but ONLY if the Element
      'contains a String value.[/COLOR]
      If TypeName(SrcArray(i)) = "String" Then SrcArray(i) = Trim(SrcArray(i))
      
     [COLOR="DarkGreen"] 'Does the TmpArray array contain anything?
      '(an error is used to detect this)[/COLOR]
      j = UBound(TmpArray)
      
      [COLOR="DarkGreen"]'If it does let's carry on...[/COLOR]
      If Err = 0 Then
         For j = LBound(TmpArray) To UBound(TmpArray)
            [COLOR="DarkGreen"]'Make sure we're not working with a blank array element.[/COLOR]
            If Len(SrcArray(i)) = 0 Then Exit For
            If Left$(TmpArray(j), IIf(InStr(1, TmpArray(j), ",") > 0, InStr(1, TmpArray(j), ",") - 1, Len(TmpArray(j)))) = SrcArray(i) Then
               If Right$(TmpArray(j), 1) <> "," Then TmpArray(j) = TmpArray(j) & ","
               TmpArray(j) = TmpArray(j) & SrcArray(i)
               Index = 1: Exit For
            End If
         Next j
         If Index = 0 Then
            ReDim Preserve TmpArray(x)
            TmpArray(x) = SrcArray(i)
            x = x + 1
         End If
      Else
        [COLOR="DarkGreen"] 'The TmpArray Array doesn't contain anything yet so
         'let's create the first element after we clear the
         'error.[/COLOR]
         Err.Clear: x = 0
         ReDim Preserve TmpArray(x)
         TmpArray(x) = SrcArray(i)
         x = x + 1
      End If
   Next i
   
  [COLOR="DarkGreen"] 'Let's see which array element in TmpArray has the most items
   'and Return that info to the calling procedure.[/COLOR]
   x = 0: Index = 0
   For i = LBound(TmpArray) To UBound(TmpArray)
      CntArray = Split(TmpArray(i), ",")
      Index = UBound(CntArray) + 1
      If Index > x Then MostCommonInArray = CntArray(0): x = Index
   Next i
   MostCommonInArray = MostCommonInArray & " | " & x
   
   [COLOR="DarkGreen"]'Kill the temporary Arrays used in this Function.[/COLOR]
   Erase TmpArray, CntArray
   [COLOR="DarkGreen"]'Set the mouse pointer to normal[/COLOR]
   Screen.MousePointer = 0
End Function

Now...it's not very elegant and it's slow if you have arrays which contain thousands of elements. I really don't care a whole lot for this one due to all the Error catching but it was done quickly. It does work Though.

.
 
Im looking for the mode, yes. Ive been googling for ages, and the mode did not give any hits. Thanks bob, cyberlynx. This solves it :)
 
Hello, I can see this page is kinda outdated,
but i have the same problem.
Is any of you still active?

Greetz. Nate
 
Nathan,

Use a table:

Code:
Dim i As Long
Dim rst As DAO.Recordset

For i = 0 To UBound(varArray)
   CurrentDb.Execute "Insert Into MyTable (TheNumber) Values (" & varArray(i)  & ")"
   Next I
Set rst = CurrentDb.OpenRecordset("Select TheNumber As TheMode, Count(*) From MyTable Group By TheNumber Order By Count(*) Desc")

MsgBox("The Mode Is: " & rst!TheMode)

hth,
Wayne
 
Yeaa, i figured that.

The problem is, I got a little diff in my program.

I got 12 text boxes, one label and one commandbutton,

I'm putting numbers in the boxes, and then click the button,
Then I'd like the mode to appear in the Label.caption

Thanks in advance,
Nate
 
Nathan,

If you name the textboxes consistently (txtNumber1 ... txtNumber12):


Code:
Dim i As Long
Dim rst As DAO.Recordset

For i = 1 To 12
   CurrentDb.Execute "Insert Into MyTable (TheNumber) Values (" & Me.Controls("txtNumber" & CStr(i))  & ")"
   Next i
Set rst = CurrentDb.OpenRecordset("Select TheNumber As TheMode, Count(*) From MyTable Group By TheNumber Order By Count(*) Desc")

MsgBox("The Mode Is: " & rst!TheMode)

Wayne
 
Thanks for trying but,

Error 1 Type 'DAO.Recordset' is not defined. C:\Users\Nathan\AppData\Local\Temporary Projects\WindowsApplication1\Form1.vb 9 20 WindowsApplication1
Error 2 Name 'CurrentDb' is not declared. C:\Users\Nathan\AppData\Local\Temporary Projects\WindowsApplication1\Form1.vb 12 13 WindowsApplication1
Error 3 Operator '&' is not defined for types 'String' and 'System.Windows.Forms.Control'. C:\Users\Nathan\AppData\Local\Temporary Projects\WindowsApplication1\Form1.vb 12 31 WindowsApplication1
Error 4 Name 'CurrentDb' is not declared. C:\Users\Nathan\AppData\Local\Temporary Projects\WindowsApplication1\Form1.vb 14 15 WindowsApplication1


Sorry, it does not seem to work :confused:.

Any idea why. ?

I'm using VB 2008...

Greetz, Nate
 

Users who are viewing this thread

Back
Top Bottom