在数字集合中查找最接近的匹配项 [英] Finding closest match in collection of numbers

查看:88
本文介绍了在数字集合中查找最接近的匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我今天被问到在集合中查找平局匹配的最佳方法是什么.

So I got asked today what was the best way to find the closes match within a collection.

例如,您有一个像这样的数组:

For example, you've got an array like this:

1, 3, 8, 10, 13, ...

哪个数字最接近4?

集合是数字的,无序的,可以是任何东西.与要匹配的数字相同.

Collection is numerical, unordered and can be anything. Same with the number to match.

让我们从各种选择的语言中了解我们能提供什么.

Lets see what we can come up with, from the various languages of choice.

推荐答案

J中的11个字节:

C=:0{]/:|@-

示例:

>> a =: 1 3 8 10 13
>> 4 C a
3
>> 11 C a
10
>> 12 C a
13

我对外行的细分:

0{         First element of
]          the right argument
/:         sorted by
|          absolute value 
@          of
-          subtraction

这篇关于在数字集合中查找最接近的匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆