language-agnostic - 在数字集合中寻找最接近的匹配

标签 language-agnostic code-golf

关闭。这个问题需要更多focused .它目前不接受答案。




6年前关闭。










锁定。这个问题及其答案是locked因为这个问题是题外话,但具有历史意义。它目前不接受新的答案或互动。








所以我今天被问到在一个集合中找到最接近匹配的最好方法是什么。

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

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

什么数字最接近 4?

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

让我们看看我们可以从各种选择的语言中想出什么。

最佳答案

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

关于language-agnostic - 在数字集合中寻找最接近的匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/445782/

相关文章:

algorithm - 使用 OpenCV 跟踪用户定义的点

c - 计算第 n 个素数的最短方法是什么?

bash - 如何使用 cat 进行编程?

language-agnostic - 语言绑定(bind)如何工作?

algorithm - 检查一个单词是否由一个或多个串联的字典单词组成

language-agnostic - 使用按位运算符检查整数是否为 2^1-2^j 形式的单行代码

python 高尔夫 : what's the most concise way of turning this list of lists into a dictionary:

function - 说出该函数的名称! (因为我不能)

language-agnostic - Code Golf : Playing Tetris

language-agnostic - 将字符串转换为摩尔斯电码