숫자에 가장 가까운 값 얻기


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)

규칙 :

앞에서 언급했듯이 음수로 작동해야합니다.

두 가지 답변이있는 경우 (예 : 0-[5, -5]) 프로그램은 가장 낮은 숫자에 우선 순위를 부여합니다. (-5)

이것은 코드 골프이므로 가장 짧은 코드가 승리합니다!


6
규칙에서 언급해야하는 낮은 숫자를 우선시합니다 .
Dennis

대상 번호가 목록에있는 경우 출력이 해당 번호 또는 목록에서 가장 가까운 다른 번호 여야합니까?
trichoplax

나는 대답이 일시적
AlexINF

4
Alex82 물론 @, 당신은 더 좋은 사람이 오면 당신이 허용 대답을 변경거야 알고 있지만 어떤 사람들은 불행히도 모든 도전의 저자가 늦게 대답에 그 세심한이기 때문에 이미 수락 된 대답을 도전에 의해 연기된다. 따라서 조기 수용이 실제로 나쁜지 아닌지, 사람들이 잘못된 인상을 받을지 여부는 중요하지 않습니다.
Martin Ender

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로 정렬하기 때문에 # 정렬이 필요하지 않습니다. 따라서 더 짧을 수 있습니다.->n,a{a.min_by{|x|(n-x).abs}}
TiSer

4

수학, 12 바이트

Min@*Nearest

내장 FTW! Buettner의 설명 : "Mathematica는이를 위해 내장되어 Nearest있지만 모든 묶인 숫자의 목록을 반환합니다. 따라서 Min넥타이를 끊으려면이 를 구성해야합니다 ."


7
그것이 제가 설명을 써서 얻는 것입니다 ...
Martin Ender

1
"온라인으로 사용해보십시오"를 추가 할 수 있습니까?
AlexINF

1
@ Alex82 Mathematica (독점)에는 거의 없을 것 같습니다.
Martin Ender

@ Alex82 여기에서 테스트하십시오 : lab.open.wolframcloud.com/app/view/newNotebook?ext=nb
thedude


2

자바 스크립트 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]
Neil

함수 를 카레 하여 바이트를 절약 할 수 있습니다 . i=>a=>...그러면 f(i)(a)호출하는 방식입니다.
Patrick Roberts

영업 이익은 함수 (또는 simulere) 값으로 소요를 요구하기 때문에 내가, 아니 말할 것이 경우 @PatrickRoberts : input및 목록 / 배열 / ... 정수로
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

파이썬 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

티 스크립트, 10 바이트

T#(y-l)a)░

TeaScript는 콘솔 실행에서 배열 입력을 지원하지 않으므로 실행하십시오 TeaScript("T#y-la)░", [[1, 2, 3], 1], {}, TEASCRIPT_PROPS).

설명

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

0

R, 42 바이트

x=sort(scan());x[which.min(abs(x-scan()))]

0

하스켈, 38 바이트

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

사용 예 : 2 # [1,5,3]-> 1.

입력리스트의 각 요소에 대하여 l, 입력 번호를 가진 요소의 차분 절대 쌍의 확인 e과 요소 자체를, 예를 들면 e=2, l=[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 덕분에 !


0

펄 6 , 31 바이트

{@^b.sort.sort((*-$^a).abs)[0]}

용법:

my &code = {@^b.sort.sort((*-$^a).abs)[0]}

say code 5, [1,2,3];   # 3
say code 0, [-1,3,5];  # -1
say code 2, [1, 5, 3]; # 1
say code 0, [5,-5];    # -5
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.