How to get the closest lower number in array?

Godot Version

4.3

Question

how to get the closest lower number in array?
example

var random_arr : Array[int] = [0,18,100,22,35]
var choose_num1 : int = 99
var choose_num2 : int = 10

how can i get closest number to
choose_num1 #return35
and
choose_num2 #return 0

var random_arr = [0, 18, 100, 22, 35]
var choose_num1 = get_closest_number_in_array(99, random_arr)
var choose_num2 = get_closest_number_in_array(10, random_arr)

func get_closest_number_in_array(number, array):
    var closest = array[0]
    for i in array:
        if abs(number - closest) > abs(number - i):
            closest = i
    return closest
1 Like

my bad, i type wrong number
choose_num1 = 35 and choose_num2 = 0
i want to get the lower one.

just call the method i gave you with the specific number and it will return you the closest number from the given array

i know your method will give me the closest number. but what i want is the lower closest number
example

var random_arr : Array[int] = [0,18,100,22,35]
var choose_num1 = 99

between 35 and 100
i want it to return to me is 35
the lower closest number to me. sorry my broken english

func get_lowest_closest_number_in_array(number, array):
    var closest = array.min()
    for i in array:
        if i <= number and i > closest:
            closest = i
    return closest

I think this should work now

1 Like

thank you so much

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.