27
\$\begingroup\$

Your challenge is to take an array of strings and output the longest string in the array. So for

["tiny", "small", "bigger", "biggest"]

the output would be biggest.

If two elements of the array have the same length, you should choose the one that appears first in the array. That means if the array looks like this:

["one", "two", "no"]

the output is one, but if the array looked like this:

["two", "one", "no"]

the output is two.


As this is , the shortest code in bytes wins.

\$\endgroup\$
8
  • 4
    \$\begingroup\$ 2 notes: 1 It's heavily discouraged if the question is changed and invalidates existing answer, and 2 the Sandbox exists for exactly that reason (make sure challenges are good before posting) \$\endgroup\$
    – DELETE_ME
    Commented Dec 20, 2017 at 10:54
  • 4
    \$\begingroup\$ Since I don't think anyone else has mentioned it -- Hi, and welcome to PPCG! \$\endgroup\$ Commented Dec 20, 2017 at 14:21
  • 1
    \$\begingroup\$ No you don't have to handle the case where the array is empty. But if you want you can. \$\endgroup\$
    – Doggo
    Commented Dec 20, 2017 at 14:25
  • 5
    \$\begingroup\$ 2 hours? That's far, far too quick to be accepting an answer. \$\endgroup\$
    – Shaggy
    Commented Dec 20, 2017 at 15:05
  • 7
    \$\begingroup\$ Normally you wait a week \$\endgroup\$
    – user63187
    Commented Dec 20, 2017 at 16:43

66 Answers 66

2
\$\begingroup\$

Bash, 44 bytes

IFS=$'\n';egrep -m1 .{`wc -L<<<"$*"`}<<<"$*"

Try it online!

\$\endgroup\$
0
2
\$\begingroup\$

dc, 39 38 36 bytes

0sl[slssdd]sG[dZdll!>Gooz0<M]dsMxlsp

Try it online!

Edit: -1 byte, filling up empty space by 'd' instead

Edit: -2 bytes, thanks @brhfl for suggestion!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Looks like you can shave off a byte by moving the ? input behind (or in front of) your initial 0sl instead (or, typically it is allowed to just assume the stack is input, ? can likely be omitted for another byte), and then changing sMlMx to dsMx. \$\endgroup\$
    – brhfl
    Commented Mar 23, 2018 at 20:47
  • \$\begingroup\$ @brhfl thanks for suggestion! \$\endgroup\$
    – cab404
    Commented Mar 24, 2018 at 7:07
1
\$\begingroup\$

APL+WIN, 11 bytes

s[↑⍒∊⍴¨s←⎕]

Prompts for screen input in the form 'abc' 'defg' hijklm'

\$\endgroup\$
1
\$\begingroup\$

Perl 5, 38 bytes

say((sort{$a=~y///c<=$b=~y///c}<>)[0])

Try it online!

\$\endgroup\$
1
\$\begingroup\$

C++, 125 bytes

Accepts input as a pair of iterators; returns an iterator to the longest string. The array must not be empty (i.e. the iterators must be different).

#include<algorithm>
template<class I>I f(I a,I b){return std::max_element(a,b,[](auto&a,auto&b){return a.size()<b.size();});}

Demo

#include <string>
#include <iostream>
#include <iterator>
int main()
{
    std::string strings[] = { "Programming", "Puzzles", "and", "Code", "Golf" };

    std::cout << *f(std::begin(strings), std::end(strings)) << std::endl;
}

The definition of std::max_element() guarantees that

If several elements in the range are equivalent to the greatest element, returns the iterator to the first such element.

\$\endgroup\$
1
  • \$\begingroup\$ If you're using GCC, you can use #import<regex>. \$\endgroup\$
    – DELETE_ME
    Commented Dec 24, 2017 at 3:36
1
\$\begingroup\$

Jelly, 4 bytes

LÐṀḢ

Try it online!

Maximum (ÐṀ) by length (L). Take Head ().


Jelly, 4 bytes

ṚLÞṪ

Try it online!

Reverse. Sort by length. Take tail (last element).

\$\endgroup\$
1
\$\begingroup\$

Javascript ES5, 41 bytes

Since there was already a solution using sort...

Try it online

a=>a.reduce((x,y)=>x.length>=y.length?x:y)
\$\endgroup\$
1
\$\begingroup\$

Coconut, 15 13 bytes

max$(key=len)

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Add++, 7 bytes

L,bU«bL

Try it online!

More interesting, 32 byte version:

L,vbU§bLdbLBkÞ{g}@
D,g,@,bLBK=

Try it online!

How they work

L,	; Create a lambda function
	; Example argument:         		[["two" "one" "abc" "no"]]
    bU	; Evaluate as list; 			STACK = ['two' 'one' 'abc' 'no']
    «bL	; Take the value with the max length;	STACK = ['two']

And the 32 byte version:

L,		; Create a lambda function
		; Example argument: 		['["two" "one" "no"]']
	vbU	; Evaluate;		STACK = ['two' 'one' 'no']
	§bL	; Sort by length;	STACK = ['no' 'two' 'one']
	dbLBk	; Save length;		STACK = ['no' 'two' 'one']	REGISTER = 3
	Þ{g}	; Filter by 'g';	STACK = ['two' 'one']
	@	; Reverse;		STACK = ['one' 'two']
		; Implicitly return the top element:   'two'

D,g,@,		; Create a function 'g'
		; Example argument:		['two']
	bL	; Length;		STACK =	[3]
	BK=	; Equal to register;	STACK = [1]
\$\endgroup\$
1
\$\begingroup\$

Attache, 9 bytes

MaxBy&:`#

Try it online!

This is simply bonding the size operator (`#) to the left of MaxBy. This is equivalent to:

f[x] := MaxBy[Size, x]

...which selects the first element with the largest size in x.

\$\endgroup\$
1
\$\begingroup\$

jq -r, 19 15 bytes

Golfed 4 bytes after learning min_by is a builtin.

min_by(-length)

Try it online!

(Without -r the output string is surrounded with "s.)

\$\endgroup\$
1
\$\begingroup\$

Kotlin, 21 bytes

{it.maxBy{it.length}}

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ I'm afraid that, if you don't count the whole function, it becomes a snippet, so it's invalid. \$\endgroup\$ Commented Dec 21, 2018 at 21:23
  • \$\begingroup\$ I've seen another kotlin answer somewhere else that did the same thing so I figured it might be valid; I'll switch it to a lambda \$\endgroup\$
    – snail_
    Commented Dec 22, 2018 at 4:45
1
\$\begingroup\$

Tcl, 93 bytes

proc c a\ b {expr [string le $a]<[string le $b]}
proc L l {return [lindex [lsort -c c $l] 0]}

Try it online!

Quite disappointed by the score, should/could be better. Thought about this one-proc version:

proc L l {
 set m  [lmap e $l {regsub -all . $e 1}]
 return [lindex $l [lsearch $m [expr max([join $m ,])]]]
}

but it's longer.

\$\endgroup\$
1
\$\begingroup\$

Lua, 70 64 bytes

function f(a,...)x=...and f(...)return x and#x>#a and x or a end

Try it online!

x is set to the second argument if that is falsy, otherwise the longest of the second argument and up. The function returns x if it is truthy and longer than the first argument, else the first argument.

No type-checking, so works not only for a sequence of strings, but for sequences containing tables, or anything with a __len metamethod that returns a number. For instance f("tiny", {1, 2, 3, 4, 5}, debug.setmetatable(6, { __len = function (self) return self end })) returns 6.

This technically breaks the rule of operating on an array (in Lua, a table) because it operates on an argument list, but operating on a table seemed more complicated (table.sort is not stable). A table can be unpacked into the function: f(table.unpack { 'oh', 'one', 'two' }).

\$\endgroup\$
1
\$\begingroup\$

Vyxal, 2 bytes

ÞG

Try it Online!

\$\endgroup\$
1
\$\begingroup\$

Thunno 2, 2 bytes

ØG

Attempt This Online!

Built-in.

\$\endgroup\$
0
\$\begingroup\$

Mathematica, 29 bytes

#&@@#~MaximalBy~StringLength&

Pure function. Takes a list of strings as input and returns a string as output. #~MaximalBy~StringLength finds the longest strings in the list and #&@@ selects the first instance.

\$\endgroup\$
1
  • \$\begingroup\$ I've been trying to find an improvement on StringLength, which is pretty long. Sadly ByteCount doesn't grow one-to-one with the length of the string. Is there anything clever in this area? \$\endgroup\$ Commented Dec 21, 2017 at 8:56
0
\$\begingroup\$

Rust, 73 bytes

|mut x:Vec<String>|{x.sort_by(|a,b|b.len().cmp(&a.len()));x[0].clone()}

Very simple code, that can probably be golfed at least a little more. The fact that i had to use String instead of &str, just for the return value, bugs me alot. (I could have used a .to_string() method, but that wouldve added 2 bytes.)

Try it online!

\$\endgroup\$
0
\$\begingroup\$

MY, 24 bytes

1ω74ǵ'ƒ⇹(ω74ǵ'ƒ⇹(⍐=⍸@ω@←

Try it online!

How?

1ω74ǵ'ƒ⇹(ω74ǵ'ƒ⇹(⍐=⍸@ω@←
                       ← = Output ...
                      ω  = ... the input ...
                       @ = ... at ...
1                    @   = ... the first ...
                   ⍸     = ... truthy index of ...
 ω74ǵ'ƒ⇹(                = ... the length of each element of the input's ...
                  =      = ... equality with ...
         ω74ǵ'ƒ⇹(⍐       = ... the maximum length.
          
\$\endgroup\$
0
\$\begingroup\$

Java 8, 57 bytes (70 bytes)

By the power of streams, my java answer shall be the shortest

Arrays.stream(a).max(Comparator.comparing(String::length))

Honestly I don't know if I cheated with that answer because I don't return anything but you could use that line of code. If we really want to return stuff then it's a bit longer.

Thanks to LukeStevens for pointing out to use lambdas to be more golfy.

w->Arrays.stream(w).max(Comparator.comparing(String::length)‌​).get()

\$\endgroup\$
7
  • \$\begingroup\$ Welcome to PPCG! An answer needs to be either a program or a function, a snippet of code is not enough. Also, input needs to be taken in some allowed way. Assuming that the input is stored in a predetermined variable is not allowed. You can take input for example from STDIN or as an argument to a function. \$\endgroup\$
    – Steadybox
    Commented Dec 21, 2017 at 7:32
  • \$\begingroup\$ Hi @Steadybox I changed my program to a function(method). Is it ok now? \$\endgroup\$
    – ChristophE
    Commented Dec 21, 2017 at 7:42
  • \$\begingroup\$ @ChristophE Unfortunately you need to include the byte cost of imports aswell :( which would add another 19 bytes to this, otherwise it's a really good solution! You should also have a look at using lamdbas which would reduce the code to w->Arrays.stream(w).max(Comparator.comparing(String::length)).get() \$\endgroup\$ Commented Dec 21, 2017 at 8:31
  • \$\begingroup\$ I think I don't understand completely, my code already uses lambdas :D but just the lambda expression counts as 'function' in codegolf? thats good to know then I'll change my answer \$\endgroup\$
    – ChristophE
    Commented Dec 21, 2017 at 8:58
  • 2
    \$\begingroup\$ By the power of streams, my Java answer shall be the shortest: s->s.max((a,b)->a.length()-b.length()).get() (44 bytes). \$\endgroup\$ Commented Dec 21, 2017 at 9:35
0
\$\begingroup\$

F# (.NET Core), 29 bytes

 Seq.maxBy <| fun s->s.Length

Try it online!

Explanation

Through partial application of Seq.maxBy, returns a function (string seq -> string)

\$\endgroup\$
0
\$\begingroup\$

Stacked, 19 bytes

[:$#'"!:MAX index#]

Try it online!

Explanation

[:$#'"!:MAX index#]
[                 ]   anonymous function, takes input as list of strings
 :$  "!               on each member:
   #'                   get the length
            index     get the index of...
       :MAX             the maximum length
                 #    and obtain the respective member in the array.

Alternatives

19 bytes: [[#'\#'-]sortby 0#]

24 bytes: [$#'"!:sorted index#_1#]

\$\endgroup\$
0
\$\begingroup\$

Common Lisp, 32 bytes

(elt(sort(read)'> :key'length)0)

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Husk, 3 bytes

►L↔

Try it online!

Explanation

  ↔  -- reverse the list (such that the first gets picked in case of a tie)
►L   -- find maximum by length
\$\endgroup\$
0
\$\begingroup\$

Scratch 2.0, 22 blocks

Accepts input by pressing see inside on the project page and manually adding and removing items from list.

Project here. Flash required to run and view, apologies.

All blocks were counted including nested ones. Not sure how I'd count bytes with this language unless you want the length of the JSON.

\$\endgroup\$
2
  • \$\begingroup\$ You might want to check out this question on meta. \$\endgroup\$
    – Timtech
    Commented Dec 24, 2017 at 6:25
  • \$\begingroup\$ @Timtech thanks a ton! Didn't even know scoring existed for Scratch. :P Probably should have done it in a "real" language. \$\endgroup\$ Commented Dec 24, 2017 at 20:52
0
\$\begingroup\$

05AB1E, 3 bytes

Réθ

Try it online!

Explanation

R     # reverse
 é    # sort by length
  θ   # get the last element
\$\endgroup\$
0
\$\begingroup\$

PHP, 59 bytes

while($n=strlen($s=$argv[++$i]))$n>$e&&$e=$n+!$r=$s;echo$r;

takes words as separate command line arguments. Run with -nr or try it online.

\$\endgroup\$
0
\$\begingroup\$

Google Sheets, 40 Bytes

Anonymous worksheet function that takes input from range A:A and outputs to the calling cell

=Index(A:A,Match(Max(Len(A:A)),Len(A:A),
\$\endgroup\$
0
\$\begingroup\$

PHP, 69 bytes

usort($x,function($a,$b){return strlen($b)<=>strlen($a);});echo$x[0];

Not a trick or nice golfing, just sorting array by string length and then outputting the first element.

\$\endgroup\$
0
\$\begingroup\$

APL NARS, 10 chars, 24 bytes

{⍵[↑⍒⍴¨⍵]}

note in the test, that: 'uno' it is not one array of array, so the array of correct deep is ,⊂'uno' instead

⎕fmt  ,⊂'uno'    
  ┌1─────┐
  │┌3───┐│
  ││ uno││
  │└────┘2
  └∊─────┘

so in the test g fail for 'uno'

g←{⍵[↑⍒⍴¨⍵]}
g 'uno'
  u

but not fail for the correct type of input

g ,⊂'uno'
  uno
g 'uno' 'quattro' 'cinque'
  quattro
⎕fmt  g ,⊂''
  ┌───┐
  │┌0┐│
  ││ ││
  │└¯┘2
  └∊──┘

if the community think this is one too much big limitation: than there is the 18 chars solution

{1=≡⍵:⍵⋄∊⍵[↑⍒⍴¨⍵]} 

that evade the problem in the first test calculate the deep of input

f←{1=≡⍵:⍵⋄∊⍵[↑⍒⍴¨⍵]}     
f 'uno'
  uno
f 'uno' 'quattro' 'cinque'
  quattro

The problem of the input type of one Char in Apl as 'a' (it is consider from interpreter one char). We can transform that in one array of array of char, or one type list of arrays of deep 2 write ,⊂,'a'; so g ,⊂,'a' should return the correct answer of type array of array length 1

\$\endgroup\$
4
  • \$\begingroup\$ Please try not to make spelling and grammar error... \$\endgroup\$
    – DELETE_ME
    Commented Jan 8, 2018 at 11:01
  • \$\begingroup\$ @user202729 for the spelling error this computer seems sufficient, for grammar error nothing \$\endgroup\$
    – user58988
    Commented Jan 8, 2018 at 11:23
  • \$\begingroup\$ My computer clearly shows the warning. \$\endgroup\$
    – DELETE_ME
    Commented Jan 8, 2018 at 11:35
  • \$\begingroup\$ @user202729 ok, I use one different phrase (for eccessive); thank you very much, and a good year \$\endgroup\$
    – user58988
    Commented Jan 8, 2018 at 11:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.