24
\$\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\$
  • 3
    \$\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\$ – user202729 Dec 20 '17 at 10:54
  • 4
    \$\begingroup\$ Since I don't think anyone else has mentioned it -- Hi, and welcome to PPCG! \$\endgroup\$ – AdmBorkBork Dec 20 '17 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 Dec 20 '17 at 14:25
  • 4
    \$\begingroup\$ 2 hours? That's far, far too quick to be accepting an answer. \$\endgroup\$ – Shaggy Dec 20 '17 at 15:05
  • 6
    \$\begingroup\$ Normally you wait a week \$\endgroup\$ – Christopher Dec 20 '17 at 16:43

61 Answers 61

2
\$\begingroup\$

Bash, 44 bytes

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

Try it online!

| improve this answer | |
\$\endgroup\$
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!

| improve this answer | |
\$\endgroup\$
  • 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 Mar 23 '18 at 20:47
  • \$\begingroup\$ @brhfl thanks for suggestion! \$\endgroup\$ – cab404 Mar 24 '18 at 7:07
1
\$\begingroup\$

APL+WIN, 11 bytes

s[↑⍒∊⍴¨s←⎕]

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

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Perl 5, 38 bytes

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

Try it online!

| improve this answer | |
\$\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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ If you're using GCC, you can use #import<regex>. \$\endgroup\$ – user202729 Dec 24 '17 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).

| improve this answer | |
\$\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)
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Coconut, 15 13 bytes

max$(key=len)

Try it online!

| improve this answer | |
\$\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]
| improve this answer | |
\$\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.)

| improve this answer | |
\$\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' }).

| improve this answer | |
\$\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.

| improve this answer | |
\$\endgroup\$
  • \$\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\$ – Patrick Stevens Dec 21 '17 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!

| improve this answer | |
\$\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.
          
| improve this answer | |
\$\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()

| improve this answer | |
\$\endgroup\$
  • \$\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 Dec 21 '17 at 7:32
  • \$\begingroup\$ Hi @Steadybox I changed my program to a function(method). Is it ok now? \$\endgroup\$ – ChristophE Dec 21 '17 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\$ – Luke Stevens Dec 21 '17 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 Dec 21 '17 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\$ – Olivier Grégoire Dec 21 '17 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)

| improve this answer | |
\$\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#]

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Common Lisp, 32 bytes

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

Try it online!

| improve this answer | |
\$\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
| improve this answer | |
\$\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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ You might want to check out this question on meta. \$\endgroup\$ – Timtech Dec 24 '17 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\$ – MustacheMoses Dec 24 '17 at 20:52
0
\$\begingroup\$

05AB1E, 3 bytes

Réθ

Try it online!

Explanation

R     # reverse
 é    # sort by length
  θ   # get the last element
| improve this answer | |
\$\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.

| improve this answer | |
\$\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),
| improve this answer | |
\$\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.

| improve this answer | |
\$\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

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

V, 27 23 21 20 bytes

Í./_
ÚGYu/"
uYHVGp

Try it online!

Explanation:

Í./_         In every line, replace every character by _
Ú            Sort alphabetically. Cursor ends up in first line
 GY          Go to last line, copy it
   u         Undo sort
    /"       Search for string in register " (the one that was just copied). Non-printable character is <C-r>
u            Undo replace, go to last cursor position. Non-printable character is <C-o> (thanks, Cows quack)
  Y          Copy line
   HVG       Go to first line, select all lines until last line
      p      Paste copied line into selection

Hexdump:

00000000: cd2e 2f5f 0ada 4759 752f 1222 0a75 0f59  ../_..GYu/.".u.Y
00000010: 4856 4770                                HVGp
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

C++ (gcc), 65 63 bytes

Accepts any container of std::string and returns via reference.

[](auto&c,auto&r){r=c[0];for(auto x:c)r=x.size()>r.size()?x:r;}

Try it online!

If you are tolerant to output, there is a 58 byte solution which alters the input list and copies the longest string to the first element:

[](auto&c){for(auto x:c)c[0]=x.size()>c[0].size()?x:c[0];}
| improve this answer | |
\$\endgroup\$
0
\$\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.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

sed 4.2.2 -rz, 71 72 83 bytes

h
:
s/^.//gm
/[^\n]{2}/t
:b
/^\n/{s/.//
x
s/^[^\n]*.//
x}
tb
x
s/\n.*//

Try it online!

  • -r uses extended regular expressions, in other words, allows golifer syntax as we are able to save several \s

  • -z puts all lines of input into one "line", so that they would be processed at the same time rather than the normal cyclic processing.

This was a fun challenge seeing as sed did not have any builtin sort functions. The program works as follows:

  • copy the pattern space into the hold space
  • find the position of the longest line by repeatedly removing the first character from every line until we are remaining with line(s) with only a single character, this first of these is at the position of the longest line
  • to find which line this position corresponds to, we repeatedly

    • remove the first line of the pattern space and hold space until we encounter a non-newline character on the first line of the pattern space
  • now that the corresponding line is at the top of the hold space, we remove the other lines
  • the contents of the buffer is printed at the end of the program
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Kotlin, 21 bytes

{it.maxBy{it.length}}

Try it online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I'm afraid that, if you don't count the whole function, it becomes a snippet, so it's invalid. \$\endgroup\$ – Erik the Outgolfer Dec 21 '18 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_ Dec 22 '18 at 4:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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