统计数值算法
想通过条码机读一批条码,在读的过程中可能会重复读取,有什么好的、快捷的算法列出不重复数组的数目来,举例说明:比如第一次读到数值{0,0,1},第二次读到{0,0,2},第三次读到{0,0,1},第四次读到{0,0,3},第五次读到{0,0,1},第六次读到{0,0,2},那么这么多次下来,知道读到了三种不同的条码,即{0,0,1},{0,0,2},{0,0,3}最终就是想得到3这个数字。读取条码的次数不定,反正需要在每次读取的时候实时统计出这个不同条码的数字出来。请问这个算法该怎么写?在VB上能否模拟演示一下?
[解决办法]
建立数据库,读取后插入数据,用sql语句读出统计结果,应该是比较快的吧?
[解决办法]
新建一个工程,添加list1,text1,command1.
复制下列代码,运行,按command1,text1里面显示list1的条目总数.
Private Sub Command1_Click() Dim i As Byte, spaceS As Boolean spaceS = True For i = 0 To List1.ListCount If Text1.Text = List1.List(i) Then spaceS = False: Exit For Next If spaceS Then List1.AddItem Text1.Text Text1.Text = List1.ListCountEnd Sub
[解决办法]
Option ExplicitSub Main() Dim a(1 To 6) As String a(1) = "{0,0,1}" a(2) = "{0,0,2}" a(3) = "{0,0,1}" a(4) = "{0,0,3}" a(5) = "{0,0,1}" a(6) = "{0,0,2}" Debug.Print CountDistinct(a)End SubFunction CountDistinct(a() As String) As Long Dim o As Collection Dim i As Long Set o = New Collection For i = LBound(a) To UBound(a) On Error Resume Next o.Add a(i), a(i) On Error GoTo 0 Next CountDistinct = o.CountEnd Function
[解决办法]
新建一个工程,添加 List1, Text1,用 Text1 接收条码阅读器的输出。假定条码阅读器的输出以回车结束。
Private Declare Function SendMessagebyString Lib "user32" Alias "SendMessageA" (ByVal hWND As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As String) As Long
Private Const LB_FINDSTRINGEXACT = &H1A2 '在 ListBox 中精确查找
Private Sub Text1_Change()
Dim n As Long
If Right(Text1, 1) <> vbCrLf Then Exit Sub
n = SendMessagebyString(List1.hWnd, LB_FINDSTRINGEXACT, -1, Text1)
If n = -1 Then
List1.AddItem Text1
End If
End Sub