# Indices of elements in an array in order from smallest to largest [duplicate]

Basically you have an array of random integers e.g.

I() = [1, 4, 3, 2, 5, 3, 2, 1]


and you have to create another array of the same length with the numbers 1 to the size of the array in place of the smallest to largest numbers respectively, e.g.

O() = [1, 7, 5, 3, 8, 6, 4, 2]


For duplicates, the first occurrence is taken as the smaller of the indices.

Test Cases:

Input:   I() = [1, 5, 3, 4, 5, 3, 2, 4]
Output:  O() = [1, 7, 3, 5, 8, 4, 2, 6]

Input:   I() = [1, 5, 3, 2, 5, 3, 2, 4, 6, 6, 5]
Output:  O() = [1, 7, 4, 2, 8, 5, 3, 6, 10, 11, 9]


Rules

1. It should work with array of any finite length

2. All integers are positive(greater than 0)

3. This is , so the submission with the least amount of bytes wins!

• I feel like this must be a duplicate. – Greg Martin Apr 13 '17 at 6:12
• @GregMartin I am not sure I am new to golf code so if you can find the link to the same question on golf code I'd be happy to remove this question from here. – Stupid_Intern Apr 13 '17 at 6:14
• Related. (The opposite operation in a way.) (Edit: Actually, it's the same thing...) – Martin Ender Apr 13 '17 at 6:21
• Can we assume some upper bound on the input values and list length like 255 or so? – Martin Ender Apr 13 '17 at 7:16
• @MartinEnder Yes I think 255 is okay – Stupid_Intern Apr 13 '17 at 7:17

f l|z<-zip l[0..]=[sum[1|q<-z,p>=q]|p<-z]


Try it online!

Haskell doesn't have build-in sorting, so we have to roll up our sleeves. We pair each element with its index with z<-zip l[0..], then for each pair counts the number of pairs that are smaller or equal. This first compares the values, then tiebreaks by their index.

# Bash + coreutils, 28

f()(nl|sort -k2)
f|f|cut -f1


# Dyalog APL, 2 bytes

⍋⍋

⍋ is the symbol for grade up - return a permutation that sorts the argument. Applied twice, it does what's asked for in this problem. Indices in Dyalog are 1-based by default.

# JavaScript (ES6), 96 bytes

f=(a,b=a.length,c=[...Array(b)])=>(m=a.lastIndexOf(Math.max(...a)),a[m]=0,c[m]=b--,m?f(a,b,c):c)


f=(a,b=a.length,c=[...Array(b)])=>(m=a.lastIndexOf(Math.max(...a)),a[m]=0,c[m]=b--,m?f(a,b,c):c)

console.log(f([1, 5, 3, 4, 5, 3, 2, 4]));

# Ruby, 35 bytes

->a{a.zip(1..999).sort.map{|x,y|y}}


Try it online!