Fastest way to detect duplicate numbers on array vb.net 2005

前端 未结 9 1427
轮回少年
轮回少年 2021-01-20 17:31

I have this project that let user inputs 5 different numbers from 1 to 50. But I want to validate it before saving to DB that i will be 5 unique numbers. What\'s the best an

相关标签:
9条回答
  • 2021-01-20 17:55
    Pseudocode:
    
    integer numbers[50]
    zeroarray(numbers, 50)
    
    integer count = 0;
    while (count < 5)
    {
       integer value = getinput()
    
       if (value >= 1 and value <= 50)
         if (numbers[value] = 0)
         {
            count = count + 1
            numbers[value] = 1
         }
         else
            reject duplicate
       else
         reject invalid
    }
    
    0 讨论(0)
  • 2021-01-20 17:57

    Reed Copsey's suggestion to use hash sets was a good one (I hadn't worked with the HashSet class before).

    But I then discovered that the IEnumerable class offers an extension method called Distinct that copies the unique values from a source IEnumerable to a target IEnumerable.

    Borrowing the first line of Reed's sample code, here's the new sample VB.NET code:

        Dim numbers As IEnumerable(Of Integer) = GetInputFromUser()
        Dim isUnique As Boolean = (numbers.Distinct.Count = numbers.Count)
    

    The variable isUnique is True if the numbers IEnumerable contains no duplicate values, or False if it contains one or more duplicate values.

    0 讨论(0)
  • 2021-01-20 18:08

    Put in an array, sort it and check if elements 1,2 2,3 3,4 and 4,5 are different (in a loop).

    0 讨论(0)
  • 2021-01-20 18:09

    To simplifiy lets say the user inputs 5 different numbers from 0 to 49.

    You can create a Boolean Array IsUsed(49) with 50 elements.

    Then when the user input the value iInputNum=30 you can set IsUsed(30)=TRUE. Next time, when the user input the second value iInputNum=7, you can set IsUsed(7)=TRUE In this way you can check in a very fast way if the number was already inserted.

    if IsUsed(iInputNum) then
       'Skip the Input (put the right code here)
    else
       'Accept the number
       IsUsed(iInputNum)=TRUE
       'save iInputNum in the database
    end if
    

    Do not forget to clear the array after inserting all 5 numbers. Remenber to put the right index in order to handle the number 1-50 (e not 0-49)

    0 讨论(0)
  • 2021-01-20 18:10

    You can try this very simple method: Filtering Arrays using LINQ

    0 讨论(0)
  • 2021-01-20 18:17

    Check this code

    Private Function HasDuplicates(ByVal arr As Array) As Boolean
        For i As Integer = 0 To arr.Length - 1
            If Not arr(i) Is Nothing Then
                Dim l As Integer = Array.LastIndexOf(arr, arr(i))
                If l <> i Then Return True
            End If
        Next
        Return False
    End Function
    
    0 讨论(0)
提交回复
热议问题