# Sort and Table a Sentence by Word Lengths

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)

• 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. – HyperNeutrino Nov 13 '19 at 18:02
• @HyperNeutrino Sorry, I meant to delete that period. I'll make some edits – Sumner18 Nov 13 '19 at 18:06
• Can the length be in unary? – my pronoun is monicareinstate Nov 14 '19 at 2:14
• @someone I'm unfamiliar with unary outputs. I'd have to see it to confirm, but I imagine it can be a valid answer. – Sumner18 Nov 14 '19 at 13:54

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

• I was wondering about the best R method. I didn't even know split existed, or how it worked. That's fantastic! – Sumner18 Nov 13 '19 at 19:47
• @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. – Giuseppe Nov 13 '19 at 20:11

# 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

• 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. – Sumner18 Nov 13 '19 at 22:04
• @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 – scrawl Nov 13 '19 at 22:14
• @scrawl did you mean {x@=#'x@:<#'x}? – ngn Nov 14 '19 at 0:28
• @ngn, yes. i am constantly getting ahead of myself and not testing robustness – scrawl Nov 14 '19 at 7:11
• that being said, my initial submission was pretty wrong in 2 big ways. it wasn't just missing edge cases – scrawl Nov 14 '19 at 7:17

# 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


# Perl 6, 19 bytes

*.classify(*.chars)


Try it online!

Pretty much does exactly as asked.

*.classify(       )  # Classify the list
*.chars   # By number of characters

• I've heard of Perl's godlike ability to handle strings and regular expressions. I would expect nothing less of it. – Sumner18 Nov 13 '19 at 22:42
• @Sumner18 You're probably thinking of Perl 5 (though Perl 6 (now known as Raku) is pretty good at it too) – Jo King Nov 14 '19 at 7:10

# 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


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

-5 bytes thanks to Xcali

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


Try it online!

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

# PHP, 62 bytes

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


Try it online!

# Ruby, 22 28 bytes

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


Try it online!

• This output is not ordered shortest to longest words. – Sumner18 Nov 14 '19 at 13:47
• Sorry, now it is. – G B Nov 14 '19 at 13:51

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

• The output from J is beautiful. Does it always look like this? – Sumner18 Nov 14 '19 at 13:50
• @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 – Galen Ivanov Nov 14 '19 at 14:03
• @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. – Galen Ivanov Nov 14 '19 at 14:06
• [:/:~#@>(,~#&.>@{.)/.] if these empty boxes are acceptable – FrownyFrog Nov 14 '19 at 15:51
• Another approach with the same number of bytes: /:~@((>;~0{#&>)/.~#&>) – Traws Nov 15 '19 at 14:19

# Retina, 3127 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!

• Is this what you were referring to as unary output? It looks okay to me. – Sumner18 Nov 14 '19 at 15:38
• @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) – my pronoun is monicareinstate Nov 14 '19 at 15:40
• 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. – Sumner18 Nov 14 '19 at 16:06

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

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

# Wolfram Language (Mathematica), 30 bytes

KeySort@*GroupBy[StringLength]


Try it online!

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

# 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

# Red, 107 bytes

func[a][m: copy#()foreach w sort a[k: length? w


Try it online!

JULIA
Some 55 bytes:

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


Try it online

# Scala, 30 42 bytes

Correction thanks to Value Ink

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


Try it online!

• 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 – caird coinheringaahing Nov 14 '19 at 20:59
• 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. – Victor S Nov 15 '19 at 14:43
• 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 – Victor S Nov 15 '19 at 14:45
• 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 – caird coinheringaahing Nov 15 '19 at 14:57
• 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! – Value Ink Nov 16 '19 at 2:33