Results 1 to 10 of 10

Thread: [RESOLVED] Find Closest Match

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Apr 2007
    Posts
    86

    Resolved [RESOLVED] Find Closest Match

    I have a list of numbers:

    Code:
    100,125,150,175,200,225,250,300,350,400,450,500,600,700,800,900,1000
    I do some maths and get a result. I need to workout somehow which one of those numbers above is closest to the RESULT number.

    For example if the result was 620 it would be closer to 600 but if it was 678 it would be closer to 700.

    Any suggestions?

  2. #2
    Frenzied Member MaximilianMayrhofer's Avatar
    Join Date
    Aug 2007
    Location
    IM IN YR LOOP
    Posts
    2,001

    Re: Find Closest Match

    Sort + modified binary search.

    If you want something better, then by all means supply more information about the 'some maths' that you're planning to do.

  3. #3
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: Find Closest Match

    How the number is arrived at is irrelevant... what is relevant is the result: 620....

    To get the closest number first you need to find the two numbers on either end... which should be simple with a binary search, or a simple loop until where valueArray(i) <= 620 and valueArray(i+1) > 620.... that gives you the 600 and 700... Then all you need to do is take the difference between your end numbers and your number and the one with the lowest difference is your closer number.
    620 - 600 = 20
    700- 620 = 80
    since 20 < 80... 600 is your closer number.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  4. #4
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: Find Closest Match

    Code:
            'create list of numbers
            Dim lstOnums As New List(Of Integer)
            lstOnums.AddRange(New Integer() {100, 125, 150, 175, 200, 225, 250, 300, 350, 400, 450, 500, 600, 700, 800, 900, 1000})
    
            'add result to the list, and sort
            Dim rslt As Integer = 620
            lstOnums.Add(rslt)
            lstOnums.Sort()
    
            'get the index of the result.  
            Dim idx As Integer = lstOnums.IndexOf(rslt)
            'a couple of checks here and you should have your answer
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  5. #5
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,415

    Re: Find Closest Match

    try this:

    vb Code:
    1. Public Class Form1
    2.  
    3.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    4.         Dim numbers() As Integer = {100, 125, 150, 175, 200, 225, 250, 300, 350, 400, 450, 500, 600, 700, 800, 900, 1000}
    5.         Dim closest As Integer
    6.         Dim closestDifference As Integer = Integer.MaxValue
    7.         Dim inputNumber As Integer
    8.         If Integer.TryParse(TextBox1.Text, inputNumber) Then
    9.             For x As Integer = 0 To numbers.GetUpperBound(0)
    10.                 If Math.Abs(inputNumber - numbers(x)) < closestDifference Then
    11.                     closestDifference = Math.Abs(inputNumber - numbers(x))
    12.                     closest = numbers(x)
    13.                 End If
    14.             Next
    15.             MsgBox(closest)
    16.         End If
    17.     End Sub
    18.  
    19. End Class

  6. #6
    Frenzied Member MaximilianMayrhofer's Avatar
    Join Date
    Aug 2007
    Location
    IM IN YR LOOP
    Posts
    2,001

    Re: Find Closest Match

    Quote Originally Posted by techgnome
    How the number is arrived at is irrelevant... what is relevant is the result: 620....
    That's a little short-sighted. How the number is reached is NOT irrelevant if the closest number can be determined within the algorithm that creates the result. This can potentially reduce complexity from O(n) to O(log_n), which is significant for larger data sets.

  7. #7
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: Find Closest Match

    The user enters the number.
    The user enters a number, and it's doubled.
    It generates a random number between 1 and 12million, the ARC and COS is taken, summed, squared, cubed-root.

    If the requirement it to take a number as an input and, given a set of other numbers, find the closest... do we care how that input number was derived? maybe in the large scheme things, but for the sake of arguement, let's say that this "nearest" function IS being inserted in to said algorithm you mentioned... after all... that IS what we are trying to do here, right? find the closest number? for purposes of the function, we don't care how it gets called or where from. All the function should be concerned about is, given a set of numbers, and an input number, find the closest from the list.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  8. #8
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: Find Closest Match

    Code:
    Module module1
    
        Dim aRnd As New Random
        Public Sub Main()
            'this
            'lstOnums.AddRange(New Integer() {100, 125, 150, 175, 200, 225, 250, 300, 350, 400, 450, 500, 600, 700, 800, 900, 1000})
            'or this
            For x As Integer = 100 To 1000 Step 25
                lstOnums.Add(x)
            Next
            '
            '
            Dim rslt As Integer = 100
            Console.WriteLine("The closest to {0} is {1}", rslt, closest(rslt))
            rslt = 1000
            Console.WriteLine("The closest to {0} is {1}", rslt, closest(rslt))
            Dim stpw As New Stopwatch
            For x As Integer = 1 To 20
                rslt = aRnd.Next(100, 1001)
                stpw.Reset()
                stpw.Start()
                Dim clsts As Integer = closest(rslt)
                stpw.Stop()
                Console.WriteLine("The closest to {0} is {1}   in {2} ticks", rslt, clsts, stpw.ElapsedTicks)
            Next
            Console.ReadLine()
        End Sub 'Main
    
        Dim lstOnums As New List(Of Integer)
    
        Private Function closest(ByVal rslt As Integer) As Integer
            'create list of numbers
    
            'add result to the list, and sort
            lstOnums.Add(rslt)
            lstOnums.Sort()
    
            'get the index of the result.  
            Dim idx As Integer = lstOnums.IndexOf(rslt)
    
            'a couple of checks here and you should have your answer
            Dim rv As Integer
            If idx = 0 Then 'is it first item in list
                rv = lstOnums(1)
            Else 'determine which neighbor is closest
                Dim dl As Integer = lstOnums(idx) - lstOnums(idx - 1)
                Dim dh As Integer = lstOnums(idx + 1) - lstOnums(idx)
                If dl >= dh Then rv = lstOnums(idx + 1) Else rv = lstOnums(idx - 1)
            End If
            lstOnums.RemoveAt(idx) 'remove the number we added
            Return rv
        End Function
    End Module
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  9. #9
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    Re: Find Closest Match

    Well, is the array originally sorted? Sorting it, then performing a binary search would be less efficient than just looping through like .paul. did...

  10. #10

    Thread Starter
    Lively Member
    Join Date
    Apr 2007
    Posts
    86

    Re: Find Closest Match

    This works perfectly! Thank you!!!

    Quote Originally Posted by .paul. View Post
    try this:

    vb Code:
    1. Public Class Form1
    2.  
    3.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    4.         Dim numbers() As Integer = {100, 125, 150, 175, 200, 225, 250, 300, 350, 400, 450, 500, 600, 700, 800, 900, 1000}
    5.         Dim closest As Integer
    6.         Dim closestDifference As Integer = Integer.MaxValue
    7.         Dim inputNumber As Integer
    8.         If Integer.TryParse(TextBox1.Text, inputNumber) Then
    9.             For x As Integer = 0 To numbers.GetUpperBound(0)
    10.                 If Math.Abs(inputNumber - numbers(x)) < closestDifference Then
    11.                     closestDifference = Math.Abs(inputNumber - numbers(x))
    12.                     closest = numbers(x)
    13.                 End If
    14.             Next
    15.             MsgBox(closest)
    16.         End If
    17.     End Sub
    18.  
    19. End Class

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width