28
\$\begingroup\$

In as few bytes as possible, sort the input, a delimited string OR list/vector/array of words, words contain printable ASCII except space (ASCII values 33-126) into a numbered list, table, or something resembling a table, by length.

Table rules are as follows:

  • Order is mandatory, direction is optional, either labelled rows from shortest to longest or vice versa,
  • Formatting is not the challenge. So as long as the output is some form of numerically labelled rows of words, a numbered list, or a list of lists, or similar output, then it is a satisfactory answer.
  • including/excluding gaps (NA values, see below examples for both methods of output)
  • Word case is untouched. How the word appears in input should be shown in output.

Input 1:

Code Golf and Coding Challenges Meta

or

("Code","Golf","and","Coding","Challenges","Meta")

or similar

Output 1:

 1. NA
 2. NA
 3. and
 4. Code Golf Meta
 5. NA
 6. Coding
 7. NA
 8. NA
 9. NA
 10. Challenges

or

3. and
4. Code Golf Meta
6. Coding
10. Challenges

or

[[3, ['and']], [4, ['Code', 'Golf', 'Meta']], [6, ['Coding']], [10, ['Challenges']]]

Input 2:

My v3ry 3xc3113nt m0th3r ju5t 53rv3d u5 nin3 pizz@5 #JusticeForPluto

Output 2:

1. NA
2. My u5
3. NA
4. v3ry ju5t nin3
5. NA
6. m0th3r 53rv3d pizz@5
7. NA
8. NA
9. 3xc3113nt
10. NA
11. NA
12. NA
13. NA
14. NA
15. NA
16. #JusticeForPluto

or

2. My u5
4. v3ry ju5t nin3
6. m0th3r 53rv3d pizz@5
9. 3xc3113nt
16. #JusticeForPluto

or

[[2, ['My', 'u5']], [4, ['v3ry', 'ju5t', 'nin3']], [6, ['m0th3r', '53rv3d', 'pizz@5']], [9, ['3xc3113nt']], [16, ['#JusticeForPluto']]]

More examples can be provided if necessary but I think this should suffice for now. Please ask questions if you have them, this is my second attempt at a challenge. (the first failed dramatically)

\$\endgroup\$
4
  • \$\begingroup\$ In your second example, it seems that @ is part of a word, but . is not, and # is. Could you please define what a "word" means? Thanks. \$\endgroup\$
    – hyper-neutrino
    Nov 13, 2019 at 18:02
  • \$\begingroup\$ @HyperNeutrino Sorry, I meant to delete that period. I'll make some edits \$\endgroup\$
    – Sumner18
    Nov 13, 2019 at 18:06
  • 1
    \$\begingroup\$ Can the length be in unary? \$\endgroup\$ Nov 14, 2019 at 2:14
  • \$\begingroup\$ @someone I'm unfamiliar with unary outputs. I'd have to see it to confirm, but I imagine it can be a valid answer. \$\endgroup\$
    – Sumner18
    Nov 14, 2019 at 13:54

39 Answers 39

12
\$\begingroup\$

R, 28 bytes

split(w<-scan(,""),nchar(w))

Try it online!

split does the trick; results in a list() where the element names are the lengths and the elements are vectors containing the words.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ I was wondering about the best R method. I didn't even know split existed, or how it worked. That's fantastic! \$\endgroup\$
    – Sumner18
    Nov 13, 2019 at 19:47
  • \$\begingroup\$ @Sumner18 yes, split is super nice; if you're doing something that requires split, a transformation on each group, and an unsplit, then ave is worth trying as well. \$\endgroup\$
    – Giuseppe
    Nov 13, 2019 at 20:11
8
\$\begingroup\$

K (ngn/k), 12 14 bytes

{x@=#'x@:<#'x}

Try it online!

this returns a k dictionary. lengths are key, words are value. let me know if this output format is acceptable.

in q (wrapper around the k4 dialect), we can evaluate using the k interpreter and get q output formatting:

q)k){x@=#:'x@:<#:'x}("Code"; "Golf"; "and"; "Coding"; "Challenges"; "Meta")
3 | ,"and"
4 | ("Meta";"Golf";"Code")
6 | ,"Coding"
10| ,"Challenges"

note the extra colons, which aren't required for "eached" monads in the ngn implementation

\$\endgroup\$
5
  • \$\begingroup\$ Definitely an interesting output format. If this output is functional as a dictionary, and could be used, say, as input to some other program, then I would say it is acceptable. \$\endgroup\$
    – Sumner18
    Nov 13, 2019 at 22:04
  • 2
    \$\begingroup\$ @Sumner18 oh yeah, it's functionally a dictionary. see here, where we assign the dict to r, then use key juxtaposition to return the corresponding values \$\endgroup\$
    – scrawl
    Nov 13, 2019 at 22:14
  • 1
    \$\begingroup\$ @scrawl did you mean {x@=#'x@:<#'x}? \$\endgroup\$
    – ngn
    Nov 14, 2019 at 0:28
  • \$\begingroup\$ @ngn, yes. i am constantly getting ahead of myself and not testing robustness \$\endgroup\$
    – scrawl
    Nov 14, 2019 at 7:11
  • \$\begingroup\$ that being said, my initial submission was pretty wrong in 2 big ways. it wasn't just missing edge cases \$\endgroup\$
    – scrawl
    Nov 14, 2019 at 7:17
6
\$\begingroup\$

Japt, 7 bytes

Input as an array of words, output as a 2D-array.

üÊËiDÎÊ

Try it

üÊËiDÎÊ     :Implicit input of array
ü           :Group and sort by
 Ê          :  Length
  Ë         :Map each sub-array D
   i        :  Prepend
    DÎÊ     :    Length of first element of D
\$\endgroup\$
6
\$\begingroup\$

Perl 6, 19 bytes

*.classify(*.chars)

Try it online!

Pretty much does exactly as asked.

*.classify(       )  # Classify the list
           *.chars   # By number of characters
\$\endgroup\$
2
  • 1
    \$\begingroup\$ I've heard of Perl's godlike ability to handle strings and regular expressions. I would expect nothing less of it. \$\endgroup\$
    – Sumner18
    Nov 13, 2019 at 22:42
  • 2
    \$\begingroup\$ @Sumner18 You're probably thinking of Perl 5 (though Perl 6 (now known as Raku) is pretty good at it too) \$\endgroup\$
    – Jo King
    Nov 14, 2019 at 7:10
6
\$\begingroup\$

PowerShell, 18 bytes

$args|group Length

Try it online!

\$\endgroup\$
5
\$\begingroup\$

C (gcc), 147 129 bytes

Thanks to girobuz and ceilingcat for the suggestions.

This routine first finds the maximum string length of an input array of strings, then prints the words by length in reverse.

m,*t;f(int**s){for(t=s;*s;m=fmax(m,strlen(*s++)+1));for(;--m;)for(printf("\n%d",m),s=t;*s;)printf(" %s"+3*(strlen(*s++)!=m),*s);}

Try it online!

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

JavaScript, 50 bytes

Input as an array of words, output as an object where the keys are the word lengths and the values are arrays of words.

a=>a.map(w=>o[l=w.length]=[...o[l]||[],w],o={})&&o

Try it Online!

\$\endgroup\$
4
\$\begingroup\$

Retina 0.8.2, 37 bytes

S` 
.+
$.& $&
O#`
r`(?<=\1.+)¶(.+ )
 

Try it online! Explanation:

S` 

Split the input on spaces.

.+
$.& $&

Precede each word by its length.

O#`

Sort numerically.

r`(?<=\1.+)¶(.+ )
 

If two lines start with the same length, delete the newline and the length.

\$\endgroup\$
4
\$\begingroup\$

Python 2, 76 74 72 bytes

lambda a:sorted((l,[d for d in a if len(d)==l])for l in set(map(len,a)))

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Can squeeze a couple more bytes with set unpacking in python 3 Try it online! \$\endgroup\$
    – Kyle G
    Nov 15, 2019 at 21:16
4
\$\begingroup\$

05AB1E, 9 7 bytes

€gêεùy‚

-2 bytes thanks to @Grimy.

Outputs a list of lists from lowest to highest, with the label at the right side instead of left. I.e. [[["and"],3],[["Code","Golf","Meta"],4],[["Coding"],6],[["Challenges"],10]].

Try it online or verify all test cases.

Explanation:

€g       # Get the length of each string in the (implicit) input-list
  ê      # Sort and uniquify this list of lengths
   ε     # Map each length `y` to:
    ù    #  Keep strings from the (implicit) input-list equal to this length
     y‚  #  And pair it with the current length `y`
         # (after which the result is output implicitly)
\$\endgroup\$
5
  • 1
    \$\begingroup\$ é.γg} => €gêù for -1. EDIT: actually here's 7. \$\endgroup\$
    – Grimmy
    Nov 14, 2019 at 14:04
  • 1
    \$\begingroup\$ @Grimmy Thanks. Now the grouped by builtin looks even more useless than I already thought.. xD \$\endgroup\$ Nov 14, 2019 at 14:08
  • 1
    \$\begingroup\$ Turns out there was actually a group-by built-in all this time: (incorrectly documented as sort-by). It doesn't save any bytes here (ù is more appropriate anyway), but it dramatically improved this old answer of mine. \$\endgroup\$
    – Grimmy
    Nov 18, 2019 at 17:44
  • \$\begingroup\$ @Grimmy Oh, that's good to know. Never knew we had one. Did you discovered this in the source code? Maybe tag @Mr.Xcoder somewhere so he could change the wiki for it? \$\endgroup\$ Nov 18, 2019 at 18:39
  • \$\begingroup\$ I discovered this because I wanted to use split-by for another challenge, but it didn’t behave like I thought it would, so I investigated it. \$\endgroup\$
    – Grimmy
    Nov 18, 2019 at 19:45
4
\$\begingroup\$

jq, 53 bytes

map({l:length,s:.})|group_by(.l)|.[]|[.[0].l,[.[].s]]

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Code Golf! Nice first post. \$\endgroup\$
    – miike3459
    Nov 15, 2019 at 22:31
3
\$\begingroup\$

APL (Dyalog Unicode), 15 bytes

(⍋⊃¨⊂)≢¨{⊂⍺⍵}⌸⊢

Try it online!

APL is not particularly good at simply sorting.

How it works

(⍋⊃¨⊂)≢¨{⊂⍺⍵}⌸⊢
      ≢¨     ⌸⊢  Group the arg's elements by their lengths
        {⊂⍺⍵}    Wrap each list of items, paired with the length
(⍋⊃¨⊂)           Idiom for sorting:
 ⍋               Grade up; gives indexes that will make the array sorted
  ⊃¨⊂            Map the indexes to the items
\$\endgroup\$
1
  • \$\begingroup\$ You could save 1 with (⍋⊃¨⊂)≢¨(⊂,)⌸⊢ or go Extended: ∧≢¨⊂⍤,⌸⊢ \$\endgroup\$
    – Adám
    Nov 15, 2019 at 10:55
3
\$\begingroup\$

Ruby, 22 28 bytes

->w{w.group_by(&:size).sort}

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ This output is not ordered shortest to longest words. \$\endgroup\$
    – Sumner18
    Nov 14, 2019 at 13:47
  • \$\begingroup\$ Sorry, now it is. \$\endgroup\$
    – G B
    Nov 14, 2019 at 13:51
3
\$\begingroup\$

Retina, 31 27 23 bytes

Takes input as a newline-separated list of words (I haven't noticed that's allowed at first).

.+
$.& $&
N`
D`\d+
¶ 
 

I'll add the explanation later (for now, the previous revision's explanation without the first line works perfectly). Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ Is this what you were referring to as unary output? It looks okay to me. \$\endgroup\$
    – Sumner18
    Nov 14, 2019 at 15:38
  • \$\begingroup\$ @Sumner18 This is definitely not unary output :) I was planning to use it in the Retina answer I was planning to create, but decimal turned out to be shorter (in unary, the lengths would be basically runs of # characters instead of numbers) \$\endgroup\$ Nov 14, 2019 at 15:40
  • \$\begingroup\$ That's what I thought, I guess I was just confused. My reasoning is that if a unary output could be a useful input in some other program, or if one could reason why unary labelling is valid/useful, then I believe it would be a satisfactory response. \$\endgroup\$
    – Sumner18
    Nov 14, 2019 at 16:06
3
\$\begingroup\$

Brachylog, 9 bytes

lᵍ{hl}ᶻ¹o

Try it online!

Takes input as a list of words (the testing header converts from space-separated for convenience). Output is as a list of pairs [length,words], sorted in ascending order of length. Two alternative solutions of the same length, lᵒlᵍ{hl}ᶻ and lᵍ{hl}ᶻtᵒ, output pairs reversed.

\$\endgroup\$
3
\$\begingroup\$

Haskell, 59 56 bytes

l=length
f s=[(n,[x|x<-s,l x==n])|n<-[1..maximum$l<$>s]]

Try it online!

  • -3 bytes by using a list comprehension instead of a lambda, thanks to 79037662
\$\endgroup\$
2
2
\$\begingroup\$

Pyth, 9 bytes

m+lhdd.gl

Try it online!

Port of @Shaggy's answer, so I cant really take credit for this (lol)

Pyth, 14 bytes

m+dfqdlTQSleol

Try it online!

Saves a few bytes by mapping a filtered list to each number in a 1-indexed range. This only saves 2 bytes due to the fact that the last two bytes can be implicit (would be m+dfqdlTQSleolNQ otherwise)

How it works

m+dfqdlTQSleol
m              - Map
 +d            - The sum of the element and...
   fqdlTQ      - The filtered input where each element of the input is length d        
         Sl    - To the range [1, length]
           eol - of the last element of the ordered list by key=length
               - Print implicitly

Pyth, 16 bytes

FkSleolNQkfqklTQ

Try it online!

16 bytes seems a bit high for a challenge like this but oh well. Would be 14 bytes but it looks like the last 2 bytes cant be implicit due to how filter works in pyth

How it works

FkSleolNQkfqklTQ
Fk                 - For k in...
  Sl               - The range [1, length]
    eolN           - Of the last element of the sorted list by key=length
        Q          - Of the input
         k         - Print k
          fqklT    - Filter by key k == length...
               Q   - The input (prints implicitly)

Sorry if this answer is too long, I can cut it a bit if needed

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

Jelly, 6 8 bytes

ẈẈḢ,Ɗƙ⁸Ṣ

Try it online!

A monadic link which takes a list of Jelly strings and returns a list of lists where the first member of each list is the length and the second is a list of Jelly strings of that length. Plus 2 bytes now it’s been clarified that ordering of the list is mandatory.

\$\endgroup\$
1
  • \$\begingroup\$ I suppose I should clarify. Ordering the list is mandatory, direction is optional. \$\endgroup\$
    – Sumner18
    Nov 13, 2019 at 18:28
2
\$\begingroup\$

PowerShell, 63 53 bytes

$a=@{};$args|%{$a[$_.length]+=" $_"};$a|% *or|sort N*

Try it online!

(-10 bytes thanks to mazzy)

Takes arguments via splatting, which on TIO manifests as separate command-line arguments.

We first construct an empty hashtable $a, then loop through the input arguments. Each item is tacked onto $a in the appropriate $_.length slot. Then comes the lengthy .GetEnumerator() followed by a sort to get the hashtable to print out in order. That's left on the pipeline and output is implicit.

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

Japt, 7 bytes

üÊ®uZÎl

Try it

üÊ®uZÎl // input as array of words
üÊ // group by length
  ® // for each group
   uZÎl // append length of 1st word
\$\endgroup\$
2
\$\begingroup\$

Perl 5 (-040n), 45, 40, 34 bytes

-5 bytes thanks to Xcali

$a[y///c].=" $_"}{say$b++,$_ for@a

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ 40 bytes if 0 can be included as an entry. Either way, using \n as a delimiter can save a byte or two. \$\endgroup\$
    – Xcali
    Nov 13, 2019 at 20:28
  • \$\begingroup\$ or adding -040n option to set space as record delimiter \$\endgroup\$ Nov 14, 2019 at 8:16
2
\$\begingroup\$

PHP, 62 bytes

for(;$w=$argv[++$i];ksort($a))$a[strlen($w)][]=$w;print_r($a);

Try it online!

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

J, 22 bytes

-2 bytes thaks to FrownyFrog

If the output can be a table with some empty boxes:

[:/:~#@>(,~#&.>@{.)/.]

Try it online!

J, 24 bytes

/:~@(#@><@(#@>@{.;])/.])

Try it online!

Just made it work - no doubt it can be golfed further.

\$\endgroup\$
7
  • \$\begingroup\$ The output from J is beautiful. Does it always look like this? \$\endgroup\$
    – Sumner18
    Nov 14, 2019 at 13:50
  • 1
    \$\begingroup\$ @Sumner18 It is boxed - J works on homogeneous arrays (vectors, tables and so on). When it is necessary to store data of different type (as it is now - numbers and lists of strings) and length, the data should be boxed \$\endgroup\$ Nov 14, 2019 at 14:03
  • 1
    \$\begingroup\$ @Sumner18 Here is some examples of boxed vs regular arrays in J. Please note the trailing spaces/zeros of the regular arrays. The boxed versions contain no fill. \$\endgroup\$ Nov 14, 2019 at 14:06
  • 1
    \$\begingroup\$ [:/:~#@>(,~#&.>@{.)/.] if these empty boxes are acceptable \$\endgroup\$
    – FrownyFrog
    Nov 14, 2019 at 15:51
  • 1
    \$\begingroup\$ Another approach with the same number of bytes: /:~@((>;~0{#&>)/.~#&>) \$\endgroup\$
    – Traws
    Nov 15, 2019 at 14:19
2
\$\begingroup\$

RPL, 60+10 bytes

Let's explore more creative output formats:

DUP«SIZE»DOLIST SWAP 2«STR→ X ROT ^ *»DOLIST ΣLIST EXPANDMOD

turns the list {"Code" "Golf" "and" "Coding" "Challenges" "Meta"} into the polynomial Challenges·X10+Coding·X6+(Code+Golf+Meta)·X4+and·X3 thanks to EXPANDMOD.

Sadly to allow exotic names like pizz@5 – just for you to know, @ introduces comments – STR→ must be replaced by #5B15h SYSEVAL adding 10 bytes to the source code, and obfuscating the call. That does however allow printable and even non printable chars, the latters only displayed as black squares but not lost. So the garbage resistant code is

DUP«SIZE»DOLIST SWAP 2«#5B15h SYSEVAL X ROT ^ *»DOLIST ΣLIST EXPANDMOD

(EXPANDMOD is present in HP50g at least. Tested with Emu48 in 50g mode. The code page is documented here).

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

SimpleTemplate, 136 bytes

Yeah, it's a long one... The order of the output is what made it longer :/

{@setM 0}{@eachargv.0}{@callstrlen intoR _}{@setL.[R]L.[R],_}{@ifM is lowerR}{@setM R}{@/}{@/}{@forfrom 1toM}{@echo_}.{@echojl" " L.[_]}

Incredibly, it is easier (and shorter) to output that to return.

You can try it on http://sandbox.onlinephpfunctions.com/code/ec4bf4b3efa93c63c6c5c9f1458330da0178b6cd
(Line 974 has the words, line 976 has the golfed/ungolfed version variable)


Ungolfed:

{@set results}
{@set max 0}
{@each argv.0 as word}
    {@call strlen into length word}
    {@set results.[length] results.[length], word}
    {@if max is lower than length}
        {@set max length}
    {@/}
{@/}
{@for i from 1 to length}
    {@echo i}.{@echo separator " " results.[i], "\n"}
{@/}

Most of it should be easy to understand.

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

Wolfram Language (Mathematica), 30 bytes

KeySort@*GroupBy[StringLength]

Try it online!

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

Scala, 30 42 bytes

Correction thanks to Value Ink

(s:String)=>s.split(" ").groupBy(_.length)

Try it online!

\$\endgroup\$
6
  • 2
    \$\begingroup\$ Welcome to the site! Unfortunately, assuming the input is already in a variable (in this case s) is not one of our Standard IO Methods. In addition, I notice that this doesn't print the value (it seems to require a call to print), meaning that this is a snippet, which doesn't conform to our rules \$\endgroup\$ Nov 14, 2019 at 20:59
  • \$\begingroup\$ Thank you. Would replacing s with args[0] do the trick then? As for requiring a call to print, the runner I included displays the result without the call but not in stdout. \$\endgroup\$
    – Layman
    Nov 15, 2019 at 14:43
  • \$\begingroup\$ Also more generally, what is the standard for JVM languages here? One also needs class definitions, a main method etc. to get a 'non-snippet' so not sure what is deemed too much to exclude \$\endgroup\$
    – Layman
    Nov 15, 2019 at 14:45
  • \$\begingroup\$ Unfortunately, being a Python guy myself, I'm not to familiar with the site rules for other languages. However, if you have a look at some of the highest votes questions on Meta, you should be able to find the defaults/rules for other languages \$\endgroup\$ Nov 15, 2019 at 14:57
  • 2
    \$\begingroup\$ I believe the correct format based on this tutorial on lambdas is (s:String)=>s.split(" ").groupBy(_.length). (You don't need to include the assignment portion val f= by our rules.) Try it online! \$\endgroup\$
    – Value Ink
    Nov 16, 2019 at 2:33
1
\$\begingroup\$

JavaScript (ES6), 53 bytes

Takes input as a list of words. Returns an object whose keys are the lengths and whose values are the lists of corresponding words.

a=>a.map(w=>(o[n=w.length]=o[n]||[]).push(w),o={})&&o

Try it online!

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

Red, 107 bytes

func[a][m: copy#()foreach w sort a[k: length? w
unless m/:k[put m k copy[]]append m/:k w]sort/skip to[]m 2]

Try it online!

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

JULIA
Some 55 bytes:

H(l,L=length.(l))=sort([(v,l[L.==v]) for v in Set(L)])

Try it online

\$\endgroup\$

Your Answer

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

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