+1 vote

I have an simple array:

numberarray = [6, 2, 10, 18, 11, 4, 20]
number = 15
result should be number_array [3]

I'm trying to return the closest number to 15. Thanks for the help!

in Engine by (61 points)

1 Answer

0 votes

An algorithm comparing the differences in a loop.

A very basic idea for that would be:

extends Node2D

const INT_MAX = 2147483647

func find_closest(match, array):

    var best_match = null
    var least_diff = INT_MAX

    for number in array:

        var diff = abs(match - number)

        if(diff < least_diff):
            best_match = number
            least_diff = diff

    return best_match

func _ready():

    var data = [6, 2, 10, 18, 11, 4, 20]
    print(find_closest(15, data))
by (5,215 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.