Search code examples
juliaargmax

Is argmax working properly for an array of Strings?


I'm using the function Argmax to get the string with max size in an array of Strings, and when the string contains a repetition of a single character, the result get weird.

For example:

x = ["ABC", "AAAA"]
argmax(x) # 1
# The return of argmax is 1, is that correct ?

x = ["ABC", "AAAABBBBCCCCDDDD"]
argmax(x) # = 1

x = ["ABC", "AAAABBBBCCCCDDDD", "ABCD"]
argmax(x) # = 3

Solution

  • The strings are compared lexicographically here, not by their length.

    For this reason "ABC" is considered to be greater than "AAAA", and so the maximum element in the array ["ABC", "AAAA"] is indeed at index 1.

    If your goal is to compare the strings by length, you could apply the length function to each of the strings in the array and then use argmax. For example:

    julia> x = ["ABC", "AAAABBBBCCCCDDDD", "ABCD"]
    julia> argmax(length.(x))
    2