title: Finding your partner

text:
# Question
Title: Finding your partner
## Challenge

Given an arbitrary list of 2-tuples, and a single element in one of those tuples, output its "partner", i.e. given `a` and `[(i,j),...,(a,b),...,(l,m)]`, output `b`. You can assume all tuples are unique, and that all elements in tuples are strings. Further assume you do not have both `(x,y)` and `(y,x)`.

### Test cases

```
Input                                                           Output

[("(", ")"), ("{", "}"), ("[", "]")], "}"                       "{"
[("I'm", "So"), ("Meta", "Even"), ("This", "Acronym")], "Even"  "Meta"
[("I", "S"), ("M", "E"), ("T", "A")], "A"                       "T"
[("test", "cases"), ("are", "fun")], "test"                     "cases"
[("sad", "beep"), ("boop", "boop")], "boop"                     "boop"

```

Fewest bytes wins!

# Answer
> 8 votes
# Japt, 6 bytes

Works with strings or integers.

```
æøV kV

```

Test it

---

## Explanation

Implicit input of array `U` and string/integer `V`.

```
æ

```

Get the first element (subarray) in `U` that ...

```
øV

```

Contains `V`.

```
kV

```

Remove `V` and implicitly return the resulting single-element array.

# Answer
> 8 votes
# Haskell, 33 bytes

```
x!((a,b):c)|x==a=b|x==b=a|1<2=x!c

```

Try it online!

Defines a binary operator `!`, which takes as its left argument a value `x` of type τ and as its right argument a list of tuples (τ, τ). The definition pattern matches on the head `(a,b)` and tail `c` of the given list; if `x==a` then `b` is returned; if `x==b` then `a` is returned, and otherwise we go on looking in the rest of the list by recursing.

```
  'f' ! [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
≡ 'f' ! [('c', 'd'), ('e', 'f'), ('g', 'h')]
≡ 'f' ! [('e', 'f'), ('g', 'h')]
≡ 'e'

```

(If there’s no “partner” in the list, this will crash, because we didn’t define what `x![]` should be.)

# Answer
> 5 votes
# MATL, ~~4~~ ~~14~~ ~~5~~ 6 bytes

```
yY=P)u

```

Try it online!

Input is an array as `[{a;b},{c;d}]`. Bytecount fluctuates heavily while the OP figures out what's actually allowed.

```
y     % Implicitly input tuples T and 'lonely element' E, duplicate from below to get [T E T] on the stack
 Y=   % String comparison, element wise, between T and E. Yields a boolean array with a 1 at the correct location.
   P  % Flip this array vertically, to put the 1 at the 'partner' of E.
    ) % Select this partner from the bottom T.

```

I started off with a 4-byte version that could only handle single-character strings, which was the only testcase in the original challenge. When this turned out to be invalid, I made a very long 14-byte version, which was nice and hacky (check the revision history!), made me discover a bug, and then turned out to be completely unnecessary as `Y=`, with suitable input, worked just as well as my original 4-byte `y=P)`.

# Answer
> 5 votes
## JavaScript (ES6), 39 bytes

```
e=>g=([[b,c],...a])=>e==b?c:e==c?b:g(a)

```

Takes the entry and array of arrays as curried arguments. Best non-recursive version I could do was 44 bytes:

```
e=>a=>a.find(a=>a.includes(e)).find(b=>b!=e)

```

# Answer
> 4 votes
# Python 2, 37 bytes

```
lambda x,y:dict(x+map(reversed,x))[y]

```

Try it online!

# Proton, 31 bytes

```
a,b=>dict(a+map(reversed,a))[b]

```

Try it online!

(These two answers are so similar that I'm posting them together to avoid repfarming)

# Answer
> 3 votes
# Jelly, 6 bytes

```
ċÞṪ⁻ÞṪ

```

A dyadic link taking the list partners on the left and the lost-partner on the right and returning the partner.

**Try it online!**

### How?

```
ċÞṪ⁻ÞṪ - Link: list, partners; item, lost-partner
 Þ     - sort (the tuples) by:
ċ      -   count occurrence of lost-partner
  Ṫ    - tail (gets the tuple containing the lost-partner)
    Þ  - sort (that tuple's items) by:
   ⁻   -   not equals (non-vectorising version)
     Ṫ - tail (get the other one, or the rightmost one if they were equla)

```

# Answer
> 2 votes
# Python 2, ~~59~~ ~~45~~ 42 bytes

*-14 bytes thanks to Emigna. -3 bytes thanks to Maltysen.*

```
lambda l,v:sum(l,())[sum(l,()).index(v)^1]

```

Try it online!

Still wanna use currying though. ;-;

# Answer
> 2 votes
# Perl 5, 30 + 1 (-p) = 31 bytes

```
$_={@f=eval$_,reverse@f}->{<>}

```

Try it online!

# Answer
> 2 votes
## Mathematica ~~27~~ 24 Bytes

`Cases` picks out elements of a list that match a pattern. When used with an arrow, elements matching patterns can be transformed.

```
Cases[{#,x_}|{x_,#}:>x]&

```

Usage:

```
%[3][{{1, 2}, {3, 4}}]

```

Explanation: In this example, after encountering the first argument, 3, the function becomes `Cases[{3,x_}|{x_,3}:>x]` which is an operator form of `Cases` that is then applied to the 2nd argument, `{{1, 2}, {3, 4}}`, thus selecting the companion of 3, whether it be in the abscissa or ordinate position. Notably, this function will list out all of the companions if in fact the 1st argument appears more than once within the 2nd argument, in other words, this goes a little beyond the assumptions of the stated question.

Enclosing glyphs must be squiggly braces. Saved 3 bytes with "Currying" suggestion from @Notatree

# Answer
> 2 votes
# , 47 ~~42~~ bytes

```
function(v,a)a[(i=min(which(v==a)))+(i%%2*2-1)]

```

Try it online!

Works on either a matrix or a straight vector. v = the search value, a = tuple array.

# Answer
> 2 votes
## C++, 179 bytes

```
#include<vector>
#include<string>
#define S std::string
S f(std::vector<std::pair<S,S>>s,S t){for(auto&a:s){if(a.first==t)return a.second;if(a.second==t)return a.first;}return"";}

```

## C++ w/ map data type, 162 bytes

```
#include<map>
#include<string>
#define S std::string
S f(std::map<S,S>s,S t){for(auto&a:s){if(a.first==t)return a.second;if(a.second==t)return a.first;}return"";}

```

With MSVC, the code compiles even if the last `return` statement ( `return"";` ) is omitted. It makes the code 9 bytes lighter, **BUT** exiting by the function end ( i.e. not exiting by a `return` statement in the loop ) with no return statements will cause **undefined behavior**, and not work if the tuple array does not contains the "key" element

# Answer
> 2 votes
# PowerShell, 36 Bytes

```
param($a,$c)$a|?{$c-in$_}|%{$_-ne$c}

```

finds the element containing the intput, then gets the 'other' element by excluding the input from it, PowerShell doesn't have the most amazing array management but there might be a built-in for this i'm not aware of.

```
.\Partner.ps1 (("I'm","So"),("Meta","Even"),("This","Acronym")) "Even"
Meta

```

# Answer
> 2 votes
# Röda, 30 bytes

```
f a{[(_+"")[1-indexOf(a,_1)]]}

```

Try it online!

Explanation:

```
f a{[(_+"")[1-indexOf(a,_1)]]}
f a{                         } /* Function f(a)                         */
                               /* For each pair _1 in the stream:       */
              indexOf(a,_1)    /*   Index of a in _1 or -1 if not found */
            1-                 /*   Subtract from 1 to get the index of
                                     the other value in the pair or 2 if
                                     a is not in the pair               */
     (_+"")                    /*   Append "" to _1                     */
           [               ]   /*   Get element the other element or "" */
    [                       ]  /*   Push it to the straem               */
                               /* All values in the stream are printed  */

```

# Answer
> 1 votes
# Pyth - ~~11~~ ~~9~~ 8 bytes

```
h-hf}QTE

```

Try it online here.

# Answer
> 1 votes
# Haskell, ~~65~~ 62 bytes

```
c#(a,b)|a==c=b|1>0=a
x%l=x#(snd(span(\(a,b)->a/=x&&b/=x)l)!!0)

```

Try it online!

## Explanation

This uses span to find the first instance where `x` is contained by the tuple. It then grabs the first element of the tuple if its not equal and the second otherwise.

# Haskell Lambdabot, ~~59~~ 56 bytes

```
c#Just(a,b)|a==c=b|1>0=a
x%l=x#find(\(a,b)->a==x||b==x)l

```

Try it online!

## Explanation

This uses `Data.List`s `first` function to cut down on the bytes used by `(!!0).snd.span`, however because `first` returns a `Maybe` we need to add `Just` to our pattern match in `#`.

# Answer
> 1 votes
# Husk, 10 bytes

```
→ḟo=⁰←S+m↔

```

Try it online!

### Ungolfed/Explanation

```
            -- example input:                         4 [(1,2),(3,4)]
      S+    -- concatenate list with                -
        m↔  --   itself but all pairs flipped       -   [(1,2),(3,4),(2,1),(4,3)]
 ḟo         -- find first occurence where           -
   =⁰←      --   the left element is equal to input -   (4,3)
→           -- get the right element                -   3

```

**Note**: The above example works on integers just for the sake of readability, the type itself doesn't matter (as long as you can compare it).

# Answer
> 1 votes
# 05AB1E, 7 bytes

```
.åÏ`¹K`
  Ï      # keep only pairs that contain the first input
   `     # flatten
    ¹K   # remove the first input
      `  # flatten

```

Try it online!

**Alternative 7 byte solution**

```
˜DIkX~è
˜        # deep flatten
 D       # duplicate
  Ik     # get the index of the second input in this list
    X^   # XOR with 1
      è  # get the element at this index

```

Try it online!

# Answer
> 1 votes
# Common Lisp, 74 bytes

```
(lambda(a x)(or(cdr(assoc x a :test'equal))(car(rassoc x a :test'equal))))

```

Try it online!

# Answer
> 1 votes
# Java 8, 78 bytes

A lambda (curried) from `Stream<List<String>>` to a lambda from `String` to `String` (although implicit typing happens to allow this to work for arbitrary lists). The language has no dedicated tuple classes, and I'm not aware of any in the standard library, so input pairs are represented as lists. Can be assigned to `Function<Stream<List<String>>, Function<String, String>>`.

```
l->s->l.filter(p->p.contains(s)).map(p->p.get(1-p.indexOf(s))).findAny().get()

```

Try It Online

I'll credit the saving of the last 6 bytes to anyone who can convince me that returning an `Optional` is valid. I haven't been able to convince myself.

One of the interesting parts of this solution for me was determining the cheapest way to get the output from the stream. I considered `reduce`, `findFirst`, and `min`/`max`, but none was shorter than the intuitive `findAny`.

# Answer
> 1 votes
# C# (.NET Core), ~~101~~ 100 + 18 bytes

thank you to Grzegorz Puławski helping reducing a couple of bytes.

```
x=>y=>x.Where(z=>z.Item1==y).FirstOrDefault()?.Item2??x.Where(z=>z.Item2==y).FirstOrDefault()?.Item1

```

Try it online!

# C# (.NET Core), ~~122~~ ~~121~~ 120 bytes

```
x=>y=>{for(int i=0;i<x.Length;i++){if(x[i].Item1==y){return x[i].Item2;}if(x[i].Item2==y){return x[i].Item1;}}return"";}

```

Try it online!

# Answer
> 1 votes
# JavaScript (ES6), 45 bytes

Came up with this last night then noticed Neil had beaten me to a better JS solution; figured I may as well post it anyway.

Works with strings and integers.

```
a=>n=>a.reduce((x,y)=>y[1-y.indexOf(n)]||x,0)

```

# Answer
> 1 votes
# Prolog (SWI), 43 bytes

```
f([[A,B]|T],X,R):-A=X,R=B;B=X,R=A;f(T,X,R).

```

Try it online!

# Answer
> 1 votes
# QBIC, 30 bytes

```
{_?~A=G|_X]_?~A=;|Z=B]~B=C|Z=A

```

QBIC isn't strong on lists and tuples. The above code takes `a` as a command line parameter, then asks for user input in pairs for the tuples. When an empty element is given, it outputs `b`.

# Sample run

```
Command line: Even
I'm
So
Meta
Even
This
Acronym

Meta

```

# Explanation

```
{           DO infinitely
_?          Ask for part 1 of tuple, A$
~A=G|  ]    IF A$ is empty (equal to G$, which is undefined and therefore "") THEN
     _X         Quit
_?          Ask for part 2 of tuple, B$
~A=;|       IF part 1 of the tuple equals teh cmd line param (loaded in as C$) THEN
    Z=B]        set Z$ to part 2 of the tuple (Z$ gets printed when QBIC quits)
~B=C|Z=A    IF part 2 of the tuple matches input, set Z$ to part 1
            The final IF and the DO loop are closed implicitly

```

## Alternative version, 22 bytes

```
{_?_?~A=;|_XB]~B=C|_XA

```

This basically does the same as the longer version, but immediately quits when it finds a match. I've listed this as the alternative, because you can't input all tuples into this program given that it quits early.

# Answer
> 1 votes
# Swift 4, 43 bytes

```
{a,m in a.flatMap{$0==m ?$1:$1==m ?$0:nil}}

```

The output is an array, which is either empty (no partner found), or has a single element (the partner).

Test cases:

```
let testcases: [(pairs: [(String, String)], match: String, expected: String)] = [
    (
        pairs: [("(", ")"), ("{", "}"), ("[", "]")],
        match: "}", expected: "{"
    ),
    (
        pairs: [("I'm", "So"), ("Meta", "Even"), ("This", "Acronym")],
        match: "Even", expected: "Meta"
    ),
    (
        pairs: [("I", "S"), ("M", "E"), ("T", "A")],
        match: "A", expected: "T"
    ),
    (
        pairs: [("test", "cases"), ("are", "fun")],
        match: "test", expected: "cases"
    ),
    (
        pairs: [("sad", "beep"), ("boop", "boop")],
        match: "boop", expected: "boop"
    ),
]

for (caseNumber, testcase) in testcases.enumerated() {
    let actual = f(testcase.pairs, testcase.match).first

    assert(actual == testcase.expected,
        "Testcase #\(caseNumber) \((testcase.pairs, testcase.match)) failed. Got \(String(reflecting: actual)), but expected \(testcase.expected)!")
    print("Testcase #\(caseNumber) passed!")
}

```

# Answer
> 1 votes
# Arturo, 32 bytes

```
$[a,s][--select.n:1a=>[in? s&]s]

```

Try it

# Answer
> 0 votes
# Mathematica, 50 bytes

```
(t={#2};Select[Complement[#,t]&/@#,Length@#==1&])&

```

Try it online!

# Answer
> 0 votes
# Ruby, 31 bytes

```
->a,e{e=*e;a.find{|p|p!=p-e}-e}

```

Returns a singleton array.

# Answer
> 0 votes
# Stacked, 21 bytes

```
[:$revmap,KeyArray\#]

```

Try it online! This takes input from the the stack and leaves output on the stack. Expanded, this looks like:

```
[ : $rev map , KeyArray \ # ]

```

## Explanation

Let's take `(('sad' 'beep') ('boop' 'boop'))` and `'boop'` as the input. Then, an array like so is constructed by `:$revmap,`:

```
(( 'sad' 'beep')
 ('boop' 'boop')
 ('beep'  'sad')
 ('boop' 'boop'))

```

That is, a copy of the array is map, each member is reversed, and the two are concatenated together. `KeyArray` in turn makes a hash out of the values given, like so:

```
KeyArray [ sad => beep, boop => boop, beep => sad, boop => boop ]

```

Then, `\` brings the search string to the top of the stack, and obtains the key from the KeyArray that matches with `#`. This returns only one value, so the duplicate key in the KeyArray does not need to be worried about.

## Other approaches

32 bytes: (input from stack, output to STDOUT) `[@x:$revmap,uniq[...x=$out*]map]`

36 bytes: `{%x[y index#+]YES 0# :y neq keep 0#}`

38 bytes: `[@x:$revmap#,[KeyArray x#]map:keep 0#]`

46 bytes: `[@x:KeyArray\$revmap KeyArray,[x#]map:keep 0#]`

# Answer
> 0 votes
# Excel, 18 Bytes

Anonymous Excel Workbook Formula that takes input as `<Lookup Value>` from range `A1`, `<Key Array>` from range `B:B` and `<Def Array>` from range `C:C`, and outputs the value of the definition associated with the lookup value to the calling cell

```
=VLOOKUP(A1,B:C,2)

```

Sample I/O shall be included when possible

---
Tags: code-golf, array, search
---


title: Triangularly embed a graph on a surface

text:
# Question
Title: Triangularly embed a graph on a surface
This challenge arises from a claim made in a MathOverflow answer and a paper linked in that answer which seems to back up the claim:

> Searching for triangular embeddings is much quicker than enumerating over all embeddings… In fact, Jungerman was able to find a triangular embedding of \\$K\_{18}-K\_3\\$ in about half an hour back in the 1970s.

Some definitions must be made here. A *combinatorial embedding* of a graph embedded in an orientable surface is an ordered adjacency list, where the list of neighbours for each vertex \\$v\\$ reflects their order when going around \\$v\\$ in a certain direction, which is the same for all vertices.

A combinatorial embedding corresponding to the above graph, embedded on the torus, is

```
0: 1 3 5 6
1: 0 6 3 2
2: 1 4 6 3
3: 0 2 1 4
4: 2 5 3
5: 0 4 6
6: 0 5 2 1

```

The neighbours are listed clockwise for all vertices. This embedding is the same as the one above because the neighbour lists for each vertex have only been cyclically permuted:

```
0: 3 5 6 1
1: 6 3 2 0
2: 1 4 6 3
3: 4 0 2 1
4: 3 2 5
5: 4 6 0
6: 2 1 0 5

```

However, if the neighbour list for vertex 5 was changed to `4 0 6`, it would no longer be a combinatorial embedding because `4 0 6` is not a cyclic permutation of `0 4 6`.

A *triangular embedding* is a combinatorial embedding satisfying rule R\*, which when coupled with the vertex-edge-genus relationship that will be introduced later on *guarantees* that the embedding may be drawn on the surface without crossings and with all faces triangular:

> If in the row for vertex `i` there appear the three consecutive vertices `j k l` in that order (reading forwards and wrapping around if necessary), in the row for vertex `k` there must appear the three consecutive vertices `l i j` in that order. This must hold for all adjacent vertex pairs `i` and `k`.

For example, the graph \\$K\_{10}-K\_3\\$ (a 10-vertex complete graph, or \\$K\_{10}\\$, where the edges between 3 vertices have been removed, i.e. a \\$K\_3\\$ is missing) has the following triangular embedding:

```
0: 1 7 6 2 8 5 4 9 3
1: 2 7 0 3 8 6 5 9 4
2: 3 7 1 4 8 0 6 9 5
3: 4 7 2 5 8 1 0 9 6
4: 5 7 3 6 8 2 1 9 0
5: 6 7 4 0 8 3 2 9 1
6: 0 7 5 1 8 4 3 9 2
7: 0 1 2 3 4 5 6
8: 0 2 4 6 1 3 5
9: 0 4 1 5 2 6 3

```

This embedding satisfies rule R\*. For example, `9 5 3` appears in row `2`, so `3 2 9` should appear in row `5`, and it does.

It is not necessary to specify the genus of the surface on which a triangular embedding lives (can be drawn) on, since the graph contains all necessary information: count the number of edges \\$E\\$ and number of vertices \\$V\\$. Since all faces are triangles, the faces number \\$F=2E/3\\$. Then by Euler's formula the genus is $$\frac12(2-(V-E+F))=1+\frac{E/3-V}2$$ For example, the embedding of \\$K\_{10}-K\_3\\$ above has 10 vertices and 42 edges, so it lives on the surface of genus \\$1+(14-10)/2=3\\$.

While rule R\* is fairly strong I still doubt that it makes searching for triangular embeddings – or proving their non-existence – much easier, especially since you still need to consider all permutations of neighbours for one vertex at the start. No code was provided in the MO answer or by Jungerman, so I'd like your help in "reconstructing" it.

## Task

Write the that when given a graph in any reasonable format, determines whether a triangular embedding of the graph exists and outputs one such embedding if it does exist. If no embedding exists the program must indicate this in a halting manner (returning something else, raising an error, etc.) – it cannot run forever.

Your code must work in principle for an arbitrary input graph, which you may assume is 3-connected and would live on a surface of **positive integer** genus, calculated by \\$1+\frac{E/3-V}2\\$, *if* it could be triangularly embedded. (This implies that the input is non-planar.)

The code will be run on my Lenovo ThinkPad E14 Gen 2 laptop with an 8-core Intel Core i7 processor running Ubuntu 22.10. A program's score is the sum of time needed over the six inputs below – the lower the better. You may output the embedding in any reasonable format, as long as the order of neighbours for each vertex is clear. I encourage you to post the results for your code on your own machine for my reference.

## Graphs with triangular embeddings

The graphs below are given as *unordered* adjacency lists.

* \\$K\_{10}-C\_9\\$ (on genus 2), where \\$C\_9\\$ is a 9-vertex cycle. I obtained an embedding of \\$J(5,2)\\$ from this by deleting 6 edges (see below):

```
0: 1 2 3 4 5 6 7 8 9
1: 0 2 3 4 6 7 8
2: 0 1 3 4 5 7 9
3: 0 1 2 5 6 8 9
4: 0 1 2 5 6 7 8
5: 0 2 3 4 6 7 9
6: 0 1 3 4 5 8 9
7: 0 1 2 4 5 8 9
8: 0 1 3 4 6 7 9
9: 0 2 3 5 6 7 8

```
* \\$K\_{13}-K\_3\\$ (on genus 7) from Jungerman's paper, which says that a triangular embedding was computed in "about 2 seconds" on a PDP-15:

```
0: 1 2 3 4 5 6 7 8 9 10 11 12
1: 0 2 3 4 5 6 7 8 9 10 11 12
2: 0 1 3 4 5 6 7 8 9 10 11 12
3: 0 1 2 4 5 6 7 8 9 10 11 12
4: 0 1 2 3 5 6 7 8 9 10 11 12
5: 0 1 2 3 4 6 7 8 9 10 11 12
6: 0 1 2 3 4 5 7 8 9 10 11 12
7: 0 1 2 3 4 5 6 8 9 10 11 12
8: 0 1 2 3 4 5 6 7 9 10 11 12
9: 0 1 2 3 4 5 6 7 8 10 11 12
10: 0 1 2 3 4 5 6 7 8 9
11: 0 1 2 3 4 5 6 7 8 9
12: 0 1 2 3 4 5 6 7 8 9

```
* \\$K\_{18}-K\_3\\$ (on genus 17) from Jungerman's paper, "about 25 minutes" on the same machine:

```
0: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
1: 0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
2: 0 1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
3: 0 1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17
4: 0 1 2 3 5 6 7 8 9 10 11 12 13 14 15 16 17
5: 0 1 2 3 4 6 7 8 9 10 11 12 13 14 15 16 17
6: 0 1 2 3 4 5 7 8 9 10 11 12 13 14 15 16 17
7: 0 1 2 3 4 5 6 8 9 10 11 12 13 14 15 16 17
8: 0 1 2 3 4 5 6 7 9 10 11 12 13 14 15 16 17
9: 0 1 2 3 4 5 6 7 8 10 11 12 13 14 15 16 17
10: 0 1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17
11: 0 1 2 3 4 5 6 7 8 9 10 12 13 14 15 16 17
12: 0 1 2 3 4 5 6 7 8 9 10 11 13 14 15 16 17
13: 0 1 2 3 4 5 6 7 8 9 10 11 12 14 15 16 17
14: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 15 16 17
15: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
16: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
17: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

```

## Graphs without triangular embeddings

* \\$K\_{4,2,2,2}\\$ (on genus 2), a complete tetrapartite graph with partition sizes \\$\\{4,2,2,2\\}\\$ and the subject of the MathOverflow question:

```
0: 4 5 6 7 8 9
1: 4 5 6 7 8 9
2: 4 5 6 7 8 9
3: 4 5 6 7 8 9
4: 0 1 2 3 6 7 8 9
5: 0 1 2 3 6 7 8 9
6: 0 1 2 3 4 5 8 9
7: 0 1 2 3 4 5 8 9
8: 0 1 2 3 4 5 6 7
9: 0 1 2 3 4 5 6 7

```

```
0: 1 2 3 4 5 6
1: 0 2 3 4 7 8
2: 0 1 3 5 7 9
3: 0 1 2 6 8 9
4: 0 1 5 6 7 8
5: 0 2 4 6 7 9
6: 0 3 4 5 8 9
7: 1 2 4 5 8 9
8: 1 3 4 6 7 9
9: 2 3 5 6 7 8

```
* \\$K\_{13}-K\_6\\$ (on genus 5) from Jungerman's paper:

```
0: 1 2 3 4 5 6 7 8 9 10 11 12
1: 0 2 3 4 5 6 7 8 9 10 11 12
2: 0 1 3 4 5 6 7 8 9 10 11 12
3: 0 1 2 4 5 6 7 8 9 10 11 12
4: 0 1 2 3 5 6 7 8 9 10 11 12
5: 0 1 2 3 4 6 7 8 9 10 11 12
6: 0 1 2 3 4 5 7 8 9 10 11 12
7: 0 1 2 3 4 5 6
8: 0 1 2 3 4 5 6
9: 0 1 2 3 4 5 6
10: 0 1 2 3 4 5 6
11: 0 1 2 3 4 5 6
12: 0 1 2 3 4 5 6

```

# Answer
# Python 3 + Google OR-Tools

A fairly direct encoding of the problem; takes a list of lists of adjacent indices for each variable. I suspect it might be possible to do better by introducing variables for the triangles, but then sub-cycles become a problem.

```
from ortools.sat.python import cp_model

def embed(g, log_search_progress=False):
    model = cp_model.CpModel()
    edges = [{} for _ in g]
    for i, g_i in enumerate(g):
        e = edges[i]
        for j in g_i:
            g_j = g[j]
            for k in g_i:
                if j == k:
                    continue
                if k not in g_j:
                    continue
                e[(j, k)] = model.NewBoolVar(f'e_{(j, k)}')
        index = {j: p for p, j in enumerate(g_i)}
        model.AddCircuit([(index[j], index[k], v) for (j, k), v in e.items()])
    for i, (g_i, e_i) in enumerate(zip(g, edges)):
        for j in g_i:
            for k in g_i:
                if (j, k) not in e_i:
                    continue
                v0 = e_i[(j, k)]
                for l in g_i:
                    if (k, l) not in e_i:
                        continue
                    v1 = e_i[(k, l)]
                    if l == j:
                        model.AddBoolOr([v0.Not(), v1.Not()])
                        continue
                    e_k = edges[k]
                    v2 = e_k[(l, i)]
                    v3 = e_k[(i, j)]
                    model.AddBoolOr([v0.Not(), v1.Not(), v2])
                    model.AddBoolOr([v0.Not(), v1.Not(), v3])
    solver = cp_model.CpSolver()
    if log_search_progress:
        solver.parameters.log_search_progress = True
    solver.parameters.linearization_level = 2
    status = solver.Solve(model)
    if status != 4:
        return None
    embedding = [[] for _ in g]
    for i, (e_i, emb_i) in enumerate(zip(edges, embedding)):
        succ = {}
        for (j, k), v in e_i.items():
            if solver.Value(v):
                succ[j] = k
        j = j0 = next(iter(succ))
        while True:
            emb_i.append(j)
            j = succ[j]
            if j == j0:
                break
    return embedding

```
> 1 votes

---
Tags: decision-problem, graph-theory, fastest-code, topology
---


title: Lyndon word factorization

text:
# Question
Title: Lyndon word factorization
# Background

A Lyndon word is a non-empty string which is strictly lexicographically smaller than all its other rotations. It is possible to factor any string uniquely, by the Chen–Fox–Lyndon theorem, as the concatenation of Lyndon words such that these subwords are lexicographically non-increasing; your challenge is to do this as succinctly as possible.

# Details

You should implement a function or program which enumerates the Lyndon word factorization of any printable ASCII string, in order, outputting the resultant substrings as an array or stream of some kind. Characters should be compared by their code points, and all standard input and output methods are allowed. As usual for , the shortest program in bytes wins.

# Test Cases

```
''           []
'C'          ['C']
'aaaaa'      ['a', 'a', 'a', 'a', 'a']
'K| '        ['K|', ' ']
'abaca'      ['abac', 'a']
'9_-$'       ['9_', '-', '$']
'P&O(;'      ['P', '&O(;']
'xhya{Wd$'   ['x', 'hy', 'a{', 'Wd', '$']
'j`M?LO!!Y'  ['j', '`', 'M', '?LO', '!!Y']
'!9!TZ'      ['!9!TZ']
'vMMe'       ['v', 'MMe']
'b5A9A9<5{0' ['b', '5A9A9<5{', '0']

```

# Answer
# Pyth, 17 16 bytes

<sup>-1 byte thanks to isaacg!</sup>

```
hf!ff>Y>YZUYT+./

```

Try it online!

### Explanation

```
hf!ff>Y>YZUYT+./
              ./    Take all possible disjoint substring sets of [the input]
             +      plus [the input] itself (for the null string case).
 f                  Filter for only those sets which
  !f        T       for none of the substrings
    f  >YZUY        is there a suffix of the substring
     >Y             lexographically smaller than the substring itself.
h                   Return the first (i.e. the shortest) such set of substrings.

```
> 5 votes

# Answer
# Jelly, 18 bytes

```
ṙJ¹ÐṂF⁼
ŒṖÇ€Ạ$ÐfṀȯ

```

Try it online!
> 2 votes

# Answer
# Pyth - 28 bytes

```
hf&SI_T.Am.A>Rdt.u.>N1tddT./

```

Test Suite.
> 0 votes

# Answer
# 05AB1E, 15 bytes

```
.œé.Δεā<._ć›P}P

```

Try it online or verify all test cases.

**Explanation:**

```
.œ            # Get all partitions of the (implicit) input-string
  é           # Sort them by length
   .Δ         # Find the first/shortest which is truthy for:
     ε        #  Map over each part of the current partition:
      ā       #   Push a list in the range [1,length] (without popping the part-string)
       <      #   Decrease it to a 0-based range [0,length)
        ._    #   For each value, rotate the string that many times
          ć   #   Extract head; pop and push remainder-list and first item separately
              #   (where the head is the unmodified part-string)
           ›  #   Check for each rotated part if it's lexicographically larger than the
              #   unmodified part-string
            P #   Check whether this is truthy for all rotations
     }P       #  After the inner map: check whether it's truthy for all parts in the
              #  partition
              # (after which the found result is output implicitly as result)

```
> 0 votes

---
Tags: code-golf, string, combinatorics
---


# Question
Title: Form a subset that is a continuous range
Given a list of lists of positive integers, output a subset of them so their union forms a continuous non-empty range with no numbers missing. For example, consider this input:

```
[
   [1, 2, 3, 5],
   [2, 4, 6],
   [7, 9, 11]
]

```

The union of the first 2 forms a continuous sequence: `[1, 2, 3, 4, 5, 6]` with no numbers missing. Adding the last one would create `[1, 2, 3, 4, 5, 6, 7, 9, 11]` which is missing `8` and `10` so would not be a valid answer.

Output can be either the indexes of the included lists or the lists themselves.

Lists are guaranteed to be sorted, and the list of lists will also be sorted lexicography. All lists will have at least one element. There may be more than one valid solution, if so you may choose output any of them, or all of them, or some of them. If you output multiple solutions all must be valid and they must be clearly separated.

There will never be no solutions.

## Test cases

| Input | Output |
| --- | --- |
| `[[1, 2, 3]]` | `0` |
| `[[1, 3], [2, 4]]` | `0, 1` |
| `[[2, 4], [4, 23], [8, 10], [8, 12], [9, 13], [10, 23], [11, 14]]` | `2, 3, 4, 6` |
| `[[1, 3], [2, 4], [5,7], [6,8]]` | `0,1` OR `2,3` OR `0,1,2,3` |
| `[[1, 17], [2,23], [3,42], [4,17], [5, 3912], [6]]` | `5` |

# Answer
# Factor \+ `math.combinatorics math.unicode`, ~~61~~ 57 bytes

```
[ all-subsets rest [ concat dup minmax [a,b] ⊃ ] find ]

```

Try it online!

Returns the lists that make up the range. Returns the first solution it finds.

* `all-subsets rest` Powerset sans the empty set.
* `[ ... ] find` Find the first element that returns true when `[ ... ]` is run on it.
* `concat` The union of all sets in a sequence (with duplicates, but it doesn't matter).
* `dup minmax [a,b]` Create a range from the minimum and maximum elements in the union.
* Is the union a superset of the range?
> 3 votes

# Answer
# Pyth, 12 bytes

```
f!-.+{SsT1ty

```

Try it online!

Returns a list of all answers, each in list of lists form.

### Explanation

```
f!-.+{SsT1tyQ    # implicitly add Q
                 # implicitly assign Q = eval(input())
           yQ    # power set of Q
          t      # all but the first element (thus excluding the empty element)
f                # filter on lambda T
       sT        #   flatten T
      S          #   sort
     {           #   deduplicate
   .+            #   take the deltas (should be all 1s if we have a continuous range)
  -      1       #   remove all instances of 1
 !               #   not (will only be true for the empty list)

```
> 3 votes

# Answer
# Vyxal ~~22~~ ~~18~~ ~~17~~ 15 or 10 bytes

This code output resulting range:

```
ṗƛÞfUs;'¯U1w⁼;,

```

Try it online!

and this (@lyxal) - the lists that are used in the range:

```
ṗꜝ'ƒ∪s¯1=A

```

Try it online!
> 3 votes

# Answer
# Jelly, 9 bytes

```
ŒPṬSṠṢƑƲƇ

```

A monadic Link that accepts a list of lists of positive integers and yields a list of the valid lists of lists for which the union forms a continuous range.

**Try it online!** Or see the test-suite.

### How?

```
ŒPṬSṠṢƑƲƇ - Link: list of lists of positive integers, A
ŒP        - powerset (of A)
        Ƈ - keep those for which:
       Ʋ  -   last four links as a monad:
  Ṭ       -     untruth - e.g. [[2], [2, 5, 7]] -> [[0, 1], [0, 1, 0, 0, 1, 0, 1]]
   S      -     sum (columns of that)           -> [0, 2, 0, 0, 1, 0, 1]
    Ṡ     -     sign                            -> [0, 1, 0, 0, 1, 0, 1]
      Ƒ   -     is invariant under?:
     Ṣ    -       sort                          -> 0

```

---

If we may also identify the empty set (as producing a continuous range of zero positive integers) then \\$8\\$ bytes: `ŒPFṬṢƑƊƇ` \- test suite.
> 3 votes

# Answer
# Japt, 15 bytes

Outputs all possible solutions as the original arrays.

```
à fÊkÈrâ Íän dÉ

```

Try it
> 2 votes

# Answer
# Python, 150 bytes

```
lambda l:[x for i in range(len(l))for x in combinations(l,i+1)if(s:=sorted({*chain.from_iterable(x)}))==[*range(s[0],s[-1]+1)]]
from itertools import*

```

Attempt This Online!
> 2 votes

# Answer
# 05AB1E, 7 or 10 bytes

```
ā<æ¦ʒè˜ê¥P

```

Outputs all possible result, by outputting the 0-based indices like the challenge description.

Try it online or verify all test cases.

```
æ¦ʒ˜ê¥P

```

Outputs all possible results, by outputting the lists of lists themselves.

Try it online or verify all test cases.

If we're also allowed to include an empty list, the `¦` can be dropped in both programs for -1 byte.

**Explanation:**

```
ā           # Push a list in the range [1, (implicit) input-length]
 <          # Decrease each by 1 to the range [0, length)
  æ         # Get the powerset of this
   ¦        # Remove the empty leading list
    ʒ       # Filter the list of lists by:
     è      #  Index each into the (implicit) input list of lists
      ˜     #  Flatten it
       ê    #  Sorted-uniquify it
        ¥   #  Get all deltas / forward-differences
         P  #  Take the product (only 1 is truthy in 05AB1E)
            # (after which the filtered result is output implicitly)

```

The second program is similar, but without `ā<` so the powerset is done directly on the input-list of lists, and therefore also without `è`.
> 2 votes

# Answer
# JavaScript (Node.js), 84 bytes

```
f=([x,...y],v=[])=>x?f(y,[...v,x])||f(y,v):v.flat().map(i=>y[i]=0)|/0,,/.test(y)?0:v

```

Try it online!

```
f=([x,...y],v=[])=>
x?
  f(y,[...v,x])||f(y,v)   // [] is always a continuous range, so it's last tested
:
  v.flat().map(i=>y[i]=0) // Writing 0, so if v.flat().length==1 then it returns 0, not bother bitOR
  |/0,,/.test(y)?0:v      // Is there hole between, ,,,0,0,0,0 is fine, ,,,0,0,,0 isn't

```
> 1 votes

# Answer
# JavaScript (ES6), 81 bytes

*-1 thanks to @l4m2*

Returns a single solution as a space-separated string of integer lists.

```
f=([v,...a],m,o)=>v?f(a,m,o)||f(a,v.map(k=>m|=1<<k)|m,[o]+v+' '):(m|=m-1)&m+1?0:o

```

Try it online!
> 1 votes

# Answer
# Charcoal, 30 bytes

```
ＩΦＥＸ²ＬθΦθ﹪÷ιＸ²μ²∧ι¬⁻…·⌊Σι⌈ΣιΣι

```

Attempt This Online! Link is to verbose version of code. Outputs all solutions. Explanation:

```
    ²                           Literal integer `2`
   Ｘ                            Raised to power
      θ                         Input list
     Ｌ                          Length
  Ｅ                             Map over implicit range
        θ                       Input list
       Φ                        Filtered where
           ι                    Outer value
          ÷                     Integer divided by
             ²                  Literal integer `2`
            Ｘ                   Raised to power
              μ                 Inner index
         ﹪     ²                Is odd
 Φ                              Filtered where
                 ι              Current result
                ∧               Logical And
                        ι       Current result
                       Σ        Flattened
                      ⌊         Minimum
                           ι    Current result
                          Σ     Flattened
                         ⌈      Maximum
                    …·          Inclusive range
                   ⁻            Remove elements present in
                             ι  Current result
                            Σ   Flattened
                  ¬             Logical Not i.e. is empty
Ｉ                               Cast to string
                                Implicitly print

```

The output format is as follows: Each result is triple-spaced from each other, while within a result, the sets that comprise the result are double-spaced from each other and each element is output on its own line.
> 1 votes

# Answer
# Haskell, 94 bytes

```
import Data.List
s=take 1.filter((\s->s>[]&&s==[head s..last s]).nub.sort.concat).subsequences

```

Try it online!
> 1 votes

# Answer
# Brachylog, 9 bytes

```
⊇.cod~⟦₂∧

```

Try it online!

Generates solution with the largest number of sublists first.

### Explanation

```
⊇.           Output is a sublist of the input
  cod        Concatenate, sort, remove duplicates
     ~⟦₂     The resulting list must be a range between 2 integers
        ∧

```
> 1 votes

# Answer
# BQN, 35 bytes

```
({(⌈´¬⌊´)=≠}¨/⊢)∘((⍷∾)¨(⥊(↕2˘)/¨<))

```

Try it online!

### Explanation

```
({(⌈´¬⌊´)=≠}¨/⊢)∘((⍷∾)¨(⥊(↕2˘)/¨<))
                          (↕2˘)/¨<      Powerset (as a length-dimensional tensor)
                         (⥊        )    Deshape tensor to single dimension
                     ((⍷∾)¨          )  Concatenate, remove dupes in each element
                   ∘                    Then...
               /⊢                       filter the input by...
  (⌈´¬⌊´)                               whether range (span)...
         =                              is equal to...
          ≠                             length...
({          }¨    )                     for each element.

```

Originally had 34 bytes but there was a bug.
> 1 votes

# Answer
# Arturo, 57 bytes

```
$=>[select--powerset&[[]]=>[b:flatten&[]=--@..b\0max<=b]]

```

Try it

```
$=>[                  ; a function
    select            ; select elements from
    --powerset&[[]]   ; powerset of input without empty set
    =>[               ; begin select, assign current elt to &
        b:flatten&    ; flatten sets in current elt
        []=           ; is the empty block equal to
        --            ; set difference of
        @             ; evaluate block
        ..            ; range
        b\0           ; first element of b
        max<=         ; max of b
        b             ; and b (second argument to set difference)
    ]                 ; end select
]                     ; end function

```
> 1 votes

# Answer
# Python 3.8 (pre-release), 84 bytes

```
f=lambda a:max(f(a-{i})for i in a)if a and~-len(b:={*sum(a,())})-max(b)+min(b)else a

```

Try it online!

Takes a set of tuples as input and recursively removes items until a valid result is found.
> 1 votes

# Answer
# Julia 1.0, 66 bytes

```
!l=all(diff(sort([l...;])).<2) ? l : maximum(i->!setdiff(l,[i]),l)

```

Try it online!
> 1 votes

---
Tags: code-golf, number, array
---


title: Unflatten an Array

text:
# Question
Title: Unflatten an Array
This challenge was inspired by a question on Mathematica.SE.

Say you've got a nested list/array of some arbitrary structure (the lists at each level don't necessarily have the same length). For simplicity, we'll assume that the nodes are non-negative integers or empty arrays. As an example

```
[[[1, 3], 2], [1, 4], 12, [[0, [], 0], [5, [7]]]]

```

Sometimes it's more convenient to flatten that list to perform some manipulation of the nodes, e.g.

```
--> [1, 3, 2, 1, 4, 12, 0, 0, 5, 7]
--> [1, 1, 0, 1, 0, 0, 0, 0, 1, 1]

```

But in the end you actually want to preserve the original structure, so you want to turn this back into

```
--> [[[1, 1], 0], [1, 0], 0, [[0, [], 0], [1, [1]]]

```

Your task is to perform that last step.

Given a nested list of arbitrary non-negative integers, which represents the desired structure of the result, and a flat list of non-negative integers, which represent the desired values, reshape the flat list into the form of the structured list. You may assume that both lists contain the same number of integers.

As usual you don't have to deal with invalid input (e.g. the second list not being flat, the input being syntactically malformed, not having integers as nodes, etc.). You may modify the input arrays in your code.

You may write a function or program, taking input via STDIN, command-line argument or function argument, and you may return the result or print it to STDOUT. You may use any convenient list or string format to represent input and output (as long as the format is unambiguous and the input is not preprocessed). Also, the format of both inputs needs to be consistent (so you can't take one input as a string and the other as a list, for instance). You may take the input lists in either order, but please specify the exact input method in your answer.

One more restriction: you must not use regular expressions. This is an array manipulation challenge, not a string manipulation challenge.

This is code golf, so the shortest answer (in bytes) wins.

## Test Cases

```
Structure                             Values                 Result
[[[1,3],2],[1,4],12,[[0,0],[5,[7]]]]  [1,1,0,1,0,0,0,0,1,1]  [[[1,1],0],[1,0],0,[[0,0],[1,[1]]]]
[[[0,0],0],[0,0],0,[[0,0],[0,[0]]]]   [1,1,0,1,0,0,0,0,1,1]  [[[1,1],0],[1,0],0,[[0,0],[1,[1]]]]
[]                                    []                     []
[[]]                                  []                     [[]]
[0,1,2,3]                             [5,1,0,5]              [5,1,0,5]
[[[[[0]]]]]                           [123]                  [[[[[123]]]]]
[0,[1,[]],[[]],[2,3],[]]              [1,6,1,8]              [1,[6,[]],[[]],[1,8],[]]

```

# Answer
# CJam, ~~18 16~~ 13 bytes

```
lA,sNerN%l~]z

```

Takes input via STDIN in the same format as the previous CJam answer:

```
[0 [11 []] [[]] [2 3] []]
[1 6 1 8]

```

and outputs the result string to STDOUT

```
[1 [6 []] [[]] [1 8] []]

```

I simply treat the first line as string, convert all digit characters to newlines, split on one or more occurrences of newlines, put the second line as an array on stack, wrap in an array and zip together the two arrays (rows). Printing is automatic and as the first row was treated as string, it retains its brackets.

**Code expansion**

```
lA,sNerN%l~]z
l                     "Read the first line of input. This is the nested array";
 A,s                  "Get array [0,1,2...9] and  convert it to string '012..9'";
    Ner               "Replace all occurrences of 0,1,2,..9 with new line";
       N%             "Split on one or more occurrences of new line";
         l~           "Read the second line as an array";
           ]          "Wrap both the splitted string and the second line array";
                      "in an array";
            z         "Transpose the array, there by placing the numbers from second";
                      "input array in the split holes of first input string";

```

*Thanks to @user23013 for saving 3 bytes.*

Try it online here
> 9 votes

# Answer
# JavaScript, ES6, 44 bytes

```
f=(a,b,i=0)=>a.map(x=>x.map?f(x,b,i):b[i++])

```

This creates a function `f` which can be called like

```
f([0,[1,[]],[[]],[2,3],[]],[1,6,1,8])

```

i.e. the nested array and the values array as input arguments. The output of the function is the converted nested array.

This question is a very nice question for recursion, that is why the answer is a neat and sweet recursion function. I create a function `f` which converts the first argument using the `map` method. For each element, if the element is an array, it calls `f` again, otherwise, for integers, it gets the ith item and returns that, incrementing the value of `i`. The value of `i` is passed down in each recursive call, so as to maintain the order correct.

Array vs. Integer detection is yet again done using the `map` method. For an array variable, `map` is a valid function, while for integer variables, there is no property or function called `map` defined for the variable.

This works in a latest Firefox browser (due to ES6).
> 26 votes

# Answer
# JavaScript, ES6, 41 bytes

I was really impressed by Optimizer's answer, it was very cleverly done and I learned a lot. However on looking it over I found a way of shortening it slightly and fixing a small bug:

```
f=(a,b)=>a.map(x=>x.map?f(x,b):b.shift())

```

I took out the `i` variable and replaced it with a `shift()`. This makes it slightly shorter and fixes the problem with the fact that `i` is passed by value and not by reference, witch caused some numbers from the final array to repeat and some at the end not to be used. Again, Optimizer's answer was really well thought out, better than I could have done, I just fixed it a little.
> 19 votes

# Answer
# Dyalog APL, 14 characters

This is a no-brainer: `(∊a)←b`.

Normally, `∊a` means `a` flattened, but when it occurs on the left-hand side of an assignment, it does precisely what this problem is asking for. To comply with the requirement of being a function, it needs a few extra squiggles: `{a←⍺⋄(∊a)←⍵⋄a}` (curly braces for lambda;  and  for left and right argument;  for statement separator).

Test on tryapl.org. Note that in APL the empty numeric vector is denoted by  ("zilde"). One-element vectors are constructed with `(,A)` because `(A)` would mean a scalar. In the output, this thing:

```
┌⊖┐
│0│
└~┘

```

represents an empty numeric vector. The `0` in the centre shows the "prototypical element" which is not an element of the array.
> 18 votes

# Answer
# Python 2, 50

```
f=lambda s,v:v.pop(0)if s<[]else[f(x,v)for x in s]

```

This was a very beautiful problem. As I kept working on it, I kept realizing that bits of my code were unnecessary, and the logic collapsed into a simple expression. Most of the golfing was in finding the right algorithm.

`s` is the structure and `v` is the flat list of list. The idea is to check whether `s` is an integer with `s<[]` (Python 2 treats numbers as smaller than lists). If it is, simply take and return the first element of `v`, removing it from `v`. Otherwise, recurse down onto the sublists of `s`.

The `pop` is a piece of imperative magic in very functional-style code. Because all `v` point to the same instance, popping an element from one removes it from `v` in the whole execution tree, so each number in `v` is only used once. The list comprehension `[f(x,v)for x in s]` creates a call tree that is expanded depth-first and left-to-right, causing the elements of `v` to be slotted in the correct order.

I wrote this independently of grc's answer, but it turned out to the same up to moving a single `[` (and variable names). The move saves a char due to spacing. The bracket move means handling the node case immediately in the function, rather than as part of the list comprehension, which I hadn't considered.

We can save a char for *49* if we stretch the input requirements to take the value from STDIN and the structure as a function argument. This lets us use `map`.

```
v=input()
g=lambda s:v.pop(0)if s<[]else map(g,s)

```
> 12 votes

# Answer
# Ruby, 39

```
f=->a,b{a.map{|d|f[d,b]}rescue b.shift}

```

Recurses till the element in the list is an integer.
Since calling Integer.map gives an exception,
it goes to the rescue portion, which "pops/shift" the 1st element out of the 2nd list.

Regex soln... a bit longer:

```
f=->a,b{eval a.to_s.split(/\d+/).zip(b)*''}

```

Try it with some test cases
> 10 votes

# Answer
## Python, 51

```
f=lambda a,b:[b.pop(0)if x<[]else f(x,b)for x in a]

```

Example:

```
>>> f([0,[1,[]],[[]],[2,3],[]], [1,6,1,8])
[1, [6, []], [[]], [1, 8], []]

```
> 10 votes

# Answer
# Mathematica, 41 bytes

```
Function[,m[[i++]],Listable][i=1;m=#2;#]&

```

This is an unnamed function which takes the structure as the first argument and the list of values as the second argument (and returns a list).

This is a golfed version of the accepted answer on the question that inspired this challenge. I'm posting this myself, and will not accept this answer (should it actually remain the shortest, which I doubt). This is in order to prevent any one else from winning the challenge by basically copying the answer.

How it works:

* We define a `Listable` pure function. Listable functions are automatically applied to the elements of a list argument (recursively) instead of the list itself, so calling `f` on the structured list will basically return a list of the same structure with each integer `i` replaced by `f[i]`.
* We store the value list in the global `m` and a counter in `i`.
* Each time we call `f` (regardless of the argument) we return the next element of `m`.
> 5 votes

# Answer
# CJam, ~~43 37 35~~ 33 bytes

This one is a direct conversion of my JS answer. A bit long, most of which is taken up by type detection.

```
q~:B;{{_`La`&{F}{;BW):W=}?}%}:F~`

```

Takes the two input arrays on two lines of STDIN like

```
[[[1 3] 2] [1 4] 12 [] [[0 0] [5 [7]]]]
[1 1 0 1 0 0 0 0 1 1]

```

and outputs to STDOUT like

```
[[[1 1] 0] [1 0] 0 "" [[0 0] [1 [1]]]]

```

Try it online here
> 5 votes

# Answer
# Haskell, ~~113~~ 104 bytes (86 + 18 from datatype declaration)

```
data N=I Int|L[N]
L[]!v=(L[],v)
L(a:b)!v|(c,w)<-a!v,(L d,u)<-L b!w=(L$c:d,u)
_!(n:m)=(I n,m)
s#v=fst$s!v

```

Haskell does not have a built-in nested array datatype, so I had to roll my own. For this reason, the program contains only pattern matching and explicit structural recursion. The last test case reads

```
L[I 0,L[I 1,L[]],L[L[]],L[I 2,I 3],L[]]#[1,6,1,8]

```

and evaluates to

```
L[I 1,L[I 6,L[]],L[L[]],L[I 1,I 8],L[]]

```
> 5 votes

# Answer
# Rebol - 87 66 60

```
f: func[a[block!]b][map-each n a[any[attempt[f n b]take b]]]

```

Ungolfed:

```
f: func [a [block!] b] [
    map-each n a [
        any [
            attempt [f n b]
            take b
        ]
    ]
]

```

Example:

```
>> f [0 [1 []] [[]] [2 3] []]   [1 6 1 8]
== [1 [6 []] [[]] [1 8] []]

```
> 4 votes

# Answer
# C#, ~~225 + 13 = 239~~ ~~185 + 35 = 220~~ 172 + 35 = 207 bytes

Requires this:

```
using System;using o=System.Object;

```

Accepts `object[]`s as arguments.

```
o[]u(o[]a,o[]b){var c=a;int i=0;Action<o[],o[]>d=null;d=(e, f)=>{for(int j=0;j<e.Length;j++){if(e[j]is int){f[j]=b[i];i++;}else{d((o[])e[j],(o[])f[j]);}}};d(a,c);return c;}

```

Ungolfed code:

```
object[] Unflatten(object[] structure, object[] values)
{
    var c = structure;
    int i = 0;
    Action<object[], object[]> recursiveFunc = null;
    recursiveFunc = (e, f) =>
    {
        for (int j = 0; j < e.Length; j++)
        {
            if (e[j] is int)
            {
                f[j] = values[i]; i++;
            }
            else
            {
                recursiveFunc((object[])e[j], (object[])f[j]);
            }
        }
    };
    recursiveFunc(structure, c);
    return c;
}

```
> 4 votes

# Answer
# Python 2, 64 bytes

```
def g(N,L):f=lambda N:L.pop(0)if`N`<":"else map(f,N);return f(N)

```

I heard you like lists in lists so I put functions in functions.

*Edit: Looking at grc's answer now I realise that was completely unnecessary. Oh well...*
> 3 votes

# Answer
## SWI-Prolog 82

```
f([],A,[],A):-!.
f([H|T],A,[J|U],B):-(is_list(H),!,f(H,A,J,C);A=[J|C]),f(T,C,U,B).

```

Sample run:

```
?- f([[[1,3],2],[1,4],12,[[0,[],0],[5,[7]]]],[1,1,0,1,0,0,0,0,1,1],R,[]).
R = [[[1,1],0],[1,0],0,[[0,[],0],[1,[1]]]].

```

The last `[]` in the query is for checking for mismatched number of elements, which doesn't seem to be necessary in this question.
> 3 votes

# Answer
# Jelly, 1 byte

Try it online!

Jelly's `mold` builtin does this exactly. Takes input in reversed order (i.e. the flat list first)

---

# Jelly, 7 bytes

```
ßḢ}ŒḊ?€

```

Try it online!

Non-builtin is still pretty short. Takes input in normal order (flat list second)

## How it works

```
ßḢ}ŒḊ?€ - Main link. Takes l on the left and r on the right
      € - Over each element k in l:
     ?  -   If statement:
   ŒḊ   -   Condition: Depth. This yields 0 for integers and non-zero for lists
ß       -   Then: Recurse with k on the left and r on the right
 Ḣ}     -   Else: Pop and return the first element of r

```
> 3 votes

# Answer
# Erlang, ~~116~~ 93 Bytes

```
f(R,F)->put(n,F),[g(X)||X<-R].
g([H|T])->[g(H)|g(T)];g([])->[];g(E)->[H|T]=get(n),put(n,T),H.

```

Uses two impure functions `f` and `g`. `f` manipulates the process dictionary by setting `n` to the flat list and maps each element of the nested list to `g(X)`. `g` then sets `n` to the tail of the flat list every time it encounters a non-list value and returns the head of the flat list.
> 2 votes

# Answer
# Perl 5, 49 bytes

First argument is the template structure, second is the values.

```
sub u{($t,$l)=@_;ref$t?[map{u$_,$l}@$t]:shift@$l}

```

## Test Program

```
use Test::More;
use Test::Deep;

sub u{($t,$l)=@_;ref$t?[map{u$_,$l}@$t]:shift@$l}

cmp_deeply u([[[1,3],2],[1,4],12,[[0,0],[5,[7]]]],[1,1,0,1,0,0,0,0,1,1]),[[[1,1],0],[1,0],0,[[0,0],[1,[1]]]];
cmp_deeply u([[[0,0],0],[0,0],0,[[0,0],[0,[0]]]],[1,1,0,1,0,0,0,0,1,1]),[[[1,1],0],[1,0],0,[[0,0],[1,[1]]]];
cmp_deeply u([], []), [];
cmp_deeply u([[]], []), [[]];
cmp_deeply u([0,1,2,3], [5,1,0,5]), [5,1,0,5];
cmp_deeply u([[[[[0]]]]], [123]), [[[[[123]]]]];
cmp_deeply u([0,[1,[]],[[]],[2,3],[]], [1,6,1,8]), [1,[6,[]],[[]],[1,8],[]];
done_testing;

```
> 1 votes

# Answer
# Powershell: 115

the input array is $i, the mapping is $m, output is $o

```
$h={if($_.GetType().IsArray){if($_.c -eq 0){,@()}else{,@($_|%{.$h})}}else{$m[$c++]}};$i|%{$o=@();$c=0}{$o+=,(.$h)}

```

$h is a string containing the recursive function, and you can execute code contained in a string with .$h... And it would be 30 bytes shorter if powershell didn't insist on flattening single value arrays to scalars, and an array with a single null value to null

and a handy array structure viewer for verifying results

```
$j={if($_.GetType().IsArray){write-host '(' -n;($_|%{.$j});write-host ')' -n}else{write-host "$_" -n}};write-host '(' -n;$o|%{(.$j)}; write-host ')' -n;

```

## edit: 149

save as unflatten.ps1:

```
$m=[array]$args[1];$h={if($_.GetType().IsArray){if($_.c -eq 0){,@()}else{,@($_|%{.$h})}}else{$m[$c++]}};$args[0]|%{$o=@();$c=0}{$o+=,(.$h)};echo $o;

```

### edit: 136, inline output array creation and write-output

```
$m=[array]$args[1];$h={if($_.GetType().IsArray){if($_.c -eq 0){,@()}else{,@($_|%{.$h})}}else{$m[$c++]}};echo(,@($args[0]|%{$c=0}{.$h}))

```

call with .\unflatten.ps1 \[input array\] \[mapping array\]

the output is written to the pipeline- so run this first:

```
Function View-Array{
Param([Parameter(ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)]
      [array]$o)

    PROCESS{
    $j={if($_.GetType().IsArray){write-host '(' -n;($_|%{.$j});write-host ')' -n}else{write-host "$_" -n}};
    write-host '(' -n;$o|%{(.$j)}; write-host ')' -n;
    }
}

```

and run with

```
.\unflatten.ps1 [input array] [mapping array] | View-Array

```
> 1 votes

# Answer
## C#, (40+123)=163 bytes OR (67+81)=148 bytes

C# suffers from its static typing and long namespaces here.

**Array method**

Using statements:

```
using o=System.Object;using System.Linq;

```

Code:

```
o[] u(o[] x,o[] y){int i=0;Func<o[],o[],o[]> f=null;f=(a,b)=>a.Select(e=>e is int?b[i++]:f((o[])e,b)).ToArray();return f(x,y);}

```

**Stack method** (uses the Stack structure instead of arrays)

Using statements:

```
using s=System.Collections.Generic.Stack<object>;using System.Linq;

```

Code:

```
System.Func<s,s,s>f=null;f=(a,b)=>new s(a.Select(e=>e is int?b.Pop():f((s)e,b)));

```

First attempts, first code golf here.
> 1 votes

# Answer
# , 6 bytes

```
relist

```

Try it online!

`relist` performs the exact operation described here; and has been included since R 2.6.0 (released Oct. 3, 2007).
> 1 votes

# Answer
# Vyxal, 1 byte

Try it Online!

Same as Jelly
> 1 votes

# Answer
# Appleseed, 136 bytes

```
(def M(q((S D)(if S(if(type?(head S)Int)(cons(head D)(M(tail S)(tail D)))(cons(M(head S)D)(M(tail S)(drop(length(flatten(head S)))D))))(

```

Defines a recursive function that takes two lists. Try it online!

### Ungolfed/commented

```
; Define mold
(def mold
  ; as a function of two arguments, the nested list representing the structure
  ; and the flat list containing the data
  (lambda (shape data)
    ; If the shape list is nonempty:
    (if shape
      ; If its first element is an int:
      (if (type? (head shape) Int)
        ; Construct the result list from
        (cons
          ; the first element of the data list
          (head data)
          ; followed by a recursive call with all but the first element of both lists
          (mold (tail shape) (tail data)))
      ; Else, its first element is a list:
        ; Construct the result list from
        (cons
          ; a recursive call with the first element of the shape list
          (mold (head shape) data)
          ; followed by a recursive call with
          (mold
            ; all but the first element of the shape list
            (tail shape)
            ; and all but the first N elements of the data list, where N is the number
            ; of data elements used in unflattening the head of the shape list
            (drop (length (flatten (head shape))) data))))
    ; Else, the shape list is empty:
      ; Return the empty list
      nil)))

```
> 0 votes

# Answer
# Japt, 10 bytes

```
Ë¶Ô?ßDÔ:Vv

```

Try it
> 0 votes

---
Tags: code-golf, array, ragged-list
---


# Question
Title: Find distance between the closest 3D points
Your task is to take \\$n \ge 2\\$ points in 3D space, represented as 3 floating point values, and output the Euclidean distance between the two closest points. For example

$$A = (0, 0, 0) \\ B = (1, 1, 1) \\ C = (4, 0, 2)$$

would output \\$\sqrt3 = 1.7320508075688772...\\$, the distance between \\$A\\$ and \\$B\\$.

The Euclidean distance, \\$E\\$, between any two points in 3D space \\$X = (a\_1, b\_1, c\_1)\\$ and \\$Y = (a\_2, b\_2, c\_2)\\$ is given by the formula

$$E = \sqrt{(a\_2 - a\_1)^2 + (b\_2 - b\_1)^2 + (c\_2 - c\_1)^2}$$

This is so the shortest code in bytes wins

# Answer
> 6 votes
# 05AB1E, 8 bytes

```
œ€ü-nOtß

```

Try it online!

**Commented**:

```
œ         # take all permutations of the input
 €        # for each permutation:
   -      #   take the element-wise difference
  ü       #   between each pair of adjacent points
    n     # square each number
     O    # sum all difference-lists
      t   # take the square root of every sum
       ß  # take the minimum

```

# Answer
> 11 votes
# , 34 bytes

```
function(...)min(dist(rbind(...)))

```

Try it online!

This is a nice opportunity to use 's `...` syntax to define a function that can accept a variable number of arguments; in this case, the `x,y,z` coordinates of each point.

The `dist` function calculates the pairwise distance between all rows of a matrix, using a chosen method - luckily, the default is 'euclidean' and so isn't specified in this case.

Of course, it could be even shorter if we allow the input to already be combined-together as a matrix, but this wouldn't be so neat...

# , 23 bytes

```
function(m)min(dist(m))

```

Try it online!

# Answer
> 9 votes
# Wolfram Language (Mathematica), 33 bytes

```
Min[Norm[#-#2]&@@@#~Subsets~{2}]&

```

Try it online!

# Answer
> 7 votes
# Python 3, ~~106~~ ~~95~~ 93 bytes

Saved 11 bytes thanks to fireflame241!!!
Saved 2 bytes thanks to Jonathan Allan!!!

```
lambda l:min(sum((a-b)**2for a,b in zip(l[p],v))**.5for q,v in enumerate(l)for p in range(q))

```

Try it online!

Inputs a list of points as tuples and returns the Euclidean distance between the two closest points.
Works with points of any dimension so long as they are consistent within the list.

# Answer
> 7 votes
# Jelly, 9 bytes

```
ŒcZ_/²§Ṃ½

```

Try it online!

Works with points of any dimension

### Explanation

```
ŒcZ_/²§Ṃ½ # Take as input a list of points, where each point is a list of coordinates
Œc        # All pairs of two distinct points [(p1,p2),(p1,p3),...]
  Z       # Transpose to get two lists of points [[p1,p1,...],[p2,p3,...]]
   _/     # Depth-1 vectorizing difference [p1-p2, p1-p3, ...]
     ²§   # Square coordinates and sum each
       Ṃ  # Minimum
        ½ # Square root

```

# Answer
> 6 votes
# Ruby 2.7, ~~79~~ 65 bytes

*Saved a whooping 14 bytes, thanks to Sisyphus!*

```
->s{s.combination(2).map{_1.zip(_2).sum{|a,b|(a-b)**2}**0.5}.min}

```

Try it online!

* Expects an array of points!
* TIO uses an older version of Ruby, so `|p,q|p,q` is replaced by `_1,_2` to save three bytes (as suggested by Dingus).

# Answer
> 4 votes
# Brachylog, 14 bytes

```
{⊇Ċz-ᵐ^₂ᵐ+√}ᶠ⌋

```

Try it online!

Boring and straightforward.

```
             ⌋    The output is the minimum of
{          }ᶠ     every possible
          √       square root of
         +        a sum of
      ^₂ᵐ         the squares of
    -ᵐ            the differences between
   z              the coordinates for each axis
 ⊇                for a sublist of the input
  Ċ               containing two elements.

```

# Answer
> 3 votes
# JavaScript (ES6), 86 bytes

```
a=>a.map(m=([x,y,z],i)=>a.map(([X,Y,Z])=>m=!i--|(d=Math.hypot(x-X,y-Y,z-Z))>m?m:d))&&m

```

Try it online!

### Commented

```
a =>                          // a[] = list of triplets
  a.map(m = ([x, y, z], i) => // for each triplet (x,y,z) at position i in a[]:
    a.map(([X, Y, Z]) =>      //   for each triplet (X,Y,Z) in a[]:
      m =                     //     update the minimum distance m:
        !i-- | (              //       decrement i; if it was equal to 0
          d = Math.hypot(     //       or the Euclidean distance d:
            x - X,            //         between (x,y,z)
            y - Y,            //         and (X,Y,Z)
            z - Z             //
        )) > m ?              //       is greater than m:
          m                   //         leave m unchanged
        :                     //       else:
          d                   //         update m to d
    )                         //   end of inner map()
  ) && m                      // end of outer map(); return m

```

# Answer
> 3 votes
# Husk, 10 bytes

```
▼ṁẊȯ√ṁ□z-Ṗ

```

Try it online!

```
▼           # minimum of
 ṁ          # sums of applying function to
         Ṗ  # all subsets of input
            # (this may include subsets of >2 points,
            # but that's ok...)
  Ẋȯ√ṁ□z-   # the function:
  Ẋȯ        # apply to all adjacent pairs
            # (...that's why it was ok if there were >2 points
            # in any sublist)
    √       # square root of
     ṁ□     # sum of squres of
       z-   # element-wise differences

```

# Answer
> 3 votes
# Haskell, ~~75~~ 74 bytes

```
g[]=[]
g(x:t)=[(sum$zipWith((**2).)(map(-)x)z)**0.5|z<-t]++g t
f=minimum.g

```

Try it online!

```
g[]=[]        - edge case for combinations
g(x:t)=[ ... |z<-t]++g t
              - combinations
(sum$zipWith(\a b->(a-b)**2)x z)**0.5
              - compute hypo..
f=minimum.g   - return minimum value found

```
* Saved 1 thanks to @Unrelated String insane idea `(sum$zipWith(\a b->(a-b)**2)x z)**0.5` becomes `(sum$zipWith((**2).)(map(-)x)z)**0.5` e.g. we first map `x` to obtain a list of partially applied subtractions , then we zipWith `(**2).` (read "compose with square") which firstly finishes the subtraction and then computes the square. If I understood correctly O.o

# Answer
> 2 votes
## Octave/MATLAB with Statistics package/toolbox, 17 bytes

```
@(x)min(pdist(x))

```

Try it online!

# Answer
> 2 votes
# Japt `-g`, ~~15~~ 14 bytes

The spec asks us to get the minimum but the lone test case gets the maximum so I don't know which to output. I've gone with the former but if that's not right then use the `-h` flag instead.

```
à2 ËÕËrnÃx²¬ÃÍ

```

Try it

# Answer
> 2 votes
# Scala 3, 72 bytes

```
s=>math.sqrt((for> <-s;| <-s- >yield(>zip|map(_-_)map(x=>x*x)).sum).min)

```

Try it online!

Accepts a `Set[List[Int]]` so that it can use `-` to ensure a point is not compared to itself.

This is my first time using Scala 3's new control syntax to save 2 bytes.

# Answer
> 2 votes
# , 29 bytes

```
[:<./@,+/&.:*:@:-"1/~+_*[:=#\

```

Try it online!

```
[:<./@,+/&.:*:@:-"1/~+_*[:=#\
                           #\ 1…N
                        [:=   identity matrix NxN
                      _*      times infinity
                     +        plus
                 "1/~         the table with the coordinate triples:
              @:-             a - b and
         &.:*:                under square
       +/                     summed
         &.:*:                reverse square
[:<./@,                       flatten the table and get the min entry

```

# Answer
> 2 votes
# Perl 5 `-MList::Util=min,sum`, ~~81~~ 77 bytes

*@KjetilS shaved 4 bytes.*

```
sub f{min map{@b=@$_;map{sqrt sum map($_-$b[$j++%3])**2,@$_}@_[++$i..$#_]}@_}

```

Try it online!

# Answer
> 2 votes
# C (gcc), ~~155~~ 147 bytes

Thanks to ceilingcat for -8 and an interesting (ab)use of `hypot`!

Takes a counted array of coordinates.

```
#define g(x)hypot(c[x+j]-c[x+i],
i,j;float f(s,c,d,l)float*c,d,l;{for(l=-1,s*=3,i=0;i<s;i+=3)for(j=i;(j+=3)<s;l=l<0|d<l?d:l)d=g(2)g(1)g()0)));s=l;}

```

Try it online!

# Answer
> 1 votes
# Charcoal, 22 bytes

```
Ｉ₂⌊ΦＥθ⌊Ｅ…θκΣＸＥλ⁻ν§ιξ²κ

```

Try it online! Link is to verbose version of code. Takes `n`-dimensional vectors. Explanation:

```
     θ                  Input list
    Ｅ                   Map over vectors
         θ              Input list
        …               Truncate to length
          κ             Outer index
       Ｅ                Map over remaining vectors
              λ         Inner vector
             Ｅ          Map over coordinates
                 §ιξ    Coordinate of outer vector
                ν       Current coordinate
               ⁻        Difference
            Ｘ       ²   Squared
           Σ            Summed
      ⌊                 Take the minimum square sum
   Φ                 κ  Filter out minimum of empty list
  ⌊                     Take the minimum
 ₂                      Take the square root
Ｉ                       Cast to string
                        Implicitly print

```

# Answer
> 1 votes
# Factor, 67 bytes

```
[ dup [ v- norm ] cartesian-map [ head ] map-index concat infimum ]

```

Try it online!

Evaluates self-cartesian-product by vector distance, takes the lower triangular matrix (without diagonals), and evaluates the minimum of all values.

```
[                                ! anonymous lambda
  dup [ v- norm ] cartesian-map  ! self-cartesian-product by vector distance
  [ head ] map-index             ! for each array at index i, take first i elems
  concat infimum                 ! minimum of all values
]

```

---

# Factor, 73 bytes

```
USE: math.combinatorics
[ 2 [ first2 v- norm ] map-combinations infimum ]

```

Try it online!

Factor has a built-in for generating combinations, but it is way too long (`USE: math.combinatorics map-combinations` is already 40 bytes).

# Answer
> 1 votes
# Python 3, 79 bytes

I'm new here and not completely sure this follows the rules, LMK if this isn't valid!

```
lambda p:min(sum((a-b)**2for a,b in zip(x,y))**.5for x in p for y in p if x!=y)

```

# Answer
> 1 votes
# Vyxal , 9 bytes

```
∪2ḋƛ÷∆d;g

```

```
∪           # Delete duplicates
 2ḋ         # All subsets of length 2
   ƛ÷∆d;    # Euclidean distance of every subset
        g   # Minimum

```

Try it Online!

# Answer
> 0 votes
# Python 3, 82 bytes

```
f=lambda a,*b:[*b]and[min([sum((x-y)**2for x,y in zip(a,q))**.5for q in b]+f(*b))]

```

Try it online!

---

# Python 3 with SciPy, 58 bytes

```
lambda*a:min(pdist(a))
from scipy.spatial.distance import*

```

Try it online!

# Answer
> 0 votes
# Fortran (GFortran), ~~206~~ ~~182~~ ~~148~~ 144 bytes

```
function d(A,n);real A(3,n);t=0
do 5 k=1,n-1;do 5 j=2,n;s=0;do i=1,3;s=s+(A(i,k)-A(i,j))**2;enddo
5 if(t==0)t=s;if(s>0.and.t>s)t=s;d=sqrt(t);end

```

try it online! ~~148bytes~~ ~~182bytes~~ ~~206bytes~~

\*line 1: sets up array, reads in data
\*line 2: iterates over rows `j`,`k`, and sums the difference-squares
\*line 3: initialises min distance `t`, compares current Euclidean squared distance `s`, taking the lower number, and ignores a distance of `0` (dupe points)

Saved ***24 bytes*** by removing the `allocate` stuff and giving the array preset dimensions. A possible improvement for my other Fortran answers!
Saved another ***34 bytes*** by using a subroutine and moving I/O to the main program. Replaced repeated `enddo`s with a line number. Removed a placeholder variable `q`. Some inspiration taken from this fortran golf. I went looking for a useful intrinsic like NORM2 or HYPOT but couldn't find one for this problem.
Saved ***4 bytes*** by replacing the `subroutine` with a `function`

# Answer
> 0 votes
# Julia 1.8, 52 bytes

```
a>b...=min(>(b...),@.splat(hypot)(b-[a])...)
>()=Inf

```

Try it online!

I feel like there is a better way but I can't figure it out. This will work for bigger dimensions as well

# Julia 1.0, 53 bytes

```
a>b...=min(>(b...),(b.|>i->hypot(a-i...))...)
>()=Inf

```

Try it online!

---
Tags: code-golf, math, geometry
---


# Question
Title: Classify a surface from its fundamental polygon
This question is an extension of Who's that Polygon? to arbitrary numbers of sides.

A fundamental polygon for a surface is an polygon with a prescribed pairing for all its \\$2n\\$ sides, each marked with an arrow, such that identifying the sides according to this pairing and the arrow directions produces the surface (up to homeomorphism).

This pairing can be described as a cyclic *fundamental word* with two each of \\$n\\$ distinct symbols, where any symbol may be inverted to represent an arrow pointing opposite to the direction of travel around the polygon. For example, the word \\$abab^{-1}\\$ describes the Klein bottle:

In light of the classification theorem for surfaces, which states that every closed 3D surface is homeomorphic to *either* the connect-sum of \\$g\ge0\\$ tori (including the sphere at \\$g=0\\$) *or* the connect-sum of \\$k\>0\\$ cross-caps, it may not be immediately obvious what surface a fundamental polygon represents. Fortunately canonical forms and a canonicalisation process exist – the material below comes from Gerhard Ringel's *Map Color Theorem*.

## Canonical words for surfaces

The canonical fundamental word for the connect-sum of \\$g\ge0\\$ tori, with genus \\$g\\$, is $$a\_1b\_1a\_1^{-1}b\_1^{-1}a\_2b\_2a\_2^{-1}b\_2^{-1}\dots a\_gb\_ga\_g^{-1}b\_g^{-1}$$ So the sphere's canonical word is the empty string, the normal torus's is \\$aba^{-1}b^{-1}\\$ and so on.

The canonical fundamental word for the connect-sum of \\$k\>0\\$ cross-caps, with genus \\$-k\\$ (although this is incorrect, this definition is used here because then the integers bijectively correspond to surface types) is $$a\_1a\_1a\_2a\_2\dots a\_ka\_k$$ The real projective plane and Klein bottle are the \\$k=1\\$ and \\$k=2\\$ cases of this sequence, so their canonical words are \\$aa\\$ and \\$aabb\\$ respectively.

## Canonicalisation

The surface represented by a fundamental word is unchanged if

* the word is cyclically rotated: \\$aabb\to abba\\$
* a symbol is inverted: \\$aabb\to aab^{-1}b^{-1}\\$
* a symbol and its **adjacent** inverse are cancelled: \\$caba^{-1}b^{-1}c^{-1}\to aba^{-1}b^{-1}\\$

The surface is orientable iff each symbol appears once inverted and once uninverted in the word. In that case a "handle" can be extracted by the following word transformation, where \\$Q,R,S\\$ are not all empty: $$PaQbRa^{-1}Sb^{-1}T\to PSRQTaba^{-1}b^{-1}$$ Repeating this process with intermediate cancellation leads to the canonical form for orientable surfaces described above.

If the two occurrences of a symbol are both inverted or both uninverted, the surface is non-orientable. In this case a cross-cap may be extracted by the following word transformation, where \\$Q^{-1}\\$ is the group-theoretic inverse (so e.g. \\$(abc)^{-1}=c^{-1}b^{-1}a^{-1}\\$): $$PaQaR\to aaPQ^{-1}R$$ Do this as many times as possible to get a word of the form \\$a\_1a\_1\dots a\_ia\_iO\\$, where \\$O\\$ is the fundamental word of an *orientable* surface. Canonicalise \\$O\\$ as above and determine its genus \\$g\\$; the canonical form of the full non-invertible surface is then \\$a\_1a\_1\dots a\_{i+2g}a\_{i+2g}\\$, because a handle turns into two cross-caps in the presence of another cross-cap.

## Example

This picture from one of my MathsSE answers is an embedding of the Johnson graph \\$J(5,2)\\$:

The star-shaped border represents a fundamental polygon where

* each black (dark blue) arc matches the grey (light blue) arc 5 steps away going counterclockwise
* each golden yellow arc matches the light yellow arc 7 steps away going clockwise
* in all cases the matching is parallel (as hinted by the faded exterior), so the surface is orientable

Thus the corresponding fundamental word is $$ah^{-1}bf^{-1}ca^{-1}db^{-1}ei^{-1}fd^{-1}ge^{-1}hc^{-1}ig^{-1}$$ which reduces as follows: $$(a)h^{-1}(b)f^{-1}c(a^{-1})d(b^{-1})ei^{-1}fd^{-1}ge^{-1}hc^{-1}ig^{-1}$$ $$\to (d)f^{-1}(c)h^{-1}ei^{-1}f(d^{-1})ge^{-1}h(c^{-1})ig^{-1}aba^{-1}b^{-1}$$ $$\to ge^{-1}\[hh^{-1}\]ei^{-1}\[ff^{-1}\]ig^{-1}aba^{-1}b^{-1}dcd^{-1}c^{-1}$$ $$\to g\[e^{-1}e\]\[i^{-1}i\]g^{-1}aba^{-1}b^{-1}dcd^{-1}c^{-1}$$ $$\to\[gg^{-1}\]aba^{-1}b^{-1}dcd^{-1}c^{-1}$$ $$\to aba^{-1}b^{-1}dcd^{-1}c^{-1}$$ Thus the surface has genus 2, which matched my expectation when I constructed the embedding based on a triangulation with 10 vertices and 36 edges – by Euler's formula such a triangular embedding, if orientable, must live on the genus-2 surface. Indeed (glue the three ends of the open surface below in a Y-shape so that the colours match):

## Task

Given a list of *nonzero integers* where the magnitudes from 1 to \\$n\\$ appear exactly twice each, representing a fundamental word with a negative number marking an inverted symbol, output the genus of the surface corresponding to that fundamental word, using the definition above where a negative genus \\$-k\\$ means "connect-sum of \\$k\\$ cross-caps".

This is ; fewest bytes wins.

## Test cases

```
[] -> 0
[1, -1] -> 0
[1, 1] -> -1
[1, 2, -2, -1] -> 0
[1, 2, -1, -2] -> 1
[1, 2, 1, -2] -> -2
[1, 2, 1, 2] -> -1
[-2, -2, -1, 1] -> -1
[1, 2, 3, -1, -2, -3] -> 1
[-3, 1, 3, -2, 1, 2] -> -2
[1, 2, 3, 4, -1, -2, -3, -4] -> 2
[1, 2, 4, 4, -2, -3, 1, -3] -> -2
[1, -8, 2, -6, 3, -1, 4, -2, 5, -9, 6, -4, 7, -5, 8, -3, 9, -7] -> 2
[1, -8, 2, -9, 3, -1, 4, -2, 5, -3, 6, -4, 7, -5, 8, -6, 9, -7] -> 3
[4, 3, 2, 1, 1, 2, 3, 4] -> -4
[3, 4, 1, 2, 6, 7, -4, 5, -2, -3, -7, -1, -5, -6] -> 3
[1, 2, 3, 3, -1, -2] -> -3

```

# Answer
> 5 votes
# Curry (PAKCS), 159 bytes

```
f[]=0
f(p++a:b:q)|a+b==0=f$p++q
f(p++a:q++a:r)=g$f$p++reverse[-x|x<-q]++r
f(p++a:q++b:r++c:s++d:t)=(a+c)!(b+d)$f$p++s++r++q++t
g x=min(-2*x)x-1
(0!0)x|x>=0=x+1

```

Attempt This Online!

# Answer
> 2 votes
# Vyxal, ~~56~~ ~~49~~ 46 bytes

```
(ṫ~c[€ɖ‡ṘNf&›|p;ȧ:(ṫ€:ḣt↔h:ḃ∇v€ÞfḣṘJf)W∑¥[d¥+N

```

Try it Online!

First we extract all cross-caps. This is done by looking at the last symbol. If it occurs in the same orientation twice, the cross-cap is extracted by taking a word \\$PaQa\\$ and transforming it into \\$PQ^{-1}\\$, incrementing the register each time it happens. Otherwise the word is rotated to the left. This is repeated as many times as the number of symbols in the input.

```
(ṫ~c[€ɖ‡ṘNf&›|p;
(              ; # run the following once for each symbol in the input:
                                               [1, 2, 3, 1, -2, 3]
 ṫ               #   tail extract              [1, 2, 3, 1, -2], 3
  ~c             #   contains? without popping [1, 2, 3, 1, -2], 3, 1
    [            #   if:
     €           #     split on                [[1, 2], [1, -2]]
      ɖ‡--       #     apply the following to the second item:
        ṘN       #       reverse and negate
                                               [[1, 2], [2, -1]]
          f      #     flatten                 [1, 2, 2, -1]
           &›    #     increment register
             |   #   else:
              p  #     prepend

```

Now we are left with a word of an orientable surface so we can forget which symbols are inverted.

Now we extract handles and remove adjacent inverses. This is done by looking at the last symbol. We write the word as \\$PaQa\\$. If there is a common symbol in \\$P\\$ and \\$Q\\$ there exists a handle \\$RbSaTbUa\\$ so we transform the word into \\$RUTS\\$, leaving a 1 on the stack each time it happens. If there are no common symbols in \\$P\\$ and \\$Q\\$ then \\$a\\$ will eventually become adjacent with itself so we can delete it, leaving a 0 on the stack each time it happens. This is repeated as many times as the number symbols left in the word after extracting cross-caps.

```
ȧ:(ṫ€:ḣt↔h:ḃ∇v€ÞfḣṘJf)
ȧ                      # absolute value
 :(                  ) # run the following once for each symbol in the word:
   ṫ                   #   tail extract
    €                  #   split on
     :                 #   duplicate
      ḣ                #   head extract
       t               #   tail
        ↔              #   intersection
         h             #   head
          :            #   duplicate
           ḃ           #   boolify
            ∇          #   shift (leave it on the stack for later)
             v€        #   vectorise split on
               Þf      #   flatten by one level
                 ḣ     #   head extract
                  Ṙ    #   reverse
                   Jf  #   join and flatten

```

All that's left is to combine the number of cross-caps extracted and number of handles extracted.

```
W∑¥[d¥+N
W        # wrap stack in a list
 ∑       # sum
  ¥[     # if register is non-zero
    d    #   double
     ¥+  #   add register
       N #   negate

```

---
Tags: code-golf, math, classification, topology, pattern-matching
---


# Question
Title: 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)

# Answer
> 12 votes
# , 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.

# Answer
> 8 votes
# 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

# Answer
> 6 votes
# 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

```

# Answer
> 6 votes
# Perl 6, 19 bytes

```
*.classify(*.chars)

```

Try it online!

Pretty much does exactly as asked.

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

```

# Answer
> 6 votes
# PowerShell, 18 bytes

```
$args|group Length

```

Try it online!

# Answer
> 5 votes
# 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!

# Answer
> 4 votes
# 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!

# Answer
> 4 votes
# 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.

# Answer
> 4 votes
# 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!

# Answer
> 4 votes
# 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)

```

# Answer
> 4 votes
# jq, 53 bytes

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

```

Try it online!

# Answer
> 3 votes
# Ruby, ~~22~~ 28 bytes

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

```

Try it online!

# Answer
> 3 votes
# 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

```

# Answer
> 3 votes
# 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!

# Answer
> 3 votes
# 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

# Answer
> 3 votes
# 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.

# Answer
> 2 votes
# 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.

# Answer
> 2 votes
# 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

# Answer
> 2 votes
# 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.

# Answer
> 2 votes
# Perl 5 (`-040n`), ~~45~~, ~~40~~, 34 bytes

-5 bytes thanks to Xcali

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

```

Try it online!

# Answer
> 2 votes
# 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

```

# Answer
> 2 votes
# PHP, 62 bytes

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

```

Try it online!

# Answer
> 2 votes
# , 22 bytes

-2 bytes thaks to FrownyFrog

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

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

```

Try it online!

# , 24 bytes

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

```

Try it online!

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

# Answer
> 2 votes
# Scala, 30 42 bytes

Correction thanks to Value Ink

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

```

Try it online!

# Answer
> 2 votes
# 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).

# Answer
> 2 votes
# 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.

# Answer
> 2 votes
# Wolfram Language (Mathematica), 30 bytes

```
KeySort@*GroupBy[StringLength]

```

Try it online!

# Answer
> 1 votes
# 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!

# Answer
> 1 votes
# 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!

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 48 bytes

```
a=>a.GroupBy(k=>k.Length,v=>v).OrderBy(g=>g.Key)

```

Try it online!

-1 byte thanks to @dzaima

-43 bytes if returning the raw grouping is allowed, thanks to @someone

-18 bytes by switching to the Visual C# Interactive Compiler

# Answer
> 1 votes
JULIA
Some 55 bytes:

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

```

Try it online

# Answer
> 1 votes
# Python 3, 81 bytes

Outputs a dictionary instead of a list or tuple:

```
lambda s:dict(sorted((len(x),list(filter(lambda y:len(y)==len(x),s)))for x in s))

```

Try it online!

# Answer
> 1 votes
# Röda, 53 bytes

```
{a=new map;a[#_]+=_1 if[a[#_1]?]else a[#_1]=[_1];[a]}

```

Try it online!

## Explanation

```
{a=new map;a[#_]+=_1 if[a[#_1]?]else a[#_1]=[_1];[a]}
{                                                   } anonymous function
 a=new map;                                           let a be a hash map
                                                      for each _1:
                     if[       ]else            ;     if
                        a[#_1]?                         a[length(_1)] exists
           a[#_]+=_1                                  then append _1 to a[length(_1)]
                                     a[#_1]=[_1]      else a[length(_1)] = [_1]
                                                 [a]  return a

```

# Answer
> 1 votes
# APL(NARS), chars 34, bytes 68

```
{a,⍨¨↑¨≢¨¨a←a⊂⍨≢¨a←a[⍋a←⍵⊂⍨' '≠⍵]}

```

test:

```
  f←{a,⍨¨↑¨≢¨¨a←a⊂⍨≢¨a←a[⍋a←⍵⊂⍨' '≠⍵]}
  ⎕fmt f 'Code Golf and coding challenges Meta'
┌4──────────────────────────────────────────────────────────────────────┐
│┌2───────┐ ┌4────────────────────────┐ ┌2──────────┐ ┌2───────────────┐│
││  ┌3───┐│ │  ┌4────┐ ┌4────┐ ┌4────┐│ │  ┌6──────┐│ │   ┌10─────────┐││
││3 │ and││ │4 │ Code│ │ Golf│ │ Meta││ │6 │ coding││ │10 │ challenges│││
││~ └────┘2 │~ └─────┘ └─────┘ └─────┘2 │~ └───────┘2 │~~ └───────────┘2│
│└∊───────┘ └∊────────────────────────┘ └∊──────────┘ └∊───────────────┘3
└∊──────────────────────────────────────────────────────────────────────┘
  ⎕fmt f 'My v3ry 3xc13nt m0th3r 53rv3d u5 pzz@5 #Ju'
┌6─────────────────────────────────────────────────────────────────────────────────────────┐
│┌3────────────┐ ┌2───────┐ ┌2────────┐ ┌2─────────┐ ┌3────────────────────┐ ┌2───────────┐│
││  ┌2──┐ ┌2──┐│ │  ┌3───┐│ │  ┌4────┐│ │  ┌5─────┐│ │  ┌6──────┐ ┌6──────┐│ │  ┌7───────┐││
││2 │ My│ │ u5││ │3 │ #Ju││ │4 │ v3ry││ │5 │ pzz@5││ │6 │ 53rv3d│ │ m0th3r││ │7 │ 3xc13nt│││
││~ └───┘ └───┘2 │~ └────┘2 │~ └─────┘2 │~ └──────┘2 │~ └───────┘ └───────┘2 │~ └────────┘2│
│└∊────────────┘ └∊───────┘ └∊────────┘ └∊─────────┘ └∊────────────────────┘ └∊───────────┘3
└∊─────────────────────────────────────────────────────────────────────────────────────────┘

```

# Answer
> 1 votes
# Lua, ~~85~~ 94 bytes

**changed to to function format +9 bytes**

```
r={}m=0 for j=1,#i do w=i[j]l=#w m=l>m and l or m c=r[l]r[l]=c and w..","..c or w end return r

```

Try it online!

# Answer
> 1 votes
# Husk, 8 bytes

```
mṠ,oL←kL

```

Try it online!

so close..

# Answer
> 0 votes
# Arturo, 32 bytes

```
$=>[gather arrange&=>size=>size]

```

Try it

# Answer
> 0 votes
# Python 3, 64 bytes

```
lambda x:{i:[*filter(lambda a:len(a)==i,x)]for i in range(1,11)}

```

Try it online!

# Answer
> 0 votes
# Zsh, 52 bytes

```
for i;printf \ $i>>$#i;(for j (*)<<<$j`<$j`)|sort -n

```

Try it online!

For each argument/word `i`, append to a file called `$#i` (length of `i`).
For each resulting file `j (*)`, print the filename `<<<$j` and contents `<$j`, and sort.

---
Tags: code-golf, string, sorting
---