Find the longest word in an array

24

2

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.

Doggo

Posted 2017-12-20T10:13:18.733

Reputation: 427

3

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)

– user202729 – 2017-12-20T10:54:16.420

4Since I don't think anyone else has mentioned it -- Hi, and welcome to PPCG! – AdmBorkBork – 2017-12-20T14:21:19.217

Do you have any other test cases? Should we handle the case where the array is empty and, if so, how? – Luke Stevens – 2017-12-20T14:22:42.640

1No you don't have to handle the case where the array is empty. But if you want you can. – Doggo – 2017-12-20T14:25:51.163

42 hours? That's far, far too quick to be accepting an answer. – Shaggy – 2017-12-20T15:05:21.947

@Shaggy I un accepted the answer i will look into it tomorrow. – Doggo – 2017-12-20T16:29:12.830

6Normally you wait a week – Christopher – 2017-12-20T16:43:00.123

-1 because this is a fairly trivial challenge. – Esolanging Fruit – 2017-12-22T18:28:10.750

Answers

31

Imperative Tampio, 168 bytes

Listan x on riippuen siitä,onko sen ensimmäisen alkion pituus suurempi tai yhtä suuri kuin sen jokaisen alkion pituus,joko sen ensimmäinen alkio tai sen hännän x.

Online version

Ungolfed:

Listan pisin alkio on riippuen siitä, onko sen ensimmäisen alkion pituus suurempi tai yhtä suuri kuin sen jokaisen alkion pituus, joko

  • sen ensimmäinen alkio tai
  • sen hännän pisin alkio.

Online version

The only golfing opportunity this has is to replace pisin alkio (meaning "the longest element") with x.

Translation:

The longest item in a list is, depending on whether the length of the first item is greater or equal to the length of each element in the list, either

  • the first item in the list, or
  • the longest item in the tail of the list.

fergusq

Posted 2017-12-20T10:13:18.733

Reputation: 4 867

22Is this a-... Does thi-... How do you-.... What?! – auhmaan – 2017-12-20T12:39:04.553

3Google Translate from Finnish: List of x is dependent on whether the length of the first element greater than or equal to the length of each element, either the first item or the tail of x. – Adám – 2017-12-20T12:44:27.037

2@Adám I used to think APL is hard to read. Apparently all you need to beat that is to move the gamefield to a language where English is a rare commodity. – Uriel – 2017-12-20T16:32:28.597

3Who needs COBOL, AppleScript or Inform 7? Who needs Arnold Chef or Shakespeare? You have Imperative Tampio! Oh my flying spaghetti monster, Finnish of all languages? I'm not learning that one any time soon... – fede s. – 2017-12-22T01:59:13.057

BTW, all my Finnish amounts to "suomi", "moi" and "suudelma". Can I program something with that? :P – fede s. – 2017-12-22T02:00:40.783

1@fedes. You could say "Olkoon suomalainen suudelma uusi suudelma." (Let the Finnish kiss be a new kiss, it creates a new kiss object) – fergusq – 2017-12-22T07:58:17.547

1So this is basically a Finnish AppleScript. – Zacharý – 2017-12-22T22:50:29.463

Simply the best way to hanlde this. I know this isn't the shortest answer but this answer is awesome! – Doggo – 2018-01-03T16:33:48.057

20

Python, 23 bytes

lambda a:max(a,key=len)

Try it online!

Neil

Posted 2017-12-20T10:13:18.733

Reputation: 2 417

1I'm sorry that I didn't convert this right. – Doggo – 2017-12-20T10:24:04.750

1I updated the code snippet, but as it is written, it already achieves this functionality. – Neil – 2017-12-20T10:38:57.220

1This will also work unchanged in Python 3. – anonymoose – 2017-12-21T21:48:01.950

17

Haskell, 35 bytes

-3 bytes thanks to Zgarb.

foldl1(!)
a!b|(a<$a)<(a<$b)=b|1<2=a

Try it online!

I like this code. You know why? Because Haskell supports much more elegant solutions with functions from random libraries.

maximumBy(compare`on`length).reverse

That's friggin' readable! Except, it's not valid.

import Data.List
import Data.Function
maximumBy(compare`on`length).reverse

If it weren't for the imports, this would've been a perfect submission to get all the upvotes. :P

(Also, this uses one golfing tip and it uses a fold.)

totallyhuman

Posted 2017-12-20T10:13:18.733

Reputation: 15 378

2

With out the added "first-occurence-in-case-of-tie"-requirement, this beauty would work: snd.maximum.map((,)=<<(0<$)) Try it online!.

– Laikoni – 2017-12-20T13:49:32.877

How do you manage to write elegant code even when golfing? o0 – totallyhuman – 2017-12-20T13:59:28.477

1Just for reference: there's the boring 29 byte built-in import Data.Lists;argmax(0<$). – nimi – 2017-12-20T23:27:08.483

1Woah, how is the l not a part of fold? How does it distinguish between that and a function named foldl? – 12Me21 – 2017-12-21T00:10:44.227

1@12Me21 It is part of the function name foldl1. I thought that part of the explanation might be confusing, sorry... – totallyhuman – 2017-12-21T00:19:14.373

135 bytes with a function instead of lambda. Interestingly, you must replace 0 with a or something else, otherwise GHC complains about an ambiguous numeric type. – Zgarb – 2017-12-21T22:52:04.400

"If it weren't for the imports, this would've been a perfect submission to get all the upvotes" --- I'm convinced that we need a Haskell Prelude reimplementation that's optimized for golfing. There are too many critical functions and/or operators that aren't in the default Prelude, and import is way too wordy to be usable. – Jules – 2017-12-21T23:21:15.663

9

R + pryr, 31 bytes

[-2 bytes thanks to Scrooble]

pryr::f(x[order(-nchar(x))][1])

Try it online!


R, 33 bytes

function(x)x[order(-nchar(x))][1]

Try it online!

NofP

Posted 2017-12-20T10:13:18.733

Reputation: 754

3Also 33 bytes: x[which.max(nchar(x))] – Giuseppe – 2017-12-20T11:25:13.660

@Scrooble from your link I see a 33 bytes solution. – NofP – 2018-03-05T10:19:32.123

1

@NofP Haha, silly me. 31 bytes.

– Khuldraeseth na'Barya – 2018-03-05T12:19:45.277

8

EXCEL, 36 42 bytes

=INDEX(A:A,MATCH(MAX(LEN(A:A)),LEN(A:A),))

Entered as an array formula (ctrl-shift-enter). The input array should be entered in column A.

The formula returns the first match with maximum length.

Depending on your region settings, substitute , with ;; the code length remains unchanged. Of the 16 languages listed here, English function names are the shortest for this formula.

Explanation:

=                                          - return
 INDEX(                                  ) - the item of
       A:A                                 - the input
          ,                                - at
           MATCH(                       )  - the position of
                                       ,   - the first exact match of
                 MAX(        )             - the maximum of
                     LEN(   )              - the array of lengths of
                         A:A               - the input
                              ,            - in
                               LEN(   )    - the array of lengths of
                                   A:A     - the input

pbeentje

Posted 2017-12-20T10:13:18.733

Reputation: 289

What for the , in the latter? The formula still works without it – Anastasiya-Romanova 秀 – 2017-12-21T06:57:52.030

The final , is a parameter for MATCH that returns the first exact match, as required by the (revised) question. If it is left out, then MATCH expects an array in ascending order, and returns the last match instead of the first if there are multiple elements with the same length. – pbeentje – 2017-12-21T08:22:21.317

Are sure? I've compared those two formulas and both come with the exact same result – Anastasiya-Romanova 秀 – 2017-12-21T08:40:50.667

Are you using an input array that has two (different) strings of the same length? Leaving out the comma (semicolon) gives me the last string of maximum length, as expected... (Excel 2016, 64-bit) – pbeentje – 2017-12-21T08:49:50.617

Unfortunately the community has decided that using named ranges in this manner is invalid so I suggest that for this particular case you switch to using A:A and make it an array formal with {...}, otherwise great post!

– Taylor Scott – 2018-01-02T19:24:22.783

@TaylorScott thanks for the heads up. I'll modify the answer. – pbeentje – 2018-01-03T10:32:05.560

7

Prolog (SWI), 98 92 72 69 bytes

The top level predicate is *.

X/Y:-atom_length(X,Y).
[A]*A.
[A,B|L]*Z:-A/X,B/Y,Y>X,[B|L]*Z;[A|L]*Z.

Try it online!

Explanation

The first row defines the dyadic predicate / to be a short for atom_length/2which is true if the first argument's length is the second argument. This saves us 3 bytes over using atom_length twice.

Our main predicate is defined as the dyadic * where the first argument is a list and the second argument the longest element of that list.

The second row is our base case which states that the longest element of a one element list is that element.

The third row states that for a list with at least 2 elements, the longest element is:

If the length of the second element is longer than the first element, the longest element is in the list without the first element.

Otherwise the longest element is in the list without the second element.

Emigna

Posted 2017-12-20T10:13:18.733

Reputation: 50 798

I'd be interested in seeing an explanation on how it works – user41805 – 2018-01-08T18:09:20.073

@Cowsquack: I've added a short explanation. – Emigna – 2018-01-08T19:50:34.313

7

APL (Dyalog Unicode), 9 bytesSBCS

⊢⊃⍨∘⊃∘⍒≢¨

Try it online!

 from the argument,

⊃⍨ pick the element with the index which is the

 first of the

 indices in descending order of the

≢¨ lengths of each

Adám

Posted 2017-12-20T10:13:18.733

Reputation: 37 779

7

Pyth, 4 bytes

h.Ml

Test suite.

Explanation
h.Ml   | Program
h.MlZQ | With implicit variables filled in
-------+--------------------------------------------------------------------
h      | First element of
 .M  Q | The list of elements from the input list with the maximal value for
   lZ  | The length of the element

Mr. Xcoder

Posted 2017-12-20T10:13:18.733

Reputation: 39 774

ou nice you beat the Pyth answer with 6 bytes nice. – Doggo – 2017-12-20T13:52:25.797

elD_ and ho_l achieve the same length. – isaacg – 2017-12-20T19:55:15.447

1@hakr14 Thank you very much for the edit! – Mr. Xcoder – 2018-03-25T19:44:41.930

6

JavaScript (Node.js), 38 bytes

Try it online!

a=>a.sort((a,b)=>a.length<b.length)[0]

LiefdeWen

Posted 2017-12-20T10:13:18.733

Reputation: 3 381

@Doggo It does return the first element in the case of a tie. – LiefdeWen – 2017-12-20T10:53:53.367

1

Returning a boolean instead of a signed number in the sort() callback doesn't work in all JS engines (e.g. it doesn't work in Edge). Another approach would be something like that, which is 1 byte shorter. Still, there's no guarantee that the first item will be chosen consistently across browsers in case of a tie.

– Arnauld – 2017-12-20T15:38:27.380

but if it chooses it consistently in node.js on TIO isn't that good enough?\ – LiefdeWen – 2017-12-21T06:19:54.277

Yes it is because we define languages by their implementation. But then it would be better to specify the JS version it is supposed to be run on in the title of your answer. – Arnauld – 2017-12-21T10:59:03.560

1You should be using - instead of < in the comparator function. – kamoroso94 – 2017-12-21T15:58:33.427

@kamoroso94 I tried that in the TIO and it didn't work. – LiefdeWen – 2017-12-21T18:39:14.757

Use b.length-a.length instead. – user42589 – 2017-12-22T04:54:26.413

@Xufox but the current solution works and a - doesn't save any bytes? – LiefdeWen – 2017-12-22T05:54:45.633

1@LiefdeWen Yes, but it addresses the problems in the comments. – user42589 – 2017-12-22T05:59:01.503

6

PowerShell, 24 bytes

($args[0]|sort l* -d)[0]

Try it online!

Takes input $args[0], pipes that to Sort-Object based on length in -descending order. Then takes the [0]th one thereof. Since sort is stable, this takes the first element in case of a tie.

AdmBorkBork

Posted 2017-12-20T10:13:18.733

Reputation: 41 581

1Nice name wuff wuff :D – Doggo – 2017-12-20T14:39:16.147

6

Octave, 33 bytes

@(x)x{[~,p]=max(cellfun(@nnz,x))}

Input is a cell array of strings.

Try it online!

Explanation

cellfun(@nnz,x) applies the nnz function (number of nonzeros) to each string in the input array x. For ASCII strings, nnz is equivalent to numel (number of elements), but shorter. The result is a numeric array with the string lengths.

Then, [~,]=max(...) gives the index of the first maximum in the array of string lengths. The result is used as a curly-brace index into x to obtain the corresponding string.

Luis Mendo

Posted 2017-12-20T10:13:18.733

Reputation: 87 464

5

J, 19, 11, 10 8 bytes

0{>\:#@>

Try it online!

Thanks to streetster for the hint!

-1 byte thanks to FrownyFrog!

-2 bytes thanks to Conor O'Brien

How it works:

    (  #@>) - unbox each string and find its length
     \:     - sort down the list of strings according to the lengths
0{::        - take and unbox the first string

Try it online!

Galen Ivanov

Posted 2017-12-20T10:13:18.733

Reputation: 13 815

1This was my initial approach in K, but then I realised I could just sort the list by the count, descending, and take the first item... Can you do the same thing in J? – streetster – 2017-12-20T12:15:05.833

@streetster - Thanks! I just realised that. I'm going to try it now, it sould be much shorter. – Galen Ivanov – 2017-12-20T12:17:59.413

1No parentheses beyond this point: 0{::]\:#@> – FrownyFrog – 2017-12-21T17:29:52.203

Would {.@ instead of 0{:: work? – user41805 – 2017-12-21T18:46:13.380

@ FrownyFrog Cool, a fork instead of a hook to get rid of () – Galen Ivanov – 2017-12-21T22:41:30.140

@Cows quack I don't think it will unbox the string. Can you post the entire verb? – Galen Ivanov – 2017-12-21T22:45:18.007

Ah, I didn't notice that it returned a boxed string. Never mind then. – user41805 – 2017-12-22T07:35:17.117

18 bytes: 0{>\:#@> – Conor O'Brien – 2017-12-22T22:50:30.830

@Conor O'Brien Thanks! ] was just a filler, so > is the right verb. – Galen Ivanov – 2017-12-23T19:05:45.283

4

C#, 43 + 18 = 61 bytes

Try it online!

a=>a.OrderByDescending(x=>x.Length).First()

LiefdeWen

Posted 2017-12-20T10:13:18.733

Reputation: 3 381

@Doggo It does return the first element in the case of a tie. – LiefdeWen – 2017-12-20T10:53:58.987

1@GrzegorzPuławski Oh, I see, fixed. – LiefdeWen – 2017-12-20T12:17:06.257

I've got a few that maybe someone can help shorten a=>a.Aggregate((x,y)=>y.Length>x.Length?y:x) 44 byte base, a=>a.First(x=>x.Length==a.Max(y=>y.Length)) 43 byte base – Monso – 2017-12-20T20:54:09.670

'Descending' is so long you can save a byte by reversing the collection first a=>a.Reverse().OrderBy(x=>x.Length).Last() 42+18 – Monso – 2017-12-20T20:59:22.010

1@MrLore That was my first solution but then in a tie it returns the last one, because order is unaffected. – LiefdeWen – 2017-12-21T10:26:33.960

4

Japt -h, 5 3 bytes

ÔñÊ

Try it

Reverse, sort by length and output the last element.

Shaggy

Posted 2017-12-20T10:13:18.733

Reputation: 24 623

4

Perl 6,  14  13 bytes

*.max(*.chars)

Try it

*.max(&chars)

Try it

Brad Gilbert b2gills

Posted 2017-12-20T10:13:18.733

Reputation: 12 713

4

PHP, 72 bytes

array_reduce($a,function($c,$i){return (strlen($i)>strlen($c))?$i:$c;});

Alan Ondra

Posted 2017-12-20T10:13:18.733

Reputation: 41

4Hello, and welcome to PPCG! :) – James – 2017-12-20T21:51:10.230

3

Swift, 54 bytes

{($0 as[String]).reduce(""){$1.count>$0.count ?$1:$0}}

Try it online!

Herman L

Posted 2017-12-20T10:13:18.733

Reputation: 3 611

3

K (oK), 9 bytes

*x@>#:'x:

Try it online!

Example:

*x@>#:'x:("edur";"oot";"taht")
"edur"

Explanation

*x@>#:'x: / solution
       x: / store input in variable x
    #:'   / count (#:) each (')
   >      / sort descending
 x@       / apply indices to x
*         / take the first one

Notes:

Undeleted as this is classed as non-trivial, despite being basically 5 steps (would be if written as the function {*x@>#:'x}).

streetster

Posted 2017-12-20T10:13:18.733

Reputation: 3 635

3

Röda, 30 bytes

{enum|[[#_,-_,_1]]|max|_|tail}

Try it online!

Explanation:

{
 enum|         /* For each element, push its index to the stream */
 [[#_,-_,_1]]| /* For each element and index, push [length, -index, element] */
 max|          /* Find the greatest element */
 _|            /* Flat the list in the stream */
 tail          /* Return the last item in the stream */
}

Alternative 30 bytes:

{enum|[[#_,-_,_1]]|max|[_[2]]}

Try it online!

fergusq

Posted 2017-12-20T10:13:18.733

Reputation: 4 867

Writing up my jq answer made me realise that enum can be dropped, and instead the minimum from [[-#_,_1]] can be selected, https://tio.run/##K8pPSfyf9r86OlpXOV4n3jA2tiY3M68mvqYkMTOn9n9uYmaeQjUXZ7RSakppkZKOUn5@CZAsScwoUYpVqFFI46r9DwA

– user41805 – 2018-12-21T19:24:35.560

@Cowsquack That doesn't work because then min would compare strings secondarily alphabetically (because arrays are compared secondarily by their second item). For example input ["b", "a"] would give "a" as output. I should probably add a minby function to Röda or something similar... – fergusq – 2018-12-21T22:38:16.020

3

Java (OpenJDK 8), 67 bytes

Another submission in my favourite language! (read: the only one I know).
This doesn't work with an empty array, but that's fine.

Golfed

w->{for(String y:w)if(y.length()>w[0].length())w[0]=y;return w[0];}

Ungolfed

for(String y:w)                           // Loops through all Strings
    if(y.length()>w[0].length())          // If the String is longer than the first String 
                                w[0]=y;   // Store it as the first string.
return w[0];                              // Return the first String.

Try it online!

Luke Stevens

Posted 2017-12-20T10:13:18.733

Reputation: 979

3

Racket, 160 bytes 110 bytes

Try it online! First time contributing, advice appreciated!

(define(m a)(if(>(length a)1)(if(>=(string-length(car a))(string-length(m(cdr a))))(car a)(m(cdr a)))(car a)))

Ungolfed

(define (m a)
    (if (> (length a) 1)
        (if (>= (string-length (car a)) (string-length (m (cdr a))))
            (car a)
            (m (cdr a))
        )
        (car a)
    )
)

Updated solution based on feedback

Daniel Lambert

Posted 2017-12-20T10:13:18.733

Reputation: 31

4

I'd like to say welcome to PPCG on behalf of the community! I noticed that your solution apparently fails for lists where the longest string is at the end. Example here. I don't remember Racket well, but if you can I would recommend changing your algorithm to a foldr-based approach, taking the max by length and carrying that across.

– cole – 2017-12-20T19:13:21.097

Oh huh. Thank you for pointing that out. I can't believe that I didn't test that. – Daniel Lambert – 2017-12-21T13:56:07.233

You can also change the define(m a) to λ(a) – fede s. – 2017-12-22T21:01:53.853

1

Also check the tips if you haven't!

– fede s. – 2017-12-22T21:06:17.527

3

APL -- 23 16 bytes

a←{((⍴¨⍵)⍳(⌈/(⍴¨⍵)))⌷⍵}

Thanks to everyone for all of your great suggestions and encouragement!

a←{⍵⌷⍨(⍴¨⍵)⍳⌈/⍴¨⍵}

Usage:

a 'duck' 'duck' 'goose'
  'goose'

Explanation:

gets length of each vector of characters (string) then uses maximum as an index. I just started APL 20 min ago so I am sorry if this is a stupid way to do it.

Try it Online!

(edited for clarity)

rmoro

Posted 2017-12-20T10:13:18.733

Reputation: 131

1Welcome to PPCG! – Steadybox – 2017-12-21T07:24:26.550

The a← is not counted towards your bytecount. – user41805 – 2017-12-22T10:17:43.960

Never forget APL is evaluated right-to-left: (⌈/(⍴¨⍵)) => ⌈/⍴¨⍵. Also, (...)⌷⍵ => ⍵⌷⍨... to save one byte – Zacharý – 2017-12-22T22:44:38.940

Other than the parentheses, this actually seems pretty good! – Zacharý – 2017-12-22T22:46:20.253

3

Bash, 45 bytes

a=;for b;do((${#b}>${#a}))&&a=$b;done;echo $a

Try it online!

nxnev

Posted 2017-12-20T10:13:18.733

Reputation: 141

1Welcome to PPCG, nice first post! – Conor O'Brien – 2017-12-22T22:51:47.730

3

Scratch 27 17 170 160

the code picture

It expects a global (attached to all sprites, to be more precise) list of strings called mylist. After clicking the green flag, the longest word will be left in the variable w.

I think this is the link

when gf clicked
set[w]to(item[1]of[mylist
set[i]to[0
repeat(length of[mylist
change[i]by(1
set[m]to(item(i)of[mylist
if<(m)>(w)>then
set[w]to(m
end
end
stop[all

Counting as per this meta.

fede s.

Posted 2017-12-20T10:13:18.733

Reputation: 945

Is it necessary to stop[all here? – ggorlen – 2018-12-22T05:25:03.463

2

Standard ML (MLton), 55 bytes

fun&(s::r)=foldl(fn(%,$)=>if size% >size$then%else$)s r

Try it online! Example usage: & ["abc","de","fgh"] yields "abc".

Ungolfed:

fun step (current, longest) = 
    if size current > size longest 
    then current 
    else longest

fun longestString (start :: list) = foldl step start list
  | longestString nil = raise Empty

Try it online!

Laikoni

Posted 2017-12-20T10:13:18.733

Reputation: 23 676

2

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!

cab404

Posted 2017-12-20T10:13:18.733

Reputation: 141

1Looks 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. – brhfl – 2018-03-23T20:47:14.777

@brhfl thanks for suggestion! – cab404 – 2018-03-24T07:07:03.263

2

Julia 0.6, 24 bytes

!s=s[indmax(length.(s))]

Try it online!

LukeS

Posted 2017-12-20T10:13:18.733

Reputation: 421

2

Funky, 38 bytes

a=>a[(v=a::map@#)::find(math.max...v)]

Explained

a=>a[(v=a::map@#)::find(math.max...v)]
        a::map@#                        $ Create a list of the lengths of the input's strings.
      v=                                $ And assign it to v.
     (          )::find(            )   $ Find the first index in this list that equals...
                        math.max...v    $ The largest value of v, eg. the length of the longest string.
   a[                                ]  $ Get the value at that position.

Try it online!

ATaco

Posted 2017-12-20T10:13:18.733

Reputation: 7 898

2

Bash, 44 bytes

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

Try it online!

DarkHeart

Posted 2017-12-20T10:13:18.733

Reputation: 171

2

SNOBOL4 (CSNOBOL4), 63 57 bytes

I	M =LT(SIZE(M),SIZE(X)) X
	X =INPUT	:S(I)
	OUTPUT =M
END

Try it online!

Input is on stdin and output on stdout.

Roughly translates to the following pseudocode:

while input exists
 x = input
 if length(m) < length(x)
  m = x
end
return m

Giuseppe

Posted 2017-12-20T10:13:18.733

Reputation: 21 077

2

Ruby, 21 20 bytes

->s{s.max_by &:size}

Try it online!

Trivial solution, thanks Snack for -1 byte

G B

Posted 2017-12-20T10:13:18.733

Reputation: 11 099

1Take the &:size out of the parentheses for -1 – Snack – 2017-12-22T18:48:23.010

1

APL+WIN, 11 bytes

s[↑⍒∊⍴¨s←⎕]

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

Graham

Posted 2017-12-20T10:13:18.733

Reputation: 3 184

1

Perl 5, 38 bytes

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

Try it online!

Xcali

Posted 2017-12-20T10:13:18.733

Reputation: 7 671

1

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.

Toby Speight

Posted 2017-12-20T10:13:18.733

Reputation: 5 058

If you're using GCC, you can use #import<regex>. – user202729 – 2017-12-24T03:36:28.933

1

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)

Jack

Posted 2017-12-20T10:13:18.733

Reputation: 131

1

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).

user202729

Posted 2017-12-20T10:13:18.733

Reputation: 14 620

1

Coconut, 15 13 bytes

max$(key=len)

Try it online!

ovs

Posted 2017-12-20T10:13:18.733

Reputation: 21 408

1

Perl, 24 bytes

Includes +1 for p

Give words as lines on STDIN

perl -pe '$;[y///c]//=$_}{$_=pop@'
one
two 
no
^D

Ton Hospel

Posted 2017-12-20T10:13:18.733

Reputation: 14 114

1

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]

caird coinheringaahing

Posted 2017-12-20T10:13:18.733

Reputation: 13 702

1

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.)

user41805

Posted 2017-12-20T10:13:18.733

Reputation: 16 320

1

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' }).

cyclaminist

Posted 2017-12-20T10:13:18.733

Reputation: 191

0

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.

LegionMammal978

Posted 2017-12-20T10:13:18.733

Reputation: 15 731

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? – Patrick Stevens – 2017-12-21T08:56:42.583

0

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!

Håvard Nygård

Posted 2017-12-20T10:13:18.733

Reputation: 341

0

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.

Zacharý

Posted 2017-12-20T10:13:18.733

Reputation: 5 710

0

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()

ChristophE

Posted 2017-12-20T10:13:18.733

Reputation: 101

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.

– Steadybox – 2017-12-21T07:32:54.493

Hi @Steadybox I changed my program to a function(method). Is it ok now? – ChristophE – 2017-12-21T07:42:25.860

@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() – Luke Stevens – 2017-12-21T08:31:55.640

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 – ChristophE – 2017-12-21T08:58:23.300

2

By the power of streams, my Java answer shall be the shortest: s->s.max((a,b)->a.length()-b.length()).get() (44 bytes).

– Olivier Grégoire – 2017-12-21T09:35:27.137

haha "comparator.comparing" is just too long :D you win olivier. I don't know the rules of code golf, do you just post your own answer now or do I edit main and just give you credit? – ChristophE – 2017-12-21T09:43:44.273

@ChristophE Oh... generally PPCG users are nice, you can use others' idea with credit. Don't worry too much about it. – user202729 – 2017-12-24T03:38:20.730

0

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)

Aaron M. Eshbach

Posted 2017-12-20T10:13:18.733

Reputation: 101

0

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#]

Conor O'Brien

Posted 2017-12-20T10:13:18.733

Reputation: 36 228

0

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.

Krzysiu

Posted 2017-12-20T10:13:18.733

Reputation: 491

0

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

oktupol

Posted 2017-12-20T10:13:18.733

Reputation: 697

1

You can change mmu'm to u'' ('' goes to the last cursor position) to save some bytes https://tio.run/##K/v//3Cvnn481@FZ7pGl@kJKXKXq6pEeYe4F//87ZebkcHmlJqWmZCZmcDnlJ3GFJeak5pVk5iVyheTn5lZyORalQ/lBmckZiUUpAA

– user41805 – 2018-01-02T11:09:50.567

0

Common Lisp, 32 bytes

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

Try it online!

Renzo

Posted 2017-12-20T10:13:18.733

Reputation: 2 260

0

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

ბიმო

Posted 2017-12-20T10:13:18.733

Reputation: 15 345

0

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.

MustacheMoses

Posted 2017-12-20T10:13:18.733

Reputation: 131

You might want to check out this question on meta.

– Timtech – 2017-12-24T06:25:38.130

@Timtech thanks a ton! Didn't even know scoring existed for Scratch. :P Probably should have done it in a "real" language. – MustacheMoses – 2017-12-24T20:52:09.033

0

05AB1E, 3 bytes

Réθ

Try it online!

Explanation

R     # reverse
 é    # sort by length
  θ   # get the last element

Emigna

Posted 2017-12-20T10:13:18.733

Reputation: 50 798

0

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.

Titus

Posted 2017-12-20T10:13:18.733

Reputation: 13 814

0

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),

Taylor Scott

Posted 2017-12-20T10:13:18.733

Reputation: 6 709

0

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

RosLuP

Posted 2017-12-20T10:13:18.733

Reputation: 3 036

Please try not to make spelling and grammar error... – user202729 – 2018-01-08T11:01:31.197

@user202729 for the spelling error this computer seems sufficient, for grammar error nothing – RosLuP – 2018-01-08T11:23:33.017

My computer clearly shows the warning. – user202729 – 2018-01-08T11:35:23.023

@user202729 ok, I use one different phrase (for eccessive); thank you very much, and a good year – RosLuP – 2018-01-08T11:51:38.890

0

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

user41805

Posted 2017-12-20T10:13:18.733

Reputation: 16 320

0

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];}

Karl Napf

Posted 2017-12-20T10:13:18.733

Reputation: 4 131

0

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.

Conor O'Brien

Posted 2017-12-20T10:13:18.733

Reputation: 36 228

0

Kotlin, 21 bytes

{it.maxBy{it.length}}

Try it online!

snail_

Posted 2017-12-20T10:13:18.733

Reputation: 1 982

I'm afraid that, if you don't count the whole function, it becomes a snippet, so it's invalid. – Erik the Outgolfer – 2018-12-21T21:23:32.620

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 – snail_ – 2018-12-22T04:45:45.823

0

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.

david

Posted 2017-12-20T10:13:18.733

Reputation: 479