Uzyskaj indeksy tablicy po posortowaniu


14

Twoim wyzwaniem jest dziś napisanie programu lub funkcji, która pobiera listę li podaje pozycje, w lktórych lpojawia się każdy kolejny posortowany element .

Innymi słowy, wypisz indeks najmniejszej wartości, a następnie indeks drugiej najmniejszej wartości itp.

Możesz założyć, że tablica wejściowa będzie zawierać tylko dodatnie liczby całkowite i będzie zawierać co najmniej jeden element.

Przypadki testowe:

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]

Kiedy pojawią się dwa lub więcej elementów o tej samej wartości, ich wskaźniki powinny pojawić się obok siebie od najmniejszej do największej.

To jest , wygrywa najmniej bajtów!


16
-1 za trywialne wyzwanie, które można rozwiązać za pomocą wbudowanych popularnych języków golfowych, oraz za zaakceptowanie odpowiedzi w mniej niż 24 godziny. To nie było ani uczciwe, ani interesujące wyzwanie.
Cody Gray

3
Rozumiem, dlaczego przyjął odpowiedź w ciągu 24 godzin, nie da się jej pokonać.
Zacharý

3
@CodyGray Zastanawiałem się nad oddaniem głosu, gdy zobaczyłem odpowiedź na 1-2 bajty, ale tak naprawdę nie sądzę, że jest to złe wyzwanie dla bardziej standardowych języków programowania. Oczywiście nie jest to trudne wyzwanie, ale z pewnością istnieją pewne możliwości gry w golfa. Oczywiście, nieprzyjemnie jest widzieć wbudowane 1-bajty, ale nie sądzę, aby można było winić za to wyzwanie.
Dada

1
Używanie wbudowanej 1 postaci nie jest ćwiczeniem. Łatwość niekoniecznie oznacza rozwiązanie problemu przy użyciu tylko wbudowanych funkcji.
JAD,

2
Najlepszym rozwiązaniem w takich przypadkach jest zapomnienie o funkcji akceptującej, która tak naprawdę nie jest tutaj istotna.
Pan Xcoder,

Odpowiedzi:



11

Dyalog APL, 1 bajt

Dyalog APL ma wbudowaną funkcję operatora (dziękuję Zacharý za wyjaśnienie tego), aby to zrobić.

Przykład

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

Tutaj indeksuję listę według posortowanych indeksów, aby zwrócić listę w porządku rosnącym.


Och, żeby ostrzec cię o mylącej terminologii, w APL, wbudowane podobne są uważane za funkcje, podczas gdy podobne ¨⍨⍣.∘/\⌿⍀⌸⍤są operatorami.
Zacharý



9

JavaScript (ES6), 39 bajtów

-2 bajty dzięki @powelles

Działa to tylko w przeglądarkach, w których Array.prototype.sortjest stabilny.

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

Wersja 1-indeksowana (47 bajtów):

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

Przykładowy fragment kodu:

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()]zamiast a.map((_,i)=>i)zaoszczędzi ci kilka bajtów.
powelles

7

Python 2 , 48 bajtów

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

Wypróbuj online!


Fajnie, zostałem rozegrany> _ <.
Zmieniłem

4
@ Mr.Xcoder Cóż, to jego praca ...
Neil

@ Mr.Xcoder Chodź, nie powinieneś się z tego powodu źle czuć! Stworzyłeś pełny program, ja stworzyłem funkcję, a moje podejście jest trochę inne.
Erik the Outgolfer,

Nie czuję się źle, wiedziałem, że to się pojawi (osobiście nienawidzę __<blahblah>__składni). Zrobię trochę galaretki, nie chcę stracić szkolenia :)
Mr. Xcoder

1
@ Mr.Xcoder Codegolf nie oznacza ładnej składni i formatowania. ;)
Erik the Outgolfer



4

Swift 4 , 82 bajtów

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

Pakiet testowy.

Wyjaśnienie

W Swift l.sorted()tworzy posortowaną kopię oryginalnej tablicy. Przechodzimy przez posortowane elementy na liście i po wydrukowaniu indeksu każdego elementu w oryginalnej tablicy za pomocą let a=l.index(of:k)!;print(a), a następnie, aby zachować prawidłowe indeksy w tablicy, przypisujemy l[a]do 0, ponieważ nie wpływa to na nasze normalne wyniki.


Take note that this is 0-indexed, since it is a port of my Python solution. If you want it to be 1-indexed, replace print(a) with print(a+1) or Try it online!.


4

R, 5 bytes

There is a builtin function for this.

order

3
Standard rules is to provide a program of function. order is already a function, so you don't have to handle input using scan(). This would be 5 bytes.
JAD

rank() would save a byte
gstats

1
I am sure there was a rank answer by @JarkoDubbeldam, but I do not see it anymore.
djhurio

1
Correct, it does not follow the spec so I deleted it.
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

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

Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.