numberに最も近い値を取得します


16

このコードゴルフでは、リスト内の別の番号から最も近い番号を取得する必要があります。

出力は、入力に最も近い番号になる場合があります。

例:

value: (Input) 5 --- [1,2,3] --- 3

また、プログラムは負の数で動作する場合があります。

例:

value: (Input) 0 --- [-1,3,5] --- -1


value: (Input) 2 --- [1, 5, 3] --- 1 (Because it gives priority to lower numbers)

ルール:

前述のように、負の数を処理する必要があります。

2つの回答がある場合(例:0-[5、-5])、プログラムは最も低い番号を優先します。(-5)

これはコードゴルフなので、最短のコードが勝ちます!


6
それはルールで言及されるべきであるより低い数字を優先します。
デニス

ターゲット番号がリストに存在する場合、出力はその番号またはリストから最も近い他の番号ですか?
-trichoplax

受け入れられた答えは一時的なものです。
AlexINF

4
Alex82確かに@、あなたはより良い1が入る場合は、受け入れ答えを変更するだろうことを知っているが、一部の人は残念ながらありませんすべての挑戦の作者が後半の答えへの気配りがあるので、すでに、受け入れ答えを持ってチャレンジすることによって延期されています。だから、早期に受け入れることは実際に悪いかどうかではなく、人々が間違った印象を与えるかどうかについてではない。
マーティンエンダー

1
入力番号は整数ですか?
randomra

回答:


6

Pyth、6バイト

haDQSE

テストスイート

STDINで次の形式で入力します。

num
array

説明:

haDQSE
          Implicit: Q = eval(input()) (num)
     E    Evaluate input (array)
    S     Sort (smaller values to the front)
 aDQ      Sort by absolute difference with Q.
h         Take the first element of the sorted list, the min.
          Print implicitly.

6

ルビー、34バイト

->n,a{a.sort.min_by{|x|(n-x).abs}}
a.sort       min_by tiebreaks by position in array, so put smaller numbers 1st
.min_by{|x|  select the element which returns the smallest val for predicate...
(n-x).abs}   (absolute) difference between input num and element

1
min_byはすでにminからmaxにソートしているので、#sortは必要ないと思います。だから、それはさらに短くすることができます:->n,a{a.min_by{|x|(n-x).abs}}
TiSer

4

Mathematica、12バイト

Min@*Nearest

ビルトインFTW!Buettnerの説明:「Mathematicaにはこれが組み込まれNearestていますが、すべての同点の数のリストが返されます。そのため、Min同点を破るためにそれを構成する必要があります。」


7
それは...私が説明を書くために得るものだ
マーティン・エンダー

1
「オンラインで試す」を追加してもらえますか?
AlexINF

1
@ Alex82 Mathematica(プロプライエタリ)である可能性は低いようです。
マーティンエンダー



2

JavaScriptのES6、64の 56 54バイト

(i,a)=>a.sort((a,b)=>s(i-a)-s(i-b)||a-b,s=Math.abs)[0]

オンラインで試す

2バイトを節約してくれた@Nielに感謝

テストスニペット:

f=(i,a)=>a.sort((a,b)=>s(i-a)-s(i-b)||a-b,s=Math.abs)[0];

[
  [5, [1, 2, 3]],
  [2, [3, 5, 1]],
  [2, [1, 3, 5]],
  [0, [-1, 2, 3]],
  [5, [1, 2, 3]]
].map(v=>O.textContent+=JSON.stringify(v)+": "+f.apply(null,v)+"\n")
<pre id=O></pre>


ソートを組み合わせることで2バイトを節約します(i,a)=>a.sort((a,b)=>s(i-a)-s(i-b)||a-b,s=Math.abs)[0]
ニール

関数をカリー化することでバイトを保存できます:i=>a=>...それf(i)(a)があなたの呼び出し方です。
パトリックロバーツ

@PatrickRobertsこの場合、OPは値をとる関数(またはsimulere)を要求しているため、noと言います:inputand list / array / ... as integers
andlrc

2

ゼリー、7 6バイト

ạżṛỤḢị

オンラインでお試しください!

使い方

ạżṛỤḢị Main link. Left input: n (number). Right input: A (list)

ạ      Take the asbolute difference of n and the items of A.
  ṛ    Yield the right argument, A.
 ż     Zip the left result with the right one.
       This pairing causes ties in absolute value to be broken by initial value.
   Ụ   Grade up; sort the indices of the resulting list by their associated values.
    Ḣ  Retrieve the first index, which corresponds to the smallest value.
     ị Retrieve the item of A at that index.

1

MATL、10バイト

Sti-|4#X<)

オンラインでお試しください!

S       % implicitly input array, and sort. This ensures smaller numbers have priority
t       % duplicate
i       % input number
-|      % compute array of absolute differences
4#X<    % arg min. If there are several minimizers, the position of the first is returned
)       % index into original array. Implicitly display

1

Python 2、56バイト

a=input()
print sorted(input(),key=lambda x:abs(a-x))[0]

最初にターゲット番号を取得しますa=input()-これは変数に保存する必要があります。

次に、関数をlambda x:abs(a-x)適用して入力をソートします(考えますmap(lambda x:abs(a-x), input())

次に、値が重複する場合に最小値を取ります


0

TeaScript、10バイト

T#(y-l)a)░

TeaScriptは配列入力をサポートしていないため、コンソールでrun:TeaScript("T#y-la)░", [[1, 2, 3], 1], {}, TEASCRIPT_PROPS)to runthisを実行します。

説明

T#  // Sort input by...
  (y-l)a // absolute difference with input
)░  // First item in array


0

Haskell、38バイト

e#l=snd$minimum$(zip=<<map(abs.(e-)))l

使用例:2 # [1,5,3]->1

入力リスト内の各要素のl入力番号を持つ要素の絶対差の一対するeと素子自体を、例えばe=2l=[1,5,3]> - [(1,1),(3,5),(1,3)]。最小値を見つけて、差を捨てます。


0

zsh、75 73 71 70 67バイト

for n in ${@:2};{echo "$[$1-n]    $n"}|tr -d -|sort -n|head -1|cut -f2

入力をコマンドライン引数として期待します。

の4つのスペースechoは実際にはタブであることになっていますが、Stack Exchangeはすべての投稿でタブをスペースに変換します。

for 構文のため、Bash互換ではありません。

for n in ${@:2};      for each argument except the first...
{echo "$[$1-n]\t$n"}  output the difference from the first argument
                        and then the original number
|tr -d -              poor man's abs()
|sort -n              sort by first num (difference), tiebreaking by second num
                        (original value)
|head -1              take the thing that sorted first
|cut -f2              print field 2 (aka discard the difference)

2バイトのdev-nullに感謝します!


弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.