Find numeric placement of letters

128 views Asked by At

Looking to find the numeric placement of letters in a random letter vector using a function equivalent to foo.

myletters = ["a","c","b","d","z"]

foo(myletters)
# [1,3,2,4,26]
2

There are 2 answers

5
mbauman On BEST ANSWER

Edit: If you're looking for the numeric distance from 'a', here's one solution:

julia> Int.(first.(["a","c","b","d","z"])) - Int('a') + 1
5-element Array{Int64,1}:
  1
  3
  2
  4
 26

It will gracefully handle unicode (those simply are later code points and thus will have larger values) and longer strings (by only looking at the first character). Capitals, numbers, and some symbols will appear as negative numbers since their code points come before a.


Previous answer: I think you're looking for sortperm. It gives you a vector of indices that, if you index back into the original array with it, will put it in sorted order.

julia> sortperm(["a","c","b","d"])
4-element Array{Int64,1}:
 1
 3
 2
 4
0
Francis Smart On

I came up with the somewhat convoluted solution:

[reshape((1:26)[myletters[i] .== string.('a':'z')],1)[1] for i=1:length(myletters)]

Or using map

map(x -> reshape((1:26)[x .== string.('a':'z')],1)[1], myletters)