stringlanguage-agnosticlistcoldfusioncode-golf

What's the most efficient way to find the length of the longest item in a list?


Given a list of assorted length words, what is the best way to find the maximum length of any words?

For example, the following should return 6

findMaxLen("a,set,of,random,words")


Of course, it's fairly trivial to do this...

<cffunction name="findMaxLen" returntype="Numeric">
    <cfset var CurMax = 0 />
    <cfset var CurItem = 0 />
    <cfloop index="CurItem" list="#Arguments[1]#">
        <cfif Len(CurItem) GT CurMax >
            <cfset CurMax = Len(CurItem)/>
        </cfif>
    </cfloop>
    <cfreturn CurMax />
</cffunction>


Or, a little shorter...

<cffunction name="findMaxLen" returntype="Numeric">
    <cfset var CurMax = 0 />
    <cfset var CurItem = 0 />
    <cfloop index="CurItem" list="#Arguments[1]#">
        <cfset CurMax = Max( CurMax , Len(CurItem) ) />
    </cfloop>
    <cfreturn CurMax />
</cffunction>


But is there a better way - something more efficient?

Perhaps some Java method? Converting to array and sorting by item length? Counting the biggest gap between commas?


In practical terms, either of the above two examples will work fine for my current need, and this isn't for something that is performance critical, so I don't need an answer to this, but I thought it would still be interesting to see what people might come up with...


Solution

  • Count the distance between commas.

    I don't think anything could be faster than that; it's O(n), and you have to look at each character at least once anyway (to see if it's a comma).

    int FindLongestWord(char* str)
    {
       char* lastComma = str - 1;
       int longest = 0;
       int length;
       char* pCheckChar;
    
       for(pCheckChar = str; *pCheckChar; pCheckChar++)
       {
          if(*pCheckChar == ',')
          {
             length = pCheckChar - lastComma - 1;
             if(length > longest)
             {
                longest = length;
             }
    
             lastComma = pCheckChar;
          }
       }
    
       // Check to see if the last word is the longest
       length = pCheckChar - lastComma - 1;
       if(length > longest)
       {
          longest = length;
       }
    
       return longest;
    }
    

    or I suppose you could just say

    "a,set,of,random,words".Split(',').Max(w=>w.Length);
    

    if we're playing games... ;]