정렬 후 배열의 인덱스를 가져옵니다.


14

오늘 과제는 목록을 가져 와서 정렬 된 각 연속 요소가 나타나는 l위치를 제공 하는 프로그램이나 함수를 작성하는 것 입니다.ll

즉, 가장 작은 값의 색인을 출력 한 다음 두 번째로 작은 값의 색인 등을 출력하십시오.

입력 배열은 양의 정수만 포함하고 하나 이상의 요소를 포함한다고 가정 할 수 있습니다.

테스트 사례 :

Input                  | Output (1-indexed)
[7, 4, 5]              | [2, 3, 1]
[1, 2, 3]              | [1, 2, 3]
[2, 6, 1, 9, 1, 2, 3]  | [3, 5, 1, 6, 7, 2, 4]
[4]                    | [1]

동일한 값을 가진 두 개 이상의 요소가 나타나면 해당 인덱스가 가장 작은 것부터 가장 큰 것까지 나란히 나타납니다.

이것은 이며 가장 적은 바이트 수입니다!


16
-1 일반적인 골프 언어, 내장 기능으로 해결 될 수있는 사소한 반칙 24 시간 미만의 답변을 수용합니다. 이것은 공정한 도전도 아니고 흥미로운 것도 아닙니다.
코디 그레이

3
글쎄, 나는 왜 그가 24 시간 안에 대답을 받아들 였는지 알 수있다.
Zacharý

3
@CodyGray 1-2 바이트의 대답을 볼 때 하향 조정을 생각했지만 실제로는 표준 프로그래밍 언어에 대한 나쁜 도전이라고 생각하지 않습니다. 물론 어려운 도전은 아니지만 여전히 골프 가능성이 있습니다. 물론 1 바이트 내장 기능을 보는 것은 좋지 않지만, 그에 대한 도전을 비난하는 것이 공정하다고 생각하지 않습니다.
Dada

1
1 문자 내장을 사용하는 것은 거의 연습이 아닙니다. 쉬운 것이 반드시 내장 만 사용하여 해결할 수있는 것은 아닙니다.
JAD

2
이러한 경우에 가장 좋은 해결책은 어쨌든 관련성이없는 te accept 기능을 잊는 것입니다.
Mr. Xcoder

답변:



11

Dyalog APL, 1 바이트

Dyalog APL에는이를 위해 내장 된 연산자 기능 (이를 정리해 준 Zacharý에게 감사드립니다)이 있습니다.

⍋11 2 4 15
    2 3 1 4  
{⍵[⍋⍵]}11 4 2 15
    2 4 11 15

여기에서는 정렬 된 인덱스로 목록을 색인하여 오름차순으로 목록을 반환합니다.


오, 혼란스러운 용어를 경고하기 위해 APL에서 내장 은 기능으로 간주되는 반면 ¨⍨⍣.∘/\⌿⍀⌸⍤연산자 와 같은 것은 연산자 로 간주됩니다 .
Zacharý



9

자바 스크립트 (ES6), 39 바이트

@powelles 덕분에 -2 바이트

이것은 Array.prototype.sort안정적인 브라우저에서만 작동합니다 .

a=>[...a.keys()].sort((b,c)=>a[b]-a[c])

1 색인 버전 (47 바이트) :

a=>a.map((_,i)=>i+1).sort((b,c)=>a[b-1]-a[c-1])

코드 스 니펫 예제 :

f=
a=>[...a.keys()].sort((b,c)=>a[b]-a[c])
console.log("7,4,5 => "+f([7,4,5]))
console.log("1,2,3 => "+f([1,2,3]))
console.log("2,6,1,9,1,2,3 => "+f([2,6,1,9,1,2,3]))
console.log("4 -> "+f([4]))


[...a.keys()]대신 a.map((_,i)=>i)몇 바이트를 절약 할 수 있습니다.
powelles

7

파이썬 2 , 48 바이트

lambda x:sorted(range(len(x)),key=x.__getitem__)

온라인으로 사용해보십시오!


좋았어요.> _ <. 나는 기분이 나쁘지 않도록 파이썬 3으로 답을 바꿨다
Mr. Xcoder

4
@ Mr.Xcoder 글쎄, 그게 그의 일이야 ...
Neil

@ Mr.Xcoder 자, 당신은 그것에 대해 기분 나쁘게해서는 안됩니다! 당신은 완전한 프로그램을 만들고, 기능을 만들었고, 나의 접근 방식은 조금 다릅니다.
Outgolfer Erik

나는 기분 나쁘지 않다, 나는 이것이 나타날 것이라는 것을 알았다 (나는 개인적으로 __<blahblah>__구문을 싫어한다 ). 나는 약간의 젤리를 할 것이다, 나는 나의 훈련을 잃고 싶지 않다 :)
Mr. Xcoder

1
@ Mr.Xcoder Codegolf는 구문과 형식을 의미하지 않습니다. ;)
Outgolfer 에릭



4

스위프트 4 , 82 바이트

func f(l:[Int]){var l=l;for k in l.sorted(){let a=l.index(of:k)!;print(a);l[a]=0}}

테스트 스위트.

설명

Swift l.sorted()에서 원본 배열의 정렬 된 사본을 만듭니다. 우리는 목록에서 정렬 된 요소를 반복하고 원래 배열에서 각 항목의 인덱스를로 인쇄 let a=l.index(of:k)!;print(a)한 다음 배열 에서 올바른 인덱스를 유지하기 위해 일반 출력에 영향을 미치지 않기 때문에에 할당 l[a]합니다 0.


이것은 파이썬 솔루션의 포트이기 때문에 0 인덱스입니다. 당신이 1 인덱스 싶은 경우에, 교체 print(a)print(a+1)또는 온라인으로보십시오! .


4

R , 5 바이트

이를위한 내장 함수가 있습니다.

order

3
표준 규칙은 기능 프로그램을 제공하는 것입니다. order는 이미 함수이므로를 사용하여 입력을 처리 할 필요가 없습니다 scan(). 이것은 5 바이트입니다.
JAD

rank()바이트를 저장합니다
gstats

1
rank@JarkoDubbeldam 의 답변 이 있다고 확신 하지만 더 이상 볼 수 없습니다.
djhurio

1
맞습니다. 사양을 따르지 않으므로 삭제했습니다.
JAD




3

Octave, 17 bytes

@(i)[~,y]=sort(i)

Try it online!

Octave is like MATLAB but with inline assignment, making things possible that gives the folks at Mathworks HQ headaches. It doesn't matter what you call y, but you can't do without that dummy variable, as far as I know.


3

MY, 3 bytes

MY also has a builtin for this!

⎕⍋↵

Try it online!

How?

Evaluated input, grade up, then output with a newline.

Indexed however you set the index, with /0x48. (Can even be some weird integer like -1 or 2, the default is 1).


3

Java 8, 128 + 19 = 147 bytes

Based on Mr. Xcoder's solution. 0-based. Lambda takes input as an Integer[] and returns Integer[]. Byte count includes lambda expression and required import.

import java.util.*;

l->{Integer o[]=l.clone(),s[]=l.clone(),i=0;for(Arrays.sort(s);i<l.length;)l[o[i]=Arrays.asList(l).indexOf(s[i++])]=0;return o;}

Try It Online

Ungolfed lambda

l -> {
    Integer
        o[] = l.clone(),
        s[] = l.clone(),
        i = 0
    ;
    for (Arrays.sort(s); i < l.length; )
        l[o[i] = Arrays.asList(l).indexOf(s[i++])] = 0;
    return o;
}

Notes

I use Integer[] instead of int[] to allow use of Arrays.asList, which has no primitive versions. Integer is preferred to Long because values are used as array indices and would require casting.

This ended up being shorter than my best procedural-style List solution because of the cost of class and method names.

This also beat a solution I tried that streamed the inputs, mapped to (value, index) pairs, sorted on values, and mapped to indices, mostly because of the baggage needed to collect the stream.

Acknowledgments

  • -5 bytes thanks to Nevay

1
You don't need j: l->{Integer o[]=l.clone(),s[]=l.clone(),i=0;for(Arrays.sort(s);i<l.length;l[o[i]=Arrays.asList(l).indexOf(s[i++])]=0);return o;} (19+128 bytes).
Nevay

2

Common Lisp, 82 bytes

(lambda(l)(loop as i in(sort(copy-seq l)'<)do(setf(elt l(print(position i l)))0)))

Try it online!




2

MATLAB / Octave, 29 bytes

[~,y]=sort(input(''));disp(y)

Try it online!


While your answer is perfect MATLAB, you can actually do inline assignment in anonymous functions in Octave.
Sanchises

Good one! I knew about in-line assignment, but I didn't know you could output directly like that
Luis Mendo

1
To be honest, me neither. I started with something like @(X)([~,y]=sort(X)), and while I was looking of a way to get y from this, I realized y was actually the return value from the assignment, and closer inspection revealed that brackets weren't even needed. MATLAB likes everything explicit; Octave is happy when it's unambiguous.
Sanchises

2

JavaScript (ES6), 69 bytes

0-indexed. Works for lists containing up to 65,536 elements.

a=>[...a=a.map((n,i)=>n<<16|i)].sort((a,b)=>a-b).map(n=>a.indexOf(n))

Test cases


Can you change n=>a.indexOf(n) to just a.indexOf?
Zacharý

@Zacharý Unfortunately not. A method of an instanced object cannot be used as a callback.
Arnauld

@Zacharý Even worse is that Array#map passes 3 arguments to the callback function, and Array#indexOf expects 2, so it will give undesirable results.
kamoroso94


2

Husk, 10 7 bytes

This is a direct port of my Haskell answer, also 1-indexed:

m→O`z,N

Try it online!

Ungolfed/Explained

Code        Description               Example
         -- implicit input            [2,6,1]
      N  -- natural numbers           [1,2,3,..]
   `z,   -- zip, but keep input left  [(2,1),(6,2),(1,3)]
  O      -- sort                      [(1,3),(2,1),(6,2)]
m→       -- keep only indices         [3,1,2]

2

Java (OpenJDK 8), 72 bytes

l->l.stream().sorted().map(i->{int j=l.indexOf(i);l.set(j,0);return j;})

Try it online!

Takes a List<Integer>, returns a Stream<Integer> containing the results.

We get a Stream based off the initial list, sort it, then map each number to it's index in the list. In order to accommodate duplicate elements, we set the original element in the list to 0.


2

SmileBASIC, 67 bytes

DEF I(A)DIM B[0]FOR I=1TO LEN(A)PUSH B,I
NEXT
SORT A,B
RETURN B
END

Very simple, all it does is generate a list of numbers from 1 to (length of array) and sort this by the same order as the input.


2

Python 3 with Numpy, 38 26 bytes

12 bytes saved thanks to Jo King (no need to give the function a name)

import numpy
numpy.argsort

Output is 0-based.

Try it online!


The function could just be numpy.argsort without the lambda part
Jo King

@JoKing Thanks for the suggestion. I wrote it that way because with just numpy.argsort;import numpy I get an error (numpy has not been imported yet), and with import numpy;numpy.argsort I need to move f= to the code part. Do you know that the standard procedure is in these cases? Move the f= and not count it?
Luis Mendo

Yeah, I guess. Maybe just redefine f=numpy.argsort in the footer
Jo King

@JoKing Good idea. Done. Thanks!
Luis Mendo



1

PHP, 54 bytes

<?php function i($a){asort($a);return array_keys($a);}

Try it online!

This is zero-indexed. Simply sorts the array and returns the keys.


1
The <?php tag is unnecessary for a function. 48 bytes.
Titus

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.