在数字集合中查找最接近的匹配项
问题描述:
因此,我今天被问到在集合中查找平局匹配的最佳方法是什么.
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