title: Palindrome distance

text:
# Question
Title: Palindrome distance
Find what is the distance for a given string to its closest palindrome of the same length.

For this task I decided to give the characters further away from the string's center more weight (think of it as contributing more torque), proportional to their distance to the center.

Let's define the palindrome distance for a string \\$s\\$ as the sum of all products of the absolute difference of the corresponding pairs, equally spaced from the string's centre, and their distance to the center.

\\$D\_p=\displaystyle\sum\_{i=1}^{d}\left(d-i+1\right)|s\_i-s\_{l-i+1}|\\$

where \\$l\\$ is the length of \\$s\\$ and \\$d = \left\lfloor\frac{l}{2}\right\rfloor\\$

Since the middle character doesn't contribute anything to the sum, \\$d\\$ for strings with odd length \\$l\\$ is equal to \\$d\\$ for strings with length \\$l-1\\$.

## Task

Given string \\$s\\$ with length \> 1 find \\$D\_p(s)\\$

## Input

One of the following:

* a string;
* a list of characters;
* a list of numbers.

## Output

An integer - the palindrome distance of the input string.

## Test cases

```
"aa" -> 0
"bab" -> 0
"abca" -> 1
"cbade" -> 6
"hello" -> 21
"code-golf" -> 45
"neveroddoreven" -> 0
"Neveroddoreven" -> 224

```

## Winning criteria

The shortest code in bytes in every language wins.

# Sandbox

# Answer
# Haskell, 50 bytes

```
u#(a:b)|c:d<-reverse b=u+(abs(c-a)+u)#d
u#_=u
(0#)

```

Try it online!

Look ma! No multiplication! (or division)

## Explanation

Rather than explain what this answer *does* which I think would only be confusing, I think I will give an abridged explanation how I came to this answer.

First off Haskell is a recursive language, so we want to phrase this in a recursive way. This is pretty easy to do, if we have a list

```
[ a , d... , c ]

```

Then we take the "palindrome distance" of the middle bit `d` and add on `abs(a-c)*(div(length d)2)`. If it is anything else the answer is zero.

Now getting the last element is a little hard in Haskell, but getting the first is dead simple. So one way to get the last element is to reverse the list and get the first one. In order to get the middle we then have to reverse that back to the original order.

Our first breakthrough is to realize that when you reverse a string its "palindrome distance" doesn't change. So we don't have to reverse the middle part back to its original order since computing on the reversed order will give the correct result anyway.

```
f(a:b)|c:d<-reverse b= ...

```

So all in all our code is:

```
f(a:b)|c:d<-reverse b=f d+abs(a-c)*div(length d)2
f _=0

```

Ok but `length` and `div` are kind of costly. The number of steps left is really just the thing we are looking for so what if we used that to help us.

```
f(a:b)|c:d<-reverse b,(k,n)=(k+abs(a-c)*n,n+1)
f _=(0,1)
g=fst.f

```

Well that didn't help, but we are onto something here. Multiplication is just repeated addition, so what we really want is to add `abs(a-c)` once for each remaining iteration. So why don't we keep track of the numbers we want to add and just keep adding them on the way down.

```
u#(a:b)|c:d<-reverse b=sum u+(abs(c-a):u)#d
u#_=sum u
g=([]#)

```

So here we have this extra argument `u` which is just the list of all the absolute differences so far. And each iteration we add the sum of these to the result of the next iteration. This way each difference gets added as many times the number of steps from the center, in essence multiplying it by its distance from the center.

Of course since we are only ever asking `u` for its sum we don't actually need to separate the values we can just keep track of the running sum to save some bytes.

```
u#(a:b)|c:d<-reverse b=u+(abs(c-a)+u)#d
u#_=u
g=(0#)

```

And this gives us the final code.
> 9 votes

# Answer
# 05AB1E, 8 bytes

-1 byte thanks to Kevin Cruijssen for reminding me that input can be taken as lists of integers.

```
Âα2äθā*O

```

Try it online!

**Commented:**

```
           # implicit input: a list of codepoints
Â          # push codepoints and codepoints reversed
 α         # take the (element-wise) absolute difference
  2ä       # split into 2 pieces
           # the last one will be shorter for odd lengths
    θ      # take the last piece
     ā     # length-range: [1, ..., length] (doesn't pop the TOS)
      *    # multiply element-wise
       O   # take the sum

```
> 7 votes

# Answer
# , ~~50~~ 47 bytes

*Edit: -3 bytes thanks to Giuseppe by using `%*%` operator to calculate inner product of vectors, rather than summing the product of elements as separate operations*

```
abs((rev(x<-scan())-x)[(y=sum(x|1)/2):1])%*%1:y

```

Try it online!

Accepts list of numbers.

Un-golfed code:

```
x=scan()                # x is vector of numbers
y=sum(x|1)/2)           # y is half the length of x
sum(                    # return the sum of...
 abs(                   # the absolute values of...
  (x-rev(x))            # the differences between each element of x
                        # and the same elements reversed...
   [y:1]                # at positions y..1
                        # (so only the first half, backwards)...
    *1:y))              # multiplied by 1..y

```
> 5 votes

# Answer
# C (gcc), <sup>~~74~~ \\$\cdots\\$ ~~52~~</sup> 51 bytes

Saved ~~6~~ 7 bytes thanks to AZTECCO!!!
Saved ~~9~~ a whooping 15 bytes thanks to Dominic van Essen!!!

```
f(s,l)int*s;{l=l>1?l/2*abs(*s++-s[l-=2])+f(s,l):0;}

```

Try it online!

Port of my Python 3 answer.
> 4 votes

# Answer
# JavaScript (ES6),  ~~61~~  57 bytes

Expects a list of ASCII codes.

```
f=a=>1/a?0:(a.length>>1)*Math.abs(a.shift()-a.pop())+f(a)

```

Try it online!

### How?

This is a pretty straightforward recursive implementation that removes the first and the last entry from the list at each iteration, computes the absolute value of their difference and applies the weight \\$\lfloor L/2 \rfloor\\$, where \\$L\\$ is the length of the list before the items are removed.

The halting criterion `1 / a` is truthy if either:

* `a[]` is empty, in which case `1 / a == Infinity`. This happens when the length of the input list is even.
* Or `a[]` is a singleton integer, which happens if the length of the list is odd. We can safely stop the recursion without any other calculation because a single character is a palindrome and we already have the final result at this point.
> 3 votes

# Answer
# Python 2, ~~57~~ 54 bytes

A recursive function that takes input as a list of integers.

```
f=lambda l:l>[]and len(l)/2*abs(l[0]-l[-1])+f(l[1:-1])

```

Try it online!

The last part could also be `abs(l[0]-l.pop())+f(l[1:])` at the same length.

---

# Python 2, 57 bytes

A slightly longer approach without recursion.

```
lambda l:eval(len(l)/2*'+len(l)/2*abs(l.pop(0)-l.pop())')

```

Try it online!
> 3 votes

# Answer
# Charcoal, 22 bytes

```
ＩΣＥ∕θ²×⁻Ｌ∕θ²κ↔⁻℅ι℅§⮌θκ

```

Try it online! Link is to verbose version of code. Takes input as a string (halving a string is golfier than halving an array). Explanation:

```
    θ                   Input string
   ∕ ²                  First half
  Ｅ                     Map over characters
            κ           Current index
       ⁻                Subtracted from
        Ｌ∕θ²            Length of half of string
      ×                 Multiplied by
             ↔⁻         Absolute difference of
               ℅ ℅      Ordinals of
                ι       Current character and
                  §     Character at
                     κ  Current index in
                   ⮌    Reversed
                    θ   Input string
 Σ                      Take the sum
Ｉ                       Cast to string
                        Implicitly print

```

Alternative approach, also 22 bytes:

```
ＩΣＥ⮌∕⮌θ²×⊕κ↔⁻℅ι℅§⮌∕θ²κ

```

Try it online! Link is to verbose version of code. Explanation:

```
      θ                 Input string
     ⮌                  Reversed
    ∕  ²                "First" half
   ⮌                    Reversed i.e. last "half"
  Ｅ                     Map over characters
          κ             Current index
         ⊕              Incremented
        ×               Multiplied by
           ↔⁻           Absolute difference of
             ℅ ℅        Ordinals of
              ι         Current character and
                §       Character at
                     κ  Current index in
                 ⮌      Reversed
                  ∕θ²   First half of input string
 Σ                      Take the sum
Ｉ                       Cast to string
                        Implicitly print

```
> 3 votes

# Answer
# TECO, 53 Bytes

1. Q-register A has the initialisation code.

```
*:ga

$$
j0uaz-1ub0uu0uw$$*

```
2. Q-register M adds it all up. The result remains in Q-register W.

```
:gm$$

z/2<0ua0a-(qba)%a"L-qaua'qa%u%w$c-2%b>$$*

```
3. An Example to calculate the \\$D\_p\\$ of “Neveroddoreven”: kill the whole buffer, insert your word, initialise registers A,B,U, and W and jump to the beginning of the buffer; then iterate z/2 times, accumulating into register W; finally show the numeric content of register W.

```
hkiNeveroddoreven$mamm$$
*qw=$$
224
*

```
4. The complete program, and its length.

```
*ht$$
j0uaz-1ub0uu0uwz/2<0ua0a-(qba)%a"L-qaua'qa%u%w$c-2%b>*z=$$
53

```
5. The test cases.

```
"aa" -> 0
"bab" -> 0
"abca" -> 1
"cbade" -> 6
"hello" -> 21
"code-golf" -> 45
"neveroddoreven" -> 0
"Neveroddoreven" -> 224

```

This shows a TECO session of inserting each test word into the emptied edit buffer, then calling the macros of Q-registers A and M, and finally showing the \\$D\_p\\$ that was accumulated in the numeric Q-register W.

```
*hkiaa$mammqw=$$
0
*hkibab$mammqw=$$
0
*hkiabca$mammqw=$$
1
*hkicbade$mammqw=$$
6
*hkihello$mammqw=$$
21
*hkicode-golf$mammqw=$$
45
*hkineveroddoreven$mammqw=$$
0
*hkiNeveroddoreven$mammqw=$$
224

```
> 3 votes

# Answer
# C (gcc), ~~55~~ 52 bytes

```
f(a,z)char*a;{z=z/2?z/2*abs(*a++-a[z-=2])+f(a,z):0;}

```

Try it online!

* Saved a bit stealing from @Noodle9 and rearrangements

```
f(a,z)char*a;{z=  - function tacking a C-string pointer and its length
                    and returning trough eax register.

z/2?         - if not in the centre :
f(a+1,z-2)   >  recursively call with pointer moved and length decreased
+abs(*a-a[z-1])*(z/2)
              - add value of pairs
:0;}         >  else initialize r to 0

```
> 2 votes

# Answer
# APL (Dyalog Unicode), 21 bytes

```
{+/|⍵×⍳≢⍵}(⌈2÷⍨⍴)↓⊢-⌽

```

Try it online!
> 2 votes

# Answer
# Jelly, 7 bytes

```
ạṚŒHṪḋJ

```

A monadic Link accepting a list of integers which yields an integer.

**Try it online!**

### How?

```
ạṚŒHṪḋJ - Link: list of integers, A   e.g. (Abracadabra) [65,98,114,97,99,97,100,97,98,114,97]
 Ṛ      - reverse (A)                                    [97,114,98,97,100,97,99,97,114,98,65]
ạ       - absolute difference (vectorises)               [32,16,16,0,1,0,1,0,16,16,32]
  ŒH    - split in two (1st part longest, if any)        [[32,16,16,0,1,0],[1,0,16,16,32]]
    Ṫ   - tail                                           [1,0,16,16,32]
      J - range of length (of A)                         [1,2,3,4,5,6,7,8,9,10,11]
     ḋ  - dot-product                                    273 (= 1×1+0×2+16×3+16×4+32×5+0×6+...0×11)

```
> 2 votes

# Answer
# Husk, ~~14 12~~ 11 bytes

*-2 thanks to Wheat Wizard pointing out you can take input as a list of codepoints*

*and -1 thanks to HP.Wiz showing that ≠ does absolute difference not just inequality*

```
ΣFoz*ŀ½Sz≠↔

```

Try it online!

### Explanation

```
       Sz≠      Zip absolute difference the list from
          ↔    The reverse of the list
      ½         Split the list into two halves (with the longer being the first)
 F              Reduce by
  o  ŀ          Converting the first half to range(1, length)
   z*           And zip multiplying with the second half
Σ               Finally sum the absolute values

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), 53 bytes

```
f@_:0=0
f[a_,b___,c_]:=Abs[a-c]⌈Length@a?b/2⌉+f@b

```

Try it online!

Takes a list of integers.

`Length@a?b` saves one byte over `Tr[1^{a,b}]`/`Length[a.b]` thanks to `PatternTest`'s high precedence.
> 1 votes

# Answer
# Python 3, 59 bytes

```
f=lambda l:len(l)>1and len(l)//2*abs(l.pop(0)-l.pop())+f(l)

```

Try it online!
> 1 votes

# Answer
# , 24 bytes

```
+/@(#\.@]*|@-)&(,~inv)|.

```

Try it online!

Takes input as list of integers.

Another one of those interesting problems that is unexpectedly difficult to express tersely in J. I tried a few approaches and this is my best attempt.

## how

* `(...)|.` The whole phrase is a hook, which means the original input and that input reversed `|.` will be passed as the left and right arguments, respectively, to the phrase in parentheses.
* `(...)&(,~inv)` The compose conjunction `&` transforms both arguments with the specified verb, in this case `,~inv`.
    + `,~inv` is the inverse of the verb that doubles a list by self-appending `,~`. The inverse of that operation is to take the first half of the list, and it happens to "round down" for odd lists, which is what we want here.
* `#\.@]*|@-` Multiply `#\.@]` element-wise by `|@-`
    + `|@-` subtract the two list arguments element-wise and take the absolute value `|`. These are the "distances".
    + `#\.@]` produces, eg, `4 3 2 1` if the lists have length 4. It does this by taking the suffix lengths `#\.` of the right argument `]`. We could have used the left argument just as well here.
* `+/@` Sum the result

---

For comparison, the APL solution converted into J is 25 bytes:

```
>.@-:@#(1#.]*&|#\)@}.]-|.

```

Try it online!
> 1 votes

---
Tags: code-golf, string, palindrome
---


title: Area of diagonal-folded regular polygon

text:
# Question
Title: Area of diagonal-folded regular polygon
I have a piece of paper whose shape is a regular `n`-gon with side length `1`. Then I fold it through some of its diagonals. What is the area of the shape formed by the (former) edges of the regular polygon?

## Illustration

Suppose `n = 8`, i.e. an octagon-shaped paper. Let's name the vertices from A to H (left picture). Then I fold the paper along the two diagonals BE and FH (right picture). Mathematically, folding BE means to reflect the vertices C and D with respect to the line BE to obtain C' and D'. Your task is to calculate the area of the shaded octagon on the right picture.

## Input

The number of sides `n` and a list representation of the folds `l`. Each element of `l` represents either a fold or an intact side of the polygon. If it is a fold, its value is the number of sides moved by the fold (e.g. 3 for the `BE` fold above, 2 for `FH`). Otherwise, the value is 1 (e.g. for the sides `AB`, `EF`, `AH`).

For the example above, the input will be `8, [1, 3, 1, 2, 1]` if we count from the vertex A, counter-clockwise. If we count clockwise from E instead, the input will be `8, [3, 1, 1, 2, 1]`; the expected answer is the same.

Note that `sum(l) == n`. Also, `l == [1] * n` (1 repeated n times) case is just the regular polygon untouched, which is a valid input.

**The resulting polygon is guaranteed to be simple** (it does not intersect or touch itself). For `n=3` or `n=4`, this means that the only valid input is the polygon folded zero times. For `n=6`, `l=[1, 2, 2, 1]` or `l=[1, 2, 1, 2]` is invalid because the two folds will cause two folded vertices to meet at the center of the hexagon.

## Output

The area of the `n`-sided polygon created by the given folds. The result must be within `1e-6` absolute/relative error from the expected result.

## Scoring & winning criterion

Standard rules apply. Shortest code in bytes wins.

## Test cases

```
n l => answer
---------------
4 [1, 1, 1, 1]    => 1.000000
5 [1, 1, 1, 1, 1] => 1.720477
5 [2, 1, 1, 1]    => 0.769421
6 [1, 2, 1, 1, 1] => 1.732051
7 [1, 2, 1, 2, 1] => 2.070249
8 [1, 3, 1, 2, 1] => 1.707107

```

The picture below shows the first five test cases.

A reference implementation in Python.

# Answer
# Wolfram Language (Mathematica), ~~37~~ 36 bytes

```
Tr[Csc[i=Pi/#2]^2Sin[2i#]-Cot@i#]/4&

```

Try it online!

Takes input in the order `l, n`.

Uses the same approach as in the reference and many other implementations.

Mathematica's trigonometric and arithmetic functions will automatically vectorize, and `Tr` returns the sum of the elements of a one-dimensional list.

\\$\csc\\$ and \\$\cot\\$ are relatively uncommon; \\$\csc x=\frac1{\sin x}\\$, and \\$\cot x=\frac1{\tan x}\\$.
> 8 votes

# Answer
# Ruby, ~~79 .. 66~~ 65 bytes

```
->n,f{(f*2+[w=-1]*n).sum{|z|(w**z*=b=2r/n).imag/(1-w**b).real}/4}

```

Try it online!

Loosely based on the reference implementation:

* The area of the original polygon (ABCDEFGH) is `a`
* If we cut instead of folding, we get a new convex polygon (ABEFH), we call the area of this polygon `b`
* The difference between `a` and `b` is the area of the polygons we cut away (BCDE and FGH), let's call it `c`
* The area of the folded polygon is `b-c` or `a-2c` (we have to remove BCDE and FGH twice from the original polygon). This equals to `2b-a`
* Both `a` and `b` can be represented as the sum of triangles (formed by 2 radiuses of the enclosing circle and one side of the polygon). Yes, we have a formula for calculating `a`, but if we define an intermediate function `g` it's easier to use it for both `a` and `b`
* The area of a triangle is r\*r\*sin(2lπ/n) where l is the number of vertices in a fold and n is the total number of vertices, and r is the radius (which is 1/sin(π/n))
* `a` is the sum of n triangles with l=1
* since `g(-x)=-g(x)`, we don't need to split the sum in 2 parts, we can sum over a larger array (that is twice f plus \[-1\] repeated n times), the intermediate function can become a block.
* sin(x)^2 becomes (1-cos(2x))/2
* sin(2π/x) and cos(2π/x) are imaginary and real part of the xth root of -1.
> 8 votes

# Answer
# JavaScript (ES7),  ~~87 83 82 79~~  72 bytes

*Saved 2 bytes thanks to @Shaggy*
*Saved 7 bytes thanks to @GB's insight*

Takes input as `(n)(list)`. Derived from the reference implementation.

```
with(Math)f=n=>a=>a.map(v=>n+=sin(2*v*T)/sin(T)**2,n/=-tan(T=PI/n))&&n/4

```

Try it online!

Given the number of sides \\$n\\$ and the folding values \\$F\_1\\$ to \\$F\_m\\$, this computes:

$$A=\frac{1}{4}\left(-\frac{n}{\tan(\theta)}+\sum\_{i=1}^{m}\frac{\sin(2\theta F\_i)}{\sin(\theta)^2}\right)$$

with \\$\theta=\dfrac{\pi}{n}\\$
> 6 votes

# Answer
# Java 8, ~~123~~ ~~114~~ ~~112~~ 103 bytes

```
a->n->{double t=Math.PI/n,T=Math.sin(t);n/=-Math.tan(t);for(int v:a)n+=Math.sin(2*v*t)/T/T;return n/4;}

```

Port of the Python reference implementation.
-11 bytes by porting *@Arnauld*'s JavaScript answer.
-9 bytes thanks to *@G.B*'s insight.

Try it online.
> 2 votes

# Answer
# APL (Dyalog Unicode), <sup>~~41~~</sup> 35 bytes

```
{4÷⍨(+/(1○2×⍵×t)÷2*⍨1○t)-⍺÷3○t←○÷⍺}

```

Try it online!

Uses Arnauld's expression for calculating the area.

-6 bytes from ovs. (removing inner dfn)

## Explanation

```
{4÷⍨(+/(1○2×⍵×t)÷2*⍨1○t)-⍺÷3○t←○÷⍺} ⍺ → n, ⍵ → l
                             t←○÷⍺  assign t to Π/n (○÷n = (○1)÷n)
    (                  )            apply the following to each element of l:
       (1○2×⍵×t)                       sin(2×element×t)
                ÷                      divided by
                 2*⍨1○t                sin(t)²
    (+/                             sum the results
                        -           minus:
                         ⍺          n
                          ÷         divided by
                           3○t      tan(t)
 4÷⍨                                divide that whole expression by 4

```
> 2 votes

# Answer
# 05AB1E, ~~36~~ ~~31~~ ~~30~~ ~~25~~ 23 bytes

```
·žqI/©*®šÅ½ćn/OI®Å¼/-4/

```

Folds-list as first input, sides-integer as second input.

Port of my Java answer.
-5 bytes by porting *@Arnauld*'s JavaScript answer.
-1 byte thanks to *@Grimy*.
-5 bytes thanks to *@G.B*'s insight.

Try it online or verify all test cases.

**Explanation:**

```
·               # Double each value in the (implicit) input-list
 žq             # Push PI
   I/           # Divide it by the input-integer
     ©          # Store this PI/input in variable `®` (without popping)
      *         # Multiply this to each doubled value in the list
       ®š       # Prepend `®` (PI/input) to this list
         Å½     # Take the sine of each value in the list
           ć    # Pop and push remainder-list and first item separated to the stack
            n   # Square this first item: sin(PI/input)²
             /  # Divide each value in the list by this
              O # And then sum all values together
  ®Å¼           # Get the tangent of `®`: tan(PI/input)
 I   /          # And divide the input-integer by this
      -         # Subtract it from the sum
       4/       # And divide it by 4
                # (after which the result is output implicitly)

```
> 1 votes

# Answer
# Python 3, ~~81~~ 79 bytes

```
lambda n,f,a=-1:sum([(a**(2/n*r)).imag/(1-a**(2/n)).real for r in f*2+[a]*n])/4

```

Try it online!

A Python port of my Ruby solution.
> 1 votes

# Answer
# , ~~60~~ 57 bytes

-2 and -1 thanks to Nick Kennedy and CriminallyVulgar!

```
function(n,l,t=pi/n)(sum(sin(2*t*l)/sin(t)^2)-n/tan(t))/4

```

Try it online!
> 1 votes

# Answer
# Icon, 108 bytes

```
procedure g(s,f)
r:=.5/sin(t:=&pi/s)
p:=s*(c:=.25/tan(t))
p-:=(c*(i:=!f)-r*r*sin(2*i*t)/2)*2&\z
return p
end

```

Try it online!

An Icon port of the Python reference implementation.
> 0 votes

# Answer
# Jelly, 23 bytes

```
×ḤÆS÷ÆS²¥_ÆTİ×ɗS
ØP÷ç÷4

```

Try it online!

A full program that takes the number of sides as its first argument and the list of folds as its right. Returns/prints the area of the folded polygon.

Loosely based on the formula in @Arnauld’s answer.
> 0 votes

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


title: Find the Emirps!

text:
# Question
Title: Find the Emirps!
> An **emirp** is a ***non-palindromic*** prime which, when reversed, is also prime.

The list of base 10 emirps can be found on **OEIS**. The first six are:

```
13, 17, 31, 37, 71, 73

```

However, due to the reversal rule, emirps are different in each base. For example, the first six binary emirps are:

```
Bin  | 1011, 1101, 10111, 11101, 101001, 100101
Dec  | (11 , 13  , 23   , 29   , 37    , 41   )

```

...and in hexadecimal, they are:

```
Hex |  17, 1F, 35, 3B, 3D, 53
Dec | (23, 31, 53, 59, 61, 83)

```

Fun Fact: there are no emirps in unary as every number is a palindrome.

---

# The Challenge

Your task is to create a function (or full program) which takes two parameters, \\$ n \\$ and \\$ b \\$, and generates a list of the first \\$ n \\$ emirps in base \\$ b \\$.

**Rules/Details:**

* \\$ n \\$ and \\$ b \\$ are both positive integers larger than \\$ 0 \\$.
* You can assume \\$ 2 ≤ b ≤ 16 \\$: that is to say, the base will be between binary and hexidecimal.
* You should be able to compute for values of \\$ n \\$ up to \\$ ~100 \\$.
* The generated list can be in base \\$ b \\$, or your language's standard integer base, as long as you specify this in your answer.
* Builtin emirp checks are not permitted (builtin primality tests are fine)
* You cannot hard-code the emirps, or read from any external files.
* Standard loopholes are banned, as always.
* This is , so the shortest answer (in bytes) wins.

---

# Test Cases

For each test case, I've included the list in base `b` and its base 10 equivalents.

```
B = 2, N = 10

BIN: [1011, 1101, 10111, 11101, 100101, 101001, 101011, 101111, 110101, 111101]
DEC: [11, 13, 23, 29, 37, 41, 43, 47, 53, 61]

B = 3, N = 5

BASE3: [12, 21, 102, 201, 1011]
DEC:   [5, 7, 11, 19, 31]

B = 12, N = 7

BASE12: [15, 51, 57, 5B, 75, B5, 107]
DEC: [17, 61, 67, 71, 89, 137, 151]

B = 16, N = 4

HEX: [17, 1F, 35, 3B]
DEC: [23, 31, 53, 59]

```

You can test your program further against my (ungolfed) Python example on **repl.it**

# Answer
> 6 votes
# Jelly, 16 bytes

```
bµU,ḅ⁹QÆPḄ=3
⁸ç#

```

**TryItOnline!**

### How?

```
bµU,ḅ⁹QÆPḄ=3 - Link 1, in-sequence test: n, b
b            - convert n to base b - a list
 µ           - monadic chain separation
  U          - reverse the list
   ,         - pair with the list
     ⁹       - link's right argument, b
    ḅ        - convert each of the two lists from base b
      Q      - get unique values (if palindromic a list of only one item)
       ÆP    - test if prime(s) - 1 if prime, 0 if not
         Ḅ   - convert to binary
          =3 - equal to 3? (i.e. [reverse is prime, forward is prime]=[1,1])

⁸ç# - Main link: b, N
  # - count up from b *see note, and find the first N matches (n=b, n=b+1, ...) for:
 ç  - last link (1) as a dyad with left argument n and right argument
⁸   - left argument, b

```

* Note `b` in base `b` is `[1,0]`, which when reversed is `[0,1]` which is `1`, which is not prime; anything less than `b` is one digit in base `b` and hence palindromic.

# Answer
> 9 votes
# 05AB1E, 17 bytes

Uses CP-1252 encoding.

Input order is `n, b`
Output is in base-10.

```
µN²BÂD²öpŠÊNpPD–½

```

Try it online!

**Explanation**

```
                    # implicit input a,b
µ                   # loop until counter is a
 N²B                # convert current iteration number to base b
    ÂD              # create 2 reversed copies
      ²ö            # convert one reversed copy to base 10
        p           # check for primality
         ŠÊ         # compare the normal and reversed number in base b for inequality
           Np       # check current iteration number for primality
             P      # product of all
              D     # duplicate
               –    # if 1, print current iteration number
                ½   # if 1, increase counter

```

# Answer
> 4 votes
## Mathematica, 70 bytes

```
Cases[Prime@Range@437,p_/;(r=p~IntegerReverse~#2)!=p&&PrimeQ@r]~Take~#&

```

Works for `0 <= n <= 100` and `2 <= b <= 16`. From the list `Prime@Range@437` of the first `437` primes, find the `Cases` `p`where the `IntegerReverse` `r` of `p` in base `#2` is not equal to `p` and is also prime, then take the first `#` such `p`.

Here's a 95 byte solution that works for arbitrary `n>=0` and `b>=2`:

```
(For[i=1;a={},Length@a<#,If[(r=IntegerReverse[p=Prime@i,#2])!=p&&PrimeQ@r,a~AppendTo~p],i++];a)&

```

# Answer
> 3 votes
# Perl, 262 bytes

```
($b,$n)=@ARGV;$,=',';sub c{my$z;for($_=pop;$_;$z=(0..9,a..z)[$_%$b].$z,$_=($_-$_%$b)/$b){};$z}sub d{my$z;for(;c(++$z)ne@_[0];){}$z}for($p=2;@a<$n;$p++){$r=qr/^1?$|^(11+?)\1+$/;(c($p)eq reverse c$p)||((1x$p)=~$r)||(1x d($x=reverse c($p)))=~$r?1:push@a,c($p);}say@a

```

Readable:

```
($b,$n)=@ARGV;
$,=',';
sub c{
    my$z;
    for($_=pop;$_;$z=(0..9,a..z)[$_%$b].$z,$_=($_-$_%$b)/$b){};
    $z
}
sub d{
    my$z;
    for(;c(++$z)ne@_[0];){}
    $z
}
for($p=2;@a<$n;$p++){
    $r=qr/^1?$|^(11+?)\1+$/;
    (c($p)eq reverse c$p)||((1x$p)=~$r)||(1x d($x=reverse c($p)))=~$r?1:push@a,c($p)
}
say@a

```

`c` converts a given number into base `$b`, and `d` converts a given number from base `$b` back into decimal by finding the first number which returns said base-`$b` number when passed to `c`. The for loop then checks if it's a palindrome and if both of the numbers are prime using the composite regex.

# Answer
> 3 votes
# Mathematica 112 bytes

```
Cases[Table[Prime@n~IntegerDigits~#2,{n,500}],x_/;x!=(z=Reverse@x)&&PrimeQ[z~(f=FromDigits)~#2]:>x~f~#2]~Take~#&

```

---

**Example**

Find the first 10 Emips in hex; return them in decimal.

```
Cases[Table[Prime@n~IntegerDigits~#2, {n, 500}],
x_ /; x != (z = Reverse@x) && PrimeQ[z~(f = FromDigits)~#2] :> x~f~#2]~Take~# &[10, 16]

{23, 31, 53, 59, 61, 83, 89, 113, 149, 179}

```

---

**Ungolfed**

```
Take[Cases[                                             (* take #1 cases; #1 is the first input argument *)
   Table[IntegerDigits[Prime[n], #2], {n, 500}],        (* from a list of the first 500 primes, each displayed as a list of digits in base #2 [second argument] *)
   x_ /;                                                (* x, a list of digits, such that *)
   x != (z = Reverse[x]) && PrimeQ[FromDigits[z, #2]]   (* the reverse of the digits is not the same as the list of digits; and the reverse list, when composed, also constitutes a prime *)
   :> FromDigits[x, #2]],                               (* and return the prime *)
   #1] &                                                (* [this is where #1 goes, stating how many cases to Take] *)

```

# Answer
> 2 votes
# Perl 6, 91 bytes

```
->\n,\b{(grep {.is-prime&&{$_ ne.flip &&.parse-base(b).is-prime}(.base(b).flip)},1..*)[^n]}

```

Returns the list of emirps in base 10.

# Answer
> 2 votes
# C, ~~293~~ ~~286~~ 261 bytes

Improved by @ceilingcat, 261 bytes:

```
v,t,i,j,c,g,s[9],r[9],b;main(n,a)int**a;{for(b=n=atoi(a[1]);g^atoi(a[2]);t|v|!wcscmp(s,r)||printf("%u ",n,++g)){i=j=0;for(c=++n;s[i]=c;c/=b)s[i++]=c%b+1;for(;r[j]=i;)r[j++]=s[--i];p(n);for(t=v;r[i];)c+=~-r[i]*pow(b,i++);p(c);}}p(n){for(j=1,v=0;++j<n;n%j||v++);}

```

Try it online!

(This person is like constantly following me around PPCG and improving my stuff in the comments, and as soon as I reply to thank him he just deletes the comment and vanishes lol. Welp, thanks again!)

---

Improved by @movatica, 286 bytes:

```
u,v,t,i,j,c,n,g;main(int x,char**a){char s[9],r[9],b=n=atoi(a[1]);x=atoi(a[2]);for(;g^x;){i=j=0;for(c=++n;c;c/=b)s[i++]=c%b+1;s[i]=c=0;for(;i;r[j++]=s[--i]);r[j]=0;p(n);t=v;for(;r[i];)c+=(r[i]-1)*pow(b,i++);p(c);t|v|!strcmp(s,r)?:printf("%u ",n,++g);}}p(n){for(u=1,v=0;++u<n;n%u?:v++);}

```

Try it online!

---

My original answer, 293 bytes:

```
u,v,t,i,j,c,n,g;main(int x,char**a){char s[9],r[9],b=n=atoi(a[1]);x=atoi(a[2]);for(++n;g^x;++n){i=j=0;for(c=n;c;c/=b)s[i++]=c%b+1;s[i]=c=0;for(;i;r[j++]=s[--i]);r[j]=0;p(n);t=v;for(--i;r[++i];)c+=(r[i]-1)*pow(b,i);p(c);t|v|!strcmp(s,r)?:printf("%u ",n,++g);}}p(n){for(u=1,v=0;++u<n;n%u?:v++);}

```

Compile with `gcc emirp.c -o emirp -lm` and run with `./emirp <b> <n>`. Prints space-separated emirps in base-10.

# Answer
> 2 votes
# Python 3, ~~232~~ ~~214~~ ~~191~~ 188 bytes

```
p=lambda n:all(n%i for i in range(2,n))
def f(b,n):
 s=lambda n:(''if n<b else s(n//b))+f'{n%b:X}';l=[];i=3
 while n:i+=1;c=s(i);d=c[::-1];a=(c!=d)*p(i)*p(int(d,b));l+=[c]*a;n-=a
 return l

```

Try it online!

# Answer
> 1 votes
## JavaScript (ES6), ~~149~~ ~~148~~ ~~141~~ 140 bytes

Returns a space-separated list of emirps in base b. (Could be 2 bytes shorter by returning a decimal list instead.)

```
f=(b,n,i=2)=>n?((p=(n,k=n)=>--k<2?k:n%k&&p(n,k))(i)&p(k=parseInt([...j=i.toString(b)].reverse().join``,b))&&k-i&&n--?j+' ':'')+f(b,n,i+1):''

```

### Test cases

```
f=(b,n,i=2)=>n?((p=(n,k=n)=>--k<2?k:n%k&&p(n,k))(i)&p(k=parseInt([...j=i.toString(b)].reverse().join``,b))&&k-i&&n--?j+' ':'')+f(b,n,i+1):''

console.log(f(2,10));
console.log(f(3,5));
console.log(f(12,7));
console.log(f(16,4));
```

# Answer
> 1 votes
# Python 2, 133 bytes

```
p=lambda n:all(n%i for i in range(2,n))
b,n=input()
i=b
while n:
 j=i=i+1;r=0
 while j:r=r*b+j%b;j/=b
 if(i-r)*p(i)*p(r):print i;n-=1

```

Try it online!

Outputs each number on a new line, in base 10

# Answer
> 1 votes
# Husk, ~~20~~ 17 bytes

```
↑fo§&ȯṗB⁰↔S≠↔B⁰İp

```

Try it online!

The type inference is odd here.

-3 bytes from Jo King.

# Answer
> 0 votes
# APL(NARS), 87 chars, 174 bytes

```
r←a f w;i
i←1⋄r←⍬
→2×⍳∼{∼0π⍵:0⋄k≡v←⌽k←{(a⍴⍨⌊1+a⍟⍵)⊤⍵}⍵:0⋄0πa⊥v:1⋄0}i+←1⋄r←r,i⋄→2×⍳w>≢r

```

The result will be in base 10. Test and results:

```
  3 f 1
5
  2 f 10
11 13 23 29 37 41 43 47 53 61
  3 f 5
5 7 11 19 31
  12 f 7
17 61 67 71 89 137 151
  16 f 4
23 31 53 59

```

`{(⍺⍴⍨⌊1+⍺⍟⍵)⊤⍵}` would do conversion of  in base , array integer result; `0π⍵` would return true\[1\] if  is prime else it would return 0.

# Answer
> 0 votes
# Japt, 18 bytes

With decimal output.

```
È2¶[XXìV'w]â xj}jU

```

Try it

---
Tags: code-golf, number-theory, primes, base-conversion, integer
---


title: Read a crossword

text:
# Question
Title: Read a crossword
Inspired by this question about packing into this format.

Occasionally I see a completed crossword and being as I am, I can't be bothered to find out what the solutions to the clues actually were.

## Input:

* A 2D string (any format, newline separated, 2d list etc.)
* Blank squares will be represented with a  (space character)
* Every other square will be in the lower case alphabet.
* You may assume that the input will be padded with spaces to form a rectangle

## Output:

* Each word found
    + You must search for words along and down
    + Words will be at least two letters long
    + If there are duplicate words, you have to output them for each time they appear
* You don't have to do any validation
* Words may be outputted in any order
* No strict formatting rules

## Test cases:

```
word
e e
step
t d

word, step, west, reed
---
pies
 not
  no
wasp

pies, not, no, wasp, in, eons, stop
---
igloo
    n
word

igloo, word, on

```

# Answer
> 10 votes
# Pyth - ~~11~~ ~~10~~ ~~8~~ 7 bytes

*saved one bytes thanks to @issacg.*

```
t#cjsCB

```

Try it online here.

```
t#               Filter by if len > 1
 c               Chop by whitespace by default
  j              Join by newlines
   sCB           Input, implicit and its transpose in one list

```

# Answer
> 2 votes
## CJam, 14 bytes

```
{_z+S*S%{,(},}

```

An unnamed block that expects a list of (padded) strings on top of the stack and leaves a list of words instead.

Test it here.

### Explanation

```
_z    e# Duplicate and transpose the grid.
+     e# Append the transpose to the original grid.
S*    e# Join all lines by spaces to ensure that we don't get words
      e# spanning multiple lines.
S%    e# Split around spaces, discarding empty segments.
{,(}, e# Filter: keep only those strings with length 2 or greater.

```

# Answer
> 2 votes
# 05AB1E, 9 bytes

```
ø«€#J˜ʒ¦Ā

```

Input as a character matrix.

Try it online or verify all test cases.

**Explanation:**

```
ø          # Zip/transpose the (implicit) input-matrix; swapping rows/columns
 «         # Merge this list of lists to the (implicit) input list of lists
  €        # For each inner list:
   #       #  Split them on spaces
    J      # Join each innermost list together to a single string
     ˜     # Flatten the entire list
      ʒ    # Filter the strings by:
       ¦   #  Remove the first character of the string (no-op if it's already empty)
        Ā  #  And check that it's non-empty
           # (after which the result is output implicitly)

```

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

```
s=>(s+` `+[...(t=s.split`
`)[0]].map((_,i)=>t.map(t=>t[i]).join``)).match(/\w\w+/g)

```

# Answer
> 1 votes
# T-SQL, 322 bytes

I can't prove that this works, but feel free to test it in Microsoft SQL server Management Studio sql server 2017+

```
DECLARE @ varchar(max)=
('MICROWAVE
U       S
M OCEAN C
M  OWL  A
I SWELL P
E       E
SCHEDULES');

WITH C as(SELECT 1x,@ a UNION ALL SELECT
iif(ascii(a)=13,0,x+1),stuff(a,1,1,'')FROM C
WHERE''<a)SELECT w FROM(SELECT(SELECT left(a,1)FROM
c WHERE x=t.x for xml path(''),type).value('.','char(99)')a
FROM c t GROUP BY x UNION ALL SELECT @)r
CROSS APPLY(SELECT*FROM string_split(translate(a,'
','  '),' '))g(w)WHERE len(w)>1

```

This script will return

```
MUMMIES
COW
EWE
ALL
ESCAPES
MICROWAVE
OCEAN
OWL
SWELL
SCHEDULES

```

# Answer
> 1 votes
# , 30 bytes

```
[:(#~1<#&>)@,' '<;._1"1@,.],|:

```

Try it online!

# Answer
> 0 votes
## Pyke, 9 bytes

```
,+Fdc#t(s

```

Try it here!

Or 7 bytes prettified

```
,+Fdc#t

```

Try it here!

# Answer
> 0 votes
# Pyth, 18 bytes

```
Lm:d"\S\S+"1byQyCQ

```

Try it online!

Sample input:

```
["pies"," not","  no","wasp"," t  "]

```

Sample output:

```
[['pies'], ['not'], ['no'], ['wasp'], []]
[[], ['in', 'at'], ['eons'], ['stop']]

```

How it works:

```
Lm:d"\S\S+"1byQyCQ                                 The "1" here is mode
                    assign('Q',eval_input())       "1" which means show
                    @memoized                      all matches
L                   def y(b):                               v
 m:d"\S\S+"1b           return map(lambda d:regex(d,"\S\S+",1),b)
             yQ     imp_print(y(Q))
               yCQ  imp_print(y(transpose(Q)))

```

# Answer
> 0 votes
## Haskell, 58 bytes

```
import Data.List
f x=[w|w@(_:_:_)<-words=<<x++transpose x]

```

Usage example: `f ["pies"," not"," no","wasp"]` -\> `["pies", "not", "no", "wasp", "in", "eons", "stop"]`.

How it works: split each of the lines of the input and the transposition of it at spaces it into a single list words. Keep those that match `(_:_:_)`, i.e. have at least two letters.

# Answer
> 0 votes
# C++14, ~~209~~~~207~~201 bytes

Ridiculously high amount of bytes... but oh well. Transpose matrix, split string. Easy. Too bad no native function for transposing

```
[](vector<string>; m){auto t=m;int C=size(m[0]),j=0;for(;++j<C*C;)t[j%C][j/C]=m[j/C][j%C];for(j=0;++j<C+C;){stringstream Z(j<C?m[j]:t[j-C]);string s;while(getline(Z,s,' '))cout<<(size(s)>1?s+' ':"");}}

```

Ungolfed:

```
using S=vector<string>;
[](S m){
  S t=m;
  int C=size(m[0]),j=0;
  for(;j<C*C;++j)t[j%C][j/C]=m[j/C][j%C]; // Transpose
  for(j=0;j<C+C;++j){ // since rectangle matrix, we can iterate like so
    stringstream Z(j<C?m[j]:t[j-C]); // Get string from m or t
    string s;
    while(getline(Z,s,' '))
      cout<<(size(s)>1?s+' ':"");
  }
}

```

How to use it (note you must enforce padding as the question states):

```
using S = vector<string>;[](S m) { ... }({"pies", " not", "  no", "wasp"});

```

# Answer
> 0 votes
# Japt, 8 bytes

Takes input as an array of lines.

```
cUy)c¸fÅ

```

Try it (includes all test cases)

If we could include a leading and/or trailing newline in the input then this could be 7 bytes, taking input as a multi-line string.

```
pÕ·c¸fÅ

```

Try it

```
cUy)c¸fÅ     :Implicit input of array U
c            :Concatenate
 Uy          :  U transposed
   )         :End concat
    c        :Flat map
     ¸       :  Split on spaces
      f      :Filter elements that return true after
       Å     :  Slicing off the first character, resulting in the (falsey) empty string when length is <2

```

```
pÕ·c¸fÅ       :Implicit input of multi-line string
p             :Append
 Õ            :  The transposition
  ·           :Split on newlines
   c¸fÅ       :As above

```

---
Tags: code-golf, string, crossword
---


title: Pad a matrix with its sums

text:
# Question
Title: Pad a matrix with its sums
## Challenge:

Given a square input matrix \\$A\\$, pad the matrix with one row and one column on all four sides.

* The value of each element in the top and bottom row should be the sum of the elements in each corresponding column.
* The value of each element in the left and right column should be the sum of the elements in each corresponding row.
* The value of the elements in the top left, and bottom right corner should be the sum of the elements on the diagonal
* The value of the elements in the top right, and bottom left corner should be the sum of the elements in the anti-diagonal.

### Example:

```
A =
1   5   3
3   2   4
2   5   5

Output:
 8    6   12   12    7
 9    1    5    3    9
 9    3    2    4    9
12    2    5    5   12
 7    6   12   12    8

```

**Explanation:**

The top left and bottom right elements are the sum of the diagonal \\$1+2+5=8\\$. The top right and bottom left elements are the sum of the anti-diagonal \\$2+2+3=7\\$.

The top and bottom row (except the corners) are the sum of each of the columns in \\$A\\$: \\$1+3+2=6\\$, \\$5+2+5=12\\$ and \\$3+4+5=12\\$. Similarly, the left and right column (except the corners) are the sum of each of the rows of \\$A\\$: \\$1+5+3=9\\$, \\$3+2+4=9\\$ and \\$2+5+5=12\\$.

### Input:

* A non-empty square matrix, with non-negative integers.
* Optional format

### Output:

* The matrix padded as explained above
* Optional format, but it must be the same as the input format

## Test cases:

Use the submissions in this challenge if you want to convert the input format to a more suitable one (for instance `[[1, 5],[0, 2]]`).

```
0
----------------
0 0 0
0 0 0
0 0 0

```

```
1 5
0 2
----------------
3 1 7 5
6 1 5 6
2 0 2 2
5 1 7 3

```

```
17   24    1    8   15
23    5    7   14   16
 4    6   13   20   22
10   12   19   21    3
11   18   25    2    9
----------------
65   65   65   65   65   65   65
65   17   24    1    8   15   65
65   23    5    7   14   16   65
65    4    6   13   20   22   65
65   10   12   19   21    3   65
65   11   18   25    2    9   65
65   65   65   65   65   65   65

```

```
15    1    2   12
 4   10    9    7
 8    6    5   11
 3   13   14    0
----------------
30   30   30   30   30   30
30   15    1    2   12   30
30    4   10    9    7   30
30    8    6    5   11   30
30    3   13   14    0   30
30   30   30   30   30   30

```

This is , so the shortest solution **in each language** wins. Explanations are highly encouraged.

# Answer
> 5 votes
# Jelly, 27 bytes

```
,UŒDḢ$S$€,Ṛ$j€SW€jSẋ¥€2$j"$

```

Try it online!

# Answer
> 5 votes
# Octave, 64 bytes

Thanks to Tom Carpenter for both saving 4 bytes, *and* correcting an error I had in the original code!

```
@(a)[b=(t=@trace)(a),c=sum(a),d=t(flip(a));z=sum(a,2),a,z;d,c,b]

```

Try it online!

**Explanation:**

```
@(a)                 % Anonymous function that takes the matrix 'a' as input
 [ ... ]             % Concatenate everything inside to a single matrix
  b=(t=@trace)(a),   % Clever trick by Tom Carpenter. Save a function handle
                     % for 't=trace', and call it with 'a' as input
                     % Save the result in the variable 'b'
  c=sum(a)           % Sum of all columns of 'a'
  d=t(flip(a));      % Save the trace of 'a' flipped as a variable 'd', while
                     % concatenating [b,c,d] horizontally at the same time, creating the
                     % first row of the output
  z=sum(a,2)         % The sum of each row of the input, and store it in a variable 'z'
  ,a,z;              % Concatenate it with 'a' and 'z' again, to create the middle part of the output
 d,c,b]              % Add [d,c,b] to complete the bottom row

```

---

Note, I wrote this long after I posted the challenge.

# Answer
> 4 votes
# MATL, ~~27~~ 26 bytes

```
,!tXswyv]GXds5L(PGPXds5L(P

```

Try it online! Or verify all test cases.

### Explanation

```
,        % Do the following twice
  !      %   Tranpose. Takes input implititly in the first iteration
  t      %   Duplicate
  Xs     %   Row vector with the sum of each column
  wy     %   Push a copy to the bottom of the stack
  v      %   Concatenate stack vertically. This attaches the sum of
         %   each row (first iteration) and column (second), leaving
         %   the matrix with the correct orientation (transposed twice)
]        % End
G        % Push input again
Xds      % Column vector with the diagonal of the matrix. Sum of vector
5L(      % Write that into first and last entries of the result matrix
         % matrix; that is, its upper-left and lower-right corners
P        % Flip result matrix vertically
GP       % Push input matrix vertically flipped
Xds      % Diagonal, sum. Since the input has been vertically flipped,
         % this gives the sum of the anti-diagonal of the input.
5L(      % Write that into the upper-left and lower-right corners of
         % the verticallly flipped version of the result matrix
P        % Flip vertically again, to restore initial orientation
         % Implicitly display

```

# Answer
> 4 votes
# Jelly, 26 bytes

```
ŒDµḊṖÑµ€1¦ŒḌU
S;;S
Ç€Zµ⁺ÑÑ

```

Try it online!

Looks surprisingly different from Erik's solution.

I finally managed to understand how `¦` works (by debugging through Jelly's code, lol). Too bad it requires a  to work with `Ç` in my case.

### Explanation

The code uses three links. The first helper link pads a vector with its sum on both ends, the second helper link fixes two corners of the matrix and the main link calls these appropriately.

```
Ç€Zµ⁺ÑÑ    Main link. Argument: M (matrix)
Ç            Call the first helper link (pad row with sums)...
 €           ...on each row of the matrix.
  Z          Transpose, so that the second invocation uses the columns.
   µ         Begin a new monadic chain.
    ⁺        Repeat the previous chain (everything up to here).
     ÑÑ      Call the second helper link twice on the whole matrix.

S;;S    First helper link. Argument: v (1-dimensional list)
S         Sum the argument list.
 ;        Append the argument list to the sum.
  ;       Append...
   S      ...the sum of the argument list.

ŒDµḊṖÑµ€1¦ŒḌU    Second helper link. Argument: M (matrix)
ŒD                 Get the diagonals of the matrix, starting with the main diagonal.
  µ                Begin a new monadic chain.
      µ€           Perform the following actions on each diagonal...
        1¦         ...and keep the result for the first item (main diagonal):
   Ḋ                 Remove the first item (incorrect top corner).
    Ṗ                Remove the last item (incorrect bottom corner).
     Ñ               Call the first helper link on the diagonal to pad it with its sum.
          ŒḌ       Convert the diagonals back to the matrix.
            U      Reverse each row, so that consecutive calls fix the other corners.

```

# Answer
> 3 votes
# APL (Dyalog), 37 bytes

```
(d,+⌿,d∘⌽)⍪(+/,⊢,+/)⍪d∘⌽,+⌿,d←+/1 1∘⍉

```

Try it online!

`1 1∘⍉` diagonal (lit. collapse both axes into one)

`d←` store that function as *d* and apply it to the argument

`+⌿` prepend the column sums

`d∘⌽,` prepend *d* applied to the reversed argument

`(``)⍪` stack the following on top:

`+/,⊢,+/` row sums, the unmodified argument, row sums

`(``)⍪` stack the following on top:

`d,+⌿,d∘⌽` applied to the argument, column sums, *d* applied to the reversed argument

# Answer
> 3 votes
# Python 3, 155 bytes

This is the suggestion of @LeakyNun, which saves **54 bytes**. I then golfed it myself a bit.

```
def f(m):l=len(m);r=range(l);s=sum;b=[s(m[i][i]for i in r)];c=[s(m[i][l+~i]for i in r)];d=[*map(s,zip(*m))];return[b+d+c,*[[s(a),*a,s(a)]for a in m],c+d+b]

```

Try it online!

# Initial solution - Python 3, 216 bytes

```
def f(m):l=len(m);r,s=range(l),sum;a,b,c,d=s(m[i][i]for i in r),s(m[i][l-i-1]for i in r),[s(m[i][j]for j in r)for i in r],[s(m[i][j]for i in r)for j in r];print([[a]+d+[b]]+[[c[i]]+m[i]+[c[i]]for i in r]+[[b]+d+[a]])

```

Try it online!

# Answer
> 2 votes
# Python 2, ~~268~~ ~~250~~ ~~184~~ 174 bytes

10 thanks to Stewie Griffin

```
from numpy import *
a,c,v,s=sum,trace,vstack,matrix(input())
l,r,d,e=a(s,0),a(s,1),c(s),c(fliplr(s))
print hstack((v(([[d]],r,[[e]])),v((l,s,l)),v(([[e]],r,[[d]])))).tolist()

```

Try it online!

**Some explanations** The input is uploaded as a matrix. First the code computes the sum of each column and each row using numpy.sum. Then it computes the sum of the diagonal by numpy.trace. After this it obtains the other diagonal by making a left-right flip on the matrix. Finally, it uses numpy.vstack and numpy.hstack to glue the pieces together.

# Answer
> 2 votes
# R, 129 bytes

```
pryr::f(t(matrix(c(d<-sum(diag(m)),c<-colSums(m),a<-sum(diag(m[(n<-nrow(m)):1,])),t(matrix(c(r<-rowSums(m),m,r),n)),a,c,d),n+2)))

```

An anonymous function that takes a square matrix as input. I'll post an explanation if there's interest.

# Answer
> 2 votes
# PHP, 211 bytes

```
<?foreach($_GET as$l=>$r){$y=0;foreach($r as$k=>$c){$y+=$c;$x[$k]+=$c;$l-$k?:$d+=$c;($z=count($_GET))-1-$k-$l?:$h+=$c;}$o[]=[-1=>$y]+$r+[$z=>$y];}$o[]=[-1=>$h]+$x+[$z=>$d];print_r([-1=>[-1=>$d]+$x+[$z=>$h]]+$o);

```

Try it online!

Expanded

```
foreach($_GET as$l=>$r){
  $y=0; # sum for a row
  foreach($r as$k=>$c){
    $y+=$c; # add to sum for a row
    $x[$k]+=$c; # add to sum for a column and store in array
    $l-$k?:$d+=$c; # make the diagonal sum left to right
    ($z=count($_GET))-1-$k-$l?:$h+=$c; # make the diagonal sum right to left
  }
  $o[]=[-1=>$y]+$r+[$z=>$y]; # add to result array the actual row with sum of both sides
}
$o[]=[-1=>$h]+$x+[$z=>$d]; # add to result array the last array
print_r([-1=>[-1=>$d]+$x+[$z=>$h]]+$o); #output after adding the first array to the result array

```

# Answer
> 2 votes
# Python 3, 125 bytes

```
from numpy import*
f=lambda m,t=trace,s=sum:c_[r_[t(m),s(m,1),t(m[::-1])],c_[s(m,0),m.T,s(m,0)].T,r_[t(m[::-1]),s(m,1),t(m)]]

```

Try it online!

Slightly ungolfed:

```
import numpy as np

def f_expanded(m):
    return np.c_[np.r_[np.trace(m), np.sum(m, 1), np.trace(m[::-1])],
                 np.c_[np.sum(m, 0), m.T, np.sum(m, 0)].T,
                 np.r_[np.trace(m[::-1]), np.sum(m, 1), np.trace(m)]]

```

This takes input formatted as a numpy array, then uses the `np.c_` and `np.r_` indexing tools to build a new array in one go. `np.trace` and `np.sum`are used to calculate the sums along the diagonals and everywhere else, respectively. `T` is used to take the transpose before and after concatenating the sums because it's shorter than making all the arrays 2-dimensional and using `np.r_`. `m[::-1]` saves bytes when compared to `rot90(m)` or `fliplr(m)` for finding the trace for the second diagonal.

# Answer
> 2 votes
# Jelly, ~~24~~ 19 bytes

```
,U$⁺Æṭj€SW€j§,"`j"Ɗ

```

Try it online!

I know there's already 2 Jelly answers, but this, I think, is fairly different from them both, and is shorter.

The Footer in the TIO link converts the inputs into 2D arrays, runs the above link over them then outputs them similar to the input format.

## How it works

```
,U$⁺Æṭj€SW€j§,"`j"Ɗ - Main link. Takes a matrix A on the right
  $                 - Collect the previous two links:
 U                  -   Reverse each row of A
                        rev(A) = A with reversed rows
,                   -   Yield the pair [A, rev(A)]
   ⁺                - Do this again on [A, rev(a)]:
                      [A, rev(A)]U   -> [rev(A), A]
                      [A, rev(A)],U$ -> [[A, rev(A)], [rev(A), A]]

    Æṭ              - Take the trace of each.
                       This returns [[Tr(A), Tr(rev(A))], [Tr(rev(A)), Tr(A)]]
                       where Tr(·) returns the trace

        S           - Yield the sums of the columns of A
       €            - Over each pair in l:
      j             -   Insert the column sums between their elements
         W€         - Wrap each in an array
                  Ɗ - Group and run the previous commands on A:
            §       -   Yield the row sums of A
             ,"`    -   Pair each with itself
                 "  -   Zip the rows of A with the pairs of row sums
                j   -   Insert each row between each pair.
           j        - Insert the rows plus their sums in between the diagonal and column sums

```

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

```
(a,m=g=>a.map((_,i)=>g(i)),s=x=>eval(x.join`+`))=>[[d=s(m(i=>a[i][i])),...c=m(i=>s(m(j=>a[j][i]))),g=s(m(i=>a[i][a.length-i-1]))],...a.map(b=>[r=s(b),...b,r]),[g,...c,d]]

```

Input and output is a 2D array of numbers.

## Explained

```
(a,                             // input matrix: a
    m=g=>a.map((_,i)=>g(i)),    // helper func m: map by index
    s=x=>eval(x.join`+`)        // helper func s: array sum
) =>
[
    [
        d = s(m(i=>a[i][i])),           // diagonal sum: d
        ...c=m(i=>s(m(j=>a[j][i]))),    // column sums: c
        g = s(m(i=>a[i][a.length-i-1])) // antidiagonal sum: g
    ],
    ...a.map(b=>[r = s(b), ...b, r]),   // all rows with row sums on each end
    [g, ...c, d]                        // same as top row, with corners flipped
]

```

## Test Snippet

Input/output has been formatted with newlines and tabs.

```
f=
(a,m=g=>a.map((_,i)=>g(i)),s=x=>eval(x.join`+`))=>[[d=s(m(i=>a[i][i])),...c=m(i=>s(m(j=>a[j][i]))),g=s(m(i=>a[i][a.length-i-1]))],...a.map(b=>[r=s(b),...b,r]),[g,...c,d]]

let tests=[[[0]],[[1,5],[0,2]],[[17,24,1,8,15],[23,5,7,14,16],[4,6,13,20,22],[10,12,19,21,3],[11,18,25,2,9]],[[15,1,2,12],[4,10,9,7],[8,6,5,11],[3,13,14,0]]];
```

```
<select id=S oninput="I.value=S.selectedIndex?tests[S.value-1].map(s=>s.join`\t`).join`\n`:''"><option>Tests<option>1<option>2<option>3<option>4</select> <button onclick="O.innerHTML=I.value.trim()?f(I.value.split`\n`.map(s=>s.trim().split(/\s+/g))).map(s=>s.join`\t`).join`\n`:''">Run</button><br><textarea rows=6 cols=50 id=I></textarea><pre id=O>
```

# Answer
> 0 votes
## LOGO, 198 bytes

```
to g :v[:h reduce "+ :v]
op(se :h :v :h)
end
to f :s[:a reduce "+ map[item # ?]:s][:b reduce "+ map[item # reverse ?]:s][:c apply "map se "sum :s]
op `[[,:a ,@:c ,:b],@[map "g :s][,:b ,@:c ,:a]]
end

```

The function `f` takes in a matrix as a 2D list, then output the resulting matrix. `g` is helper function.

# Answer
> 0 votes
# 05AB1E, 38 bytes

```
ODŠζsζ€R€˜IÅ\OUIÅ/OVIÅ|ODXšYªsXªYšŠšsª

```

Try it online!

### Input

A list of lists as a representation of a matrix.

### Output

A list of lists as a representation of a matrix.

### Explanation

```
ODŠζsζ€R€˜IÅ\OUIÅ/OVIÅ|ODXšYªsXªYšŠšsª
OD                                            Sum of rows and duplicate
  Š                                           Triple swap
   ζ                                          Zip arrays (to append to the rows)
    sζ                                        Swap and do the same (to prepend to the rows)
      €R€˜                                    Reverse each row and deep flat each row, making the new rows.
          IÅ\OU                               Get the diagonal of the input, sum it and save in variable X
               IÅ/OV                          Get the anti-diagonal of the input, sum it and save in variable Y
                    IÅ|OD                     Get the columns of the input, sum it and duplicate the sums vector.
                         Xš                   Prepend variable x
                           Yª                 Append variable y
                             sXªYš            Repeat for the second row, but now the prepend and append values are switched
                                  Ššsª        Append and Prepend the new rows (first and last)

```

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


title: Expand the variadic expression

text:
# Question
Title: Expand the variadic expression
One of the cool features introduced in the C++11 standard is the ability to declare a template parameter as being variadic; i.e. that parameter represents a sequence of an arbitrary number of arguments (including zero!).

For example, suppose the parameter pack `args` expands contains the sequence `A0, A1, A2`. To expand the pack, an expression is followed using the expansion operator `...`, and the expression is repeated for each argument with the parameter pack replaced by each element of the pack.

Some example expansions (assume `f` and `g` are not variadic packs):

```
args... -> A0, A1, A2
f(args)... -> f(A0), f(A1), f(A2)
args(f,g)... -> A0(f,g), A1(f,g), A2(f,g)

```

If the expansion operator is used on an expression which contains multiple un-expanded parameter packs, the packs are expanded in lock-step. Note that it is required that all parameter packs which participate in a single expansion operator must all have the same length.

For example, consider the packs `args0 -> A0, A1, A2` and `args1 -> B0, B1, B2`. Then the following expressions expand to:

```
f(args0, args1)... -> f(A0, B0), f(A1, B1), f(A2, B2)
g(args0..., args1)... -> g(A0, A1, A2, B0), g(A0, A1, A2, B1), g(A0, A1, A2, B2)

```

The goal of this challenge is given an expression and set of parameter packs, produce the expanded equivalent.

Note that there must be at least one un-expanded parameter pack as the argument to the expansion operator. All of the following are syntax errors (assume `args0 = A0, A1, A2`, `args1 = B0, B1`):

```
f(args0, args1)... // packs must have the same length
f(c)... // no un-expanded packs in expansion operator
f(args0...)... // no un-expanded packs in expansion operator

```

Your program needs not handle any expressions which result in a syntax error.

# Input

Your program/function should take as input a dictionary-like object which associates a parameter pack name with it's arguments, and an expression to be expanded (expression syntax explained later). For example, in Python-like syntax the dictionary of packs might look something like this:

```
{'args0': ['A0', 'A1', 'A2'],
 'args1': [],
 'args2': ['B0', 'A1', 'B2']}

```

Feel free to adapt the parameter pack input dictionary as desired. For example, it could be a list of strings where each string is a space-separated list and the first value is the pack name:

```
args0 A0 A1 A2
args1
args2 B0 A1 B2

```

Expressions to be expanded will contain only valid C++ identifiers (case-sensitive alpha-numerics and underscore), function call operators, parenthesis grouping, commas, and the expansion operator. Any identifiers in the expression which are not in the dictionary of parameter packs are not variadic. You may assume the given expression has a valid expansion. It is your decision on what restrictions there are on how whitespace is used (for example, every token has a space between it and other tokens, or no whitespace at all).

The input may come from any source desired (stdin, function parameter, etc.)

# Output

The output of your program/function is a single string representing the expanded expression. You are allowed to remove/add any whitespace or parenthesis grouping so long as the expression is equivalent. For example, the expression `f(a,b,c,d)` is equivalent to all of the following:

```
(f(((a,b,c,d))))
f ( a,  b, c , d )
f((a), (b), (c), (d))

```

The output can be to any source desired(stdout, function return value, etc.)

# Examples

All examples are formatted as such:

The dictionary of packs are expressed as lines of strings in the example format given above (space separated, first value is the pack name), followed by the expression, and the expected result.

case 1:

```
args0 A0
args2 B0 A0
args1
args0...
A0

```

case 2:

```
args0 A0
args2 B0 A0
args1
args1...
// nothing

```

case 3:

```
args0 A0
args2 B0 A0
args1
f(args1)...
// nothing

```

case 4:

```
args0 A0
args2 B0 A0
args1
f(args1...)
f()

```

case 5:

```
args0 A0
args2 B0 A0
args1
f(C0, args0..., args2)...
f(C0, A0, B0), f(C0, A0, A0)

```

case 6:

```
args0 A0 A1
args1 B0 B1
args2 C0 C1
f(args0, args1, args2)...
f(A0, B0, C0), f(A1, B1, C1)

```

case 7:

```
args0 A0 A1
args0(C0)...
A0(C0), A1(C0)

```

case 8:

```
args0 A0 A1
args1 B0 B1
args0(args1(f))...
A0(B0(f)), A1(B1(f))

```

case 9:

```
args0 A0 A1
args1 B0 B1
f_(c)
f_(c)

```

case 10:

```
args0
args1 A0 A1
f(args0..., args1)...
f(A0), f(A1)

```

# Scoring

This is code-golf; shortest code in bytes wins. Standard loop-holes apply. You may use any built-ins desired.

# Answer
> 1 votes
# Python 3, 567 bytes

```
lambda v,q:w(g(v,p(q),-1))
def c(s):
	a=[];b=0;l=""
	for x in s:
		if x!=","or b:l+=x;b+=~-")(".find(x)%3-1
		else:a+=[p(l)];l=""
	return a+[p(l)]
p=lambda s:(0,p(s[:-3]))if"..."==s[-3:]else(1,(2,s.split("(")[0]),c(s[s.find("(")+1:-1]))if")"==s[-1]else(2,s)
def g(v,q,i):
	if q[0]>1:return q[1]if q[1]not in v or i<0else v[q[1]][i]
	if q[0]:return(g(v,q[1],i),[g(v,k,i)for k in q[2]])
	a=[];i=0
	while 1:
		try:a+=[g(v,q[1],i)];i+=1
		except:return a
w=lambda k:",".join(q for q in[w(x)for x in k]if q)if type(k)==list else k if type(k)==str else k[0]+"("+w(k[1])+")"

```

Try it online!

Could use a lot of golfing but I'm pretty happy with this answer. Tested on all 10 example cases.

-9 bytes thanks to Neil

# Answer
> 1 votes
# Wolfram Language (Mathematica), ~~267~~ 246 bytes

```
Reverse[R=StringReplace@{"("->"[",")"->"]","..."->"!",a:(WordCharacter|"_")..:>"\""<>a<>"\""},3]@ToString[a@ToExpression@R@#2//.a_String@b___:>a~q~b/.p@@@#//.a_?(FreeQ[_!])!:>(a//.s_/;FreeQ[s,p,{3,∞}]:>s~Thread~p/.p->(##&))/.q->Construct]&
a=""

```

Try it online!

As far as I can tell there's no built-in way to `Thread` beyond the first level (or `Thread` heads, for that matter).

```
a=""                                        (* ensures Reverse[R,3] works properly  *)
R=StringReplace@{                           (* parses input: *)
  "("->"[",")"->"]",                        (*  convert brackets to mathematica-style *)
  "..."->"!",                               (*  `...` is costly to manipulate, so instead use something that isn't. *)
  a:(WordCharacter|"_")..:>"\""<>a<>"\""};  (*  wrap symbols in quotes so they won't evaluate. *)
a@ToExpression@R@#                          (* parse input and wrap it with "" to allow multiple outputs *)
 //.a_String@b___:>a~q~b                    (* convert expressions to a form suitable for calling Thread *)
  /.p@@@#                                   (* substitute packed arguments *)
 //.a_?(FreeQ[_!])!]:>                      (* expand ...s from the bottom up: *)
   (a//.s_/;FreeQ[s,p,{3,∞}]:>s~Thread~p    (*  thread over packed arguments from the bottom up, *)
      /.p->(##&))                           (*  and unpack into sequences. *)
  /.q->Construct                            (* convert back into an expression *)
Reverse[R,3]@ToString[ % ]                  (* convert to c-style output. *)

```

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


title: Tips for golfing in Husk

text:
# Question
Title: Tips for golfing in Husk
Husk is a quite new golfing language, created by PPCG users Leo and Zgarb. It has begun being more and more competitive, often staying close or even beating languages known to be very terse, such as Jelly and 05AB1E.

Let's list some of the golfing techniques that are somewhat specific to Husk. As always, please post one tip per answer.

# Answer
# Use the return value from predicates

In Husk, functions that test their inputs for some property will usually return a meaningful result in truthy cases, as any positive integer is truthy.

**Examples:**

```
≠  Numbers: Absolute difference
   Chars:   Absolute difference of code points
   Lists:   First Index where the differ

Comparisons <, >, ≤, ≥:

For strict comparisons:
Numbers,Chars:  max 0 (the appropriate difference¹)
Lists: The first index where the comparison between the two lists is true

For non-strict comparisons:
Numbers,Chars: max 0 (the appropriate difference + 1)
Lists: Either the result of the strict comparison or, if they are equal,
       the length of the list + 1

ṗ  Index into the list of prime numbers

V  The index of the first element for which the condition is true

€  The first index of that element/substring in the list

£  Works like €

&  Given two arguments of the same type will return the second argument if false,
   otherwise will return the first argument

|  Given two arguments of the same type will return the second argument if true,
   otherwise will return the first argument

¦  Return the quotient if divisibility holds

Λ,E,Ë  Will all return length+1 in truthy cases

Char predicates:
□,±,√,D,½  will each return the codepoint of its argument on truthy cases

```

¹ **appropriate difference** means difference of code points for chars. It also refers to the argument order. i.e For `<x y`, would be `x-y`
> 10 votes

# Answer
# Use overflowing line labels

As you may already know,  `[₀-₉]+|[₀-₉]` is regex for the syntax to call a different line than the one you're currently in.

This tip is especially useful if you want a function defined on a specific line to be called as an argument of more than one of the functions in the table below, or as an argument to one or more of the functions below and by itself.

Function table:

```
+----------+----------+
|Index     |Function  |
+----------+----------+
|1         |´ (argdup)|
+----------+----------+
|2         |` (flip)  |
+----------+----------+
|3         |m (map)   |
+----------+----------+
|4         |z (zip)   |
+----------+----------+
|5         |S (hook)  |
+----------+----------+

```

Lines in your code are labeled with their respective 0-based indices, from top to bottom. If **M \< N**, where **M** is the label and **N** is the number of lines in your code, the label just represents the function defined at line **M**. If **N ≤ M \< N * 6**, it represents the function from the table above at index **⌊M ÷ N⌋** with the function defined at line **M mod N** as its first argument. If **N * 6 ≤ M**, an index error is raised.
> 7 votes

# Answer
# Uses of `Γ`

The main use of the built-in `Γ`, known as *pattern matching on lists* or *list deconstruction*, is to split a list into a head and tail, and apply a binary function on them. This corresponds to the Haskell pattern matching idiom

```
f (x : xs) = <something>
f [] = <something else>

```

where `<something>` is an expression containing `x`, `xs` and possibly `f`. There are 4 overloadings of `Γ`, each of which works a little differently.

### `list`

The first overloading, `list`, takes a value `a` and a binary function `f`. It returns a new function that takes a list, returns `a` if it's empty, and calls `f` on the head and tail if it's nonempty. For example, `Γ_1€` takes a list, returns `-1` if it's empty, and the index of first occurrence of the first element in the tail if not.

### `listN`

The second overloading, `listN`, is similar to `list`, except that `a` is omitted and the default value of the return type is used instead. For example, `Γ€` is equivalent to `Γ0€`, since the default numeric value is `0`.

In practice, `listN` is used more often than `list`, since the default value is either irrelevant or exactly what you need. A common pattern is `Γ~αβγ`, where `αβγ` are three functions; this applies `β` to the first element and `γ` to the tail, and combines the results with `α`. It was used e.g. in this answer. Other patterns include `Γo:α` for applying `α` only to the first element, and `Γ·:mα` for applying `α` to all elements except the first. The latter was used in this answer.

### `listF`

The third overloading is a bit more involved. Like `list`, it takes a value `a` and a function `f`, and returns a new function `g` that takes a list. However, this time `f` takes an extra function argument, which is `g` itself, and can call it on any value (including, but not limited to, the tail of the input list). This means that `listF` implements a general *recursion scheme* on lists. `listF` is not used very often, since explicit recursion with `list`/`listN` is usually of the same length or shorter, as in this answer.

### `listNF`

`listNF` is to `listF` what `listN` is to `list`: the input `a` is omitted, and the default value of the return type is used instead. In rare circumstances, it can be shorter than a right fold, for example in this answer.

As an example of the recursive versions of `Γ`, the function `Γλ·:o⁰↔` shuffles a list in the order first, last, second, second-to-last, third, third-to-last, and so on. Try it online! The function `f` is the explicit lambda `λ·:o⁰↔`, whose argument  is the entire function. What `f` does is reverse the tail with , then call the main function recursively with `o⁰`, and finally tack the head back with `·:`. Of course, `Γ·:o₀↔` is a byte shorter, but doesn't work if the line contains something else than this function.
> 7 votes

# Answer
## Lambdas can be shorter than new functions

As you probably know if you have a multi-line program, you can refer to the lines with the subscripts `₀…₉`, for example in the case of

```
f
g

```

will refer to the function `g`. Now if you always apply the inputs to the function `g` (and use it multiple times); something like this:

```
f₁⁰[...]g₁⁰[...]
h

```

You should introduce a lambda because it saves you 1 byte for each additional use:

```
λf⁰[...]g⁰[...])h

```

---

## The reverse might be true as well

In the case of self-referential lambdas (`φχψ`), there's the special case where you apply the inputs directly to the recursive function, in these cases you're better off by using the subscript  instead of defining a new lambda and using .
> 6 votes

# Answer
# Combinators can be applied to higher order functions

Suppose you have a list of integers **X**, and you want to count the total number of elements of **X** that are larger than **length(X)**. Counting elements that satisfy a predicate is done with the higher order function `#`, but here the predicate (being larger than **length(X)**) depends on **X**. The solution is to apply the combinator  to `#` and the function `o>L` that checks whether a list is shorter than a number. In the function `Ṡ#o>L`, the list **X** is passed to `o>L`, the partially applied function is passed to `#`, and **X** is given to `#` as the second argument.

In general, if `α` is a higher-order function, `β` a binary function and `γ` a unary function, `Ṡαβ` is equivalent to the Haskell pseudocode

```
\x -> α (\y -> β x y) x

```

`§αβγ` is equivalent to

```
\x -> α (\y -> β x y) (γ x)

```

and `~αβγ` is equivalent to

```
\x y -> α (\z -> β x z) (γ y)

```

as long as the types match.

As another concrete example, `§►δṁ≠P` finds a permutation of a list **X** that maximizes the sum of absolute differences to corresponding values of **X** (`δṁ≠` zips two lists using absolute difference and takes the sum).
> 3 votes

# Answer
## Husk's default values

Husk is not as strict as Haskell where you run into trouble when for example you try to get the `last` element of an empty list. To achieve this it uses predefined values, here's a list of the default values, maxima and minima:

```
.------------------------------------.---------------.----------.-------.
|   Type (X and Y are placeholders)  | default (def) |    max   |  min  |
|------------------------------------|---------------|----------|-------|
|       Character (C)                |      ' '      | \1114111 | \NUL  |
|       Numbers   (N)                |       0       |   Inf    | -Inf  |
|       List of X (LX)               |      []       |  ∞ max   |   []  | *
|       Function :: X -> Y           | const (def Y) |   n/a    |  n/a  |
'------------------------------------'---------------'----------'-------'

```

 * Here ∞ should represent an infinite list of the corresponding maximum (see below for an example)

 **Note:** For tuples (X,Y) it will use the values for each component separately.

---

## When they are used

While the maxima and minima are only used for `▲▼` on empty lists (for example `husk -u "▼" "[]:LLN"` will return an infinite list of `Inf`) the default values are used in a few places:

* folding over empty lists without providing a value yourself (`F` and )
* prepending default value (with `Θ`)
* when read (`r`) fails
* getting the first/last element (`←→`) or indexing into one (`!`)
* pattern matching (`Γ`) on empty lists
* using  or  on empty lists
> 3 votes

# Answer
# Use `,` , `e` and `ė` to debug your functions

Since Husk is a functional programming language, a lot of times you'll find yourself in a situation where you have a function with two arguments passed to it, which returns an unexpected result.

You can replace any two argument function with `e`/`ė`, so long as it's arguments are homogeneous(have the same datatype)

`,`, on the other hand makes a pair. It can only be used for 2 argument functions, but it supports heterogeneous types.

For example,

```
S+ȯ□½→

```

returns the number added to itself incremented, halved then squared in that order (\\$x + \frac{(x+1)^2}4\\$)

```
Seȯ□½→

```

will return a two element list with the original element, and the result of the function composition.

For example,

```
1 → [1,1]
2 → [2,9/4]
3 → [3,4]

```

and so on.
> 3 votes

---
Tags: code-golf, tips
---


title: Compactify the query string

text:
# Question
Title: Compactify the query string
## Introduction

Just on Hacker news, John Resig contemplates transforming a query “foo=1&foo=2&foo=3&blah=a&blah=b” into one that looks like this: “foo=1,2,3&blah=a,b", https://johnresig.com/blog/search-and-dont-replace/. He claims "being 10 lines shorter than Mark’s solution".

Query strings consist of sequences of name-value pairs. Name-value pairs consist of a name and value, separated by =. names and values are possibly empty sequences of alphanumeric characters. Name-value pairs are separated by the & character in the sequence. Values are unique for each name.

## Challenge

10 lines shorter than Mark's solution is not enough.

* Read a query string.
* Combine name value pairs with equal name into a single name value pair, with values concatenated and separated by comma.
* Output the combined query string, with name-value pairs in the order the names are found from left to right in the query string.

This is code golf, the standard loopholes are closed.

## Example Input and Output

Input:

> foo=1&foo=&blah=a&foo=3&bar=x&blah=b&=1&=2

Output:

> foo=1,,3&blah=a,b&bar=x&=1,2

Input:

> foo=bar&foo=foo

Output:

> foo=bar,foo

# Answer
> 4 votes
# 05AB1E, 23 bytes

```
'&¡'=δ¡.¡н}εø€Ù}…,=&vyý

```

Try it online or verify all test cases.

**Explanation:**

```
'&¡                     '# Split the (implicit) input-string on "&"
     δ                   # For each inner string:
   '= ¡                 '#  Split it on "="
       .¡ }              # Group all pairs by:
         н               #  Their first value
           ε             # Map over each group of pairs:
            ø            #  Zip/transpose, swapping rows/columns
             €           #  For both inner lists:
              Ù          #   Uniquify it
               }…,=&     # After the map: push string ",=&"
                    v    # Pop and loop over each character `y`:
                     yý  #  Join the inner-most list of strings with `y` as delimiter
                         # (after the loop, the result is output implicitly)

```

Try it online with a step-by-step output.

# Answer
> 12 votes
# JavaScript (ES6),  ~~103 99 87~~  86 bytes

*Saved 1 byte thanks to @MatthewJensen*

```
s=>Object.values(o=/(\w*=)(\w*)/g,s.replace(o,(s,k,v)=>o[k]=o[k]?o[k]+[,v]:s)).join`&`

```

Try it online!

### Commented

```
s =>                  // s = query string
  Object.values(      // get the values of ...
    o =               //   ... the object of this regular expression, which is
      /(\w*=)(\w*)/g, //   re-used to store the keys and values of the query
    s.replace(        //   match each key with the '=' sign and the corresponding
      o,              //   value, using the regular expression defined above
      (s, k, v) =>    //   for each matched string s, key k and value v:
        o[k] =        //     update o[k]:
          o[k] ?      //       if it's already defined:
            o[k] +    //         get the current value
            [, v]     //         append a comma, followed by v
          :           //       else:
            s         //         set it to the entire matched string
                      //         (key, '=', first value)
    )                 //   end of replace()
  ).join`&`           // end of Object.values(); join with '&'

```

# Answer
> 10 votes
# JavaScript, ~~263~~ ~~201~~ ~~196~~ ~~194~~ ~~190~~ ~~189~~ ~~188~~ ~~173~~ 161 bytes

```
q=>{w={};q.split`&`.map(x=>{y=x.split`=`;if(!w[y[0]])w[y[0]]=[];w[y[0]].push(y[1])});z=`${Object.entries(w).map(a=>a=[a[0]+'='+a[1].join`,`]).join`&`}`;return z}

```

Try it online

# Answer
> 7 votes
# Python 3.8 (pre-release), 116 bytes

```
lambda s:(a:=[k.split("=")for k in s.split("&")])and"&".join(b+"="+",".join(d for c,d in a if c==b)for b in dict(a))

```

Try it online!

-46 bytes thanks to ovs

-1 byte thanks to Jonathan Allan (in Py 3.8 PR, with walrus)

# Answer
> 7 votes
# Julia 1.0, 106 bytes

```
f(a,z=split.(split(a,'&'),'='),u=first.(z))=join((i*'='*join(last.(z)[u.==i],',') for i in unique(u)),"&")

```

Try it online!

# Answer
> 7 votes
# Ruby, 88 80 76 64 bytes

```
->s{s.scan(/(\w*=)(\w*)/).group_by(&:shift).map{|k,v|k+v*?,}*?&}

```

Try it online!

*-8 bytes thanks to ovs for pointing I could assign a lambda to a variable*

*-12 bytes thanks to Dingus!*

# Answer
> 5 votes
# Jelly, 28 bytes

-2 Thanks to Zgarb!

```
ṣ”&ṣ€”=Ṗ€ĠṢịƲµZQ€j€”,j”=)j”&

```

A monadic Link accepting and yielding a list of characters.

**Try it online!**

### How?

```
ṣ”&ṣ€”=Ṗ€ĠṢịƲµZQ€j€”,j”=)j”& - Link: list of characters, S
ṣ”&                          - split at '&'s
   ṣ€”=                      - split each at '='s
                               call that A
            Ʋ                - last four links as a monad - f(A):
       Ṗ€                    -   all but last of each
         Ġ                   -   group indices by their values
          Ṣ                  -   sort (since Ġ orders by the values, not the indices)
           ị                 -   index into (A) (vectorises)
             µ          )    - for each:
              Z              -   transpose
               Q€            -   deduplicate each
                 j€”,        -   join each with ','s
                     j”=     -   join with '='s
                         j”& - join with '&'s

```

# Answer
> 5 votes
# 05AB1E, ~~62~~ 51 bytes

(-11 from @kevin)

```
'&¡'=δ¡D€нÙÐV_UsvYyнk©Xsèyθ',««Xs®ǝU}Xε¦¨}Yζí'=ý'&ý

```

Try it online!

My 62 approach:

```
'&¡ε'=¡}D€нÙ©DgÅ0Usvy¬®skDVXsèyθ',««XsYǝU}Xε¦¨}®ζεć'=s««˜}˜'&ý

```

Explanation:

```
'&¡ε'=¡}D€нÙ©DgÅ0Usvy¬®skDVXsèyθ',««XsYǝU}Xε¦¨}®ζεć'=s««˜}˜'&ý
'&¡                                                              split by &
   ε'=¡}                                                         foreach: split by =
        D                                                        duplicate
         €н                                                      foreach: push header (get the keys list)
           Ù                                                     uniquify
            ©                                                    save in register c
             Dg                                                  suplicate and get the length of that list of keys
               Å0                                                create a list of 0's with the length above
                 U                                               save in variable X
                  svy                    }                       for each set of key-value
                     ¬®sk                                        find the index of that key in the keys list
                         DV                                      save the index in variable y
                           Xsè                                   get the current value of the element of X at index Y (in X we are keeping the concatenation of the values for key i)
                              yθ                                 extract the tail of the element in this iteration (a value to concatenate)
                                ',««                             concatenate with , in between
                                    XsYǝU                        update X with the new value of the element representing the key
                                          Xε¦¨}                  remove tail and head from each element of X (removing the trailing , and leading 0)
                                               ®                 push back the list of keys
                                                ζ                zip (list of keys and list of merged values)
                                                 εć'=s««˜}       foreach element in the zipped list, join with = in between such that the result is "key=values"
                                                          ˜      flat
                                                           '&ý   join with &

```

Try it online!

# Answer
> 5 votes
## JavaScript, 79 bytes

```
f=
s=>(s=new URLSearchParams(s)).forEach((v,k)=>s.set(k,s.getAll(k)))||unescape(s)
```

```
<input oninput=o.textContent=f(this.value)><pre id=o>
```

If I/O could be actual query strings according to the WHATWG spec, rather than invalid strings that looks like query strings but aren't correctly URLencoded, then 7 bytes could be saved by stringifying the result instead of unescaping it.

# Answer
> 5 votes
# Python 3, 94 bytes

```
lambda s:'&'.join(k+'='+",".join(v)for k,v in parse_qs(s,1).items())
from urllib.parse import*

```

Try it online!

A few things:

* This only works because Python 3.6+ maintains dictionary order based upon time of insertion. We would love to use Python 2 for a shorter import (`urlparse` vs `urllib.parse`) but dictionaries are not ordered properly.
* As much as I love f-strings, `k+'='+",".join(v)` is shorter than `f'{k}={",".join(v)}'`.
* The double `.join` feels like golf smell, but I can't find a shorter way.

---

### Python 3, 95 Bytes

```
from urllib.parse import*
d=parse_qs(input(),1)
print('&'.join(k+'='+','.join(d[k])for k in d))

```

Try it online!

# Answer
> 4 votes
# JavaScript, ~~106~~ ~~104~~ 76 bytes

Port of Neil's Retina solution, posted with permission.

```
f=q=>q==(q=q.replace(/(?<=^|&)((\w*=)[^&]*)(.*?)&\2(\w*)/,`$1,$4$3`))?q:f(q)

```

Try it online!

## Original

A little bit of drunk golfing that I came back to work on sober but in the process spotted Arnauld's solution and realised I was on the path to something almost identical so I left this as-was.

```
q=>Object.keys(o={},q.split`&`.map(p=>o[[k,v]=p.split`=`,k]=[...o[k]||[],v])).map(x=>x+`=`+o[x]).join`&`

```

Try it online!

# Answer
> 3 votes
# Retina 0.8.2, 45 bytes

```
+1`(?<=^|&)((\w*=)[^&]*)(.*?)&\2(\w*)
$1,$4$3

```

Try it online! Explanation: Repeatedly matches the first duplicate key and its first duplicate and joins the value to that of the original key.

# Answer
> 3 votes
# Japt, ~~29~~ ~~28~~ ~~27~~ ~~26~~ 24 bytes

```
q& móÈk¶
ü@bøXÎÃ®ÕvÎqÃq&

```

Try it

Saved 2 bytes thanks to some inspiration from Kevin.

(Oh, if only Japt had a method just for grouping, rather than also sorting, this could be 19 bytes.)

## Explnataion

```
q& móÈk¥\nü@bøXÎÃ®ÕvÎqÃq&     :Implicit input of string U
q&                            :Split on "&"
   m                          :Map
    ó                         :  Partition after each character that returns falsey (i.e., an empty string)
     È                        :  When passed through the following function
      k                       :    Remove all characters that appear in
       ¥                      :    Literal "=="
        \n                    :Reassign to U
          ü                   :Group & sort by
           @                  :Passing each X through the following function
            b                 :  First index in U
             ø                :  That contains
              XÎ              :    First element of X
                Ã             :End grouping
                 ®            :Map each Z
                  Õ           :  Transpose
                   v          :  Map first element to
                    Î         :    Get first element
                     q        :  Join resulting array
                      Ã       :End map
                       q&     :Join with "&"

```

Or, to provide a step-by-step walkthrough:

### Input

```
"foo=1&foo=&blah=a&foo=3&bar=x&blah=b&=1&=2"

```

### Split

```
["foo=1","foo=","blah=a","foo=3","bar=x","blah=b","=1","=2"]

```

### Map & Partition

```
[["foo=","1"],["foo="],["blah=","a"],["foo=","3"],["bar=","x"],["blah=","b"],["=","1"],["=","2"]]

```

### Group & sort

```
[[["foo=","1"],["foo="],["foo=","3"]],[["blah=","a"],["blah=","b"]],[["bar=","x"]],[["=","1"],["=","2"]]]

```

### Map and ...

**Transpose**

```
[[["foo=","foo=","foo="],["1",null,"3"]],[["blah=","blah="],["a","b"]],[["bar="],["x"]],[["=","="],["1","2"]]]

```

**Map first element to its first element**

```
[["foo=",["1",null,"3"]],["blah=",["a","b"]],["bar=",["x"]],["=",["1","2"]]]

```

**Join**

```
["foo=1,,3","blah=a,b","bar=x","=1,2"]

```

### Join

```
"foo=1,,3&blah=a,b&bar=x&=1,2"

```

# Answer
> 2 votes
# Awk, ~~144~~ \\$\cdots\\$~~138~~ 135 bytes

```
BEGIN{RS="&"}{a[$1][j=i[$1]++]=$2;j||(n[m++]=$1)}END{for(l in n){k=n[l];o=k"=";for(j in a[k])o=o (j>0?",":"")a[k][j];printf z o;z="&"}}

```

*Added 6 bytes to fix a bug*
*Added 4 bytes to fix a bug kindly pointed out and solved by Dominic van Essen!!!*
*Saved 6 bytes thanks to Dominic van Essen!!!*
*Saved 3 bytes thanks to ceilingcat!!!*

Try it online!

# Answer
> 2 votes
# , 195 bytes

```
{Z=pryr::f
`/`=Z(a,b,el(regmatches(a,gregexpr(b,a))))
`-`=Z(a,b,paste(a,collapse=b))
Z(S,{L=S/'\\w*='
L=factor(L,unique(L))
U=tapply(S/'=\\w*',L,Z(a,trimws(a,,'=')-','))
paste0(names(U),U)-'&'})}

```

Try it online!

# Answer
> 2 votes
# SNOBOL4 (CSNOBOL4), ~~243~~ ~~221~~ 212 bytes

```
	Q =INPUT
	T =TABLE()
N	Q (ARB '=') . L ARB . V ('&' | RPOS(0)) REM . Q	:F(O)
	T<L> =T<L> ',' V 	:(N)
O	R =CONVERT(T,'ARRAY')
I	X =X + 1
	R<X,2> ',' REM . V 	:F(P)
	O =O '&' R<X,1> V	:(I)
P	O '&' REM . OUTPUT
END

```

Try it online!

`TABLE` in SNOBOL is weird. It's perfectly fine accepting a `PATTERN` like `ARB` as a key, but not the empty string `''`. However, using `<label>=` as the label instead of `<label>` neatly solves this problem.

Explanation for a previous iteration:

```
	E =RPOS(0)					;* alias for end of string
	A =ARB						;* alias for ARBitrary match (as short as possible)
	Q =INPUT					;* read input
	T =TABLE()					;* create a TABLE (a dictionary)
N	Q A . L '=' A . V ('&' | E) REM . Q	:F(O)	;* in regex land, this is something like
	;* '(.*=)(.*)(&|$)' where you save \1 and \2 as L and V, respectively. If there's no match, goto O
	T<L> =T<L> V ','	:(N)		;* update the values list, then goto N
O	R =CONVERT(T,'ARRAY')				;* convert T to a 2D array of [Label,Value]
I	X =X + 1					;* increment array index
	R<X,2> A . V ',' E	:F(P)			;* remove the trailing ',' from the value list. If X is out of bounds, goto P
	O =O R<X,1> V '&'	:(I)			;* Append L and V to O with an '=' and '&', then goto I
P	O A . OUTPUT '&' E				;* Print everything except for the trailing '&'
END

```

# Answer
> 2 votes
# Lua, 162 bytes

```
l,t={},{}(...):gsub('(%w-)=(%w-)',load"k,v=...o=t[k]l[#l+1]=not o and k or _ t[k]=o and o..','..v or v")for i=1,#l do io.write(i>1 and'&'or'',l[i],'=',t[l[i]])end

```

Try it online!

This is a long one, huh. It could have been made much shorter if not for ordering requiment.

Explanation:

```
l,t={},{} -- list (by first inclusion), table (keys to string)
-- (ab)use string replacement function to callback over matches in input string
(...):gsub(
    -- Match key-value pairs
    '(%w-)=(%w-)',
    -- For each pair, run callback (braces are replaced for multiline)
    load[[
        k,v=... -- Assign key, value
        o=t[k] -- Look for already stored string if any
        l[#l+1]=not o and k or _ -- If key is new, store it in list
        t[k]=o and o..','..v or v -- Append to string if it is not new, store it if it is
    ]]
)
-- For every record in list
for i=1,#l do
    -- Write with no newlines
    io.write(
        i>1 and'&'or'', -- Output & before all values but first
        l[i],'=',t[l[i]] -- Print key-value pair
    )
end

```

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

```
StringRiffle[Last@Reap[Sow@@@StringExtract[#,"&"->;;,"="->{2,1}],_,List],"&","=",","]&

```

Try it online! Pure function, takes a string as input and returns another string as output. This is inspired by and very similar to att's answer, but it uses an algorithm similar to the one in the blog post (here utilizing `Sow`/`Reap`). Here's an example of how the subexpressions evaluate on an input of `"foo=1&bar=a&foo="`:

```
StringExtract[#,"&"->;;,"="->{2,1}] == {{"1", "foo"}, {"a", "bar"}, {"", "foo"}}
Sow@@@...                           == {"1", "a", ""}; {"1", ""} sown w/ tag "foo"; {"a"} sown w/ tag "bar"
Reap[...,_,List]                    == {{"1", "a", ""}, {{"foo", {"1", ""}}, {"bar", {"a"}}}}
Last@...                            == {{"foo", {"1", ""}}, {"bar", {"a"}}}
StringRiffle[...,"&","=",","]       == "foo=1,&bar=a"

```

# Answer
> 2 votes
# Factor, 229 bytes

```
: c ( s -- s s ) 1 <hashtable> swap "&"split [ "="split ] map
[ [ dup [ last ] dip first pick push-at ] each ]
[ [ first ] map dup union ] bi dup [ [ over at ","join ] map ] dip
[ "="append ] map swap zip [ concat ] map "&"join ;

```

Try it online!

It's long but I'm somewhat content with it :)

# Answer
> 2 votes
# PHP, 146 bytes

```
<?=parse_str(str_replace('=','_[]=',$argv[1]),$a)??join('&',array_map(function($b,$c){return rtrim($b,'_').'='.join(',',$c);},array_keys($a),$a));

```

Try it online! Explanation: `parse_str` wasn't designed to handle repeated values, but you can persuade it to by naming each value with a trailing `[]`. It also wasn't designed to handle empty names, but since I'm appending `[]` anyway I can also add a `_` to satisfy that case. Having parsed the query string it then remains to join everything back together.

# Answer
> 1 votes
# Perl 5, `-pF\&` flags, ~~73~~ 57 bytes

Uses `-pF\&` to loop over inputs and autosplit on `&`.

Unordered results, in parallel competition.

```
/=/,$z{$`}.=$z{$`}?",$'":"$`=$'"for@F;$_=join'&',values%z

```

Try it online!

Uses a hash `%z` to keep track of values for individual names, and then prints them all out at the end. -16 bytes thanks to NahuelFouilleul.

# Answer
> 1 votes
# C (gcc), ~~319~~ 304 bytes

Thanks to ceilingcat for the suggestions.

This function scans each tokenized (name,value) pair and adds a list entry for each new name encountered, then appends a list entry for each value. After constructing the lists, it then iterates through each list and prints the values. To save space, I flattened the structures into arrays of `void *`.

```
f(s,t,v,i)char*s,*t;{void*d[3]={t=0},**f,**w;for(;t=strtok(t?0:s,"&");*w=calloc(8,2),w[1]=v){t[i=strcspn(t,"=")]=0;v=t-~i;for(f=&d;strcmp(f[1]?:t,t);f=*f);for(w=f[2]=f[1]?f[2]:(f[1]=t,*f=calloc(8,5))+24;w[1];w=*w);}for(f=&d;i=*f&&printf("&%s="+!!s,f[1]);f=*f)for(w=f[2];s=*w;w=s)i=!printf(",%s"+i,w[1]);}

```

Try it online!

Non-golfed version of original submission:

```
struct list {
  struct list *next;
  char *name;
  struct list *value;
};

void f(char *s) {
  char *tok=NULL, *value;
  struct list d={}, *e, *v;
  int i;

  for(; tok=strtok(tok?NULL:s, "&"); ) {
    tok[i=strcspn(tok, "=")]=0;
    value=tok+i+1;
    for(e=&d; e->name && strcmp(e->name, tok); e=e->next);
    if(!e->name) {
      e->next=calloc(sizeof(struct list), 2);
      e->name=tok;
      e->value=e->next+1;
    }
    for(v=e->value; v->name; v=v->next);
    v->next=calloc(sizeof(struct list), 1);
    v->name=value;
  }
  for(e=&d; e->next; e=e->next, s=0) {
    printf("&%s="+!!s, e->name);
    for(v=e->value, i=1; v->next; v=v->next, i=0)
      printf(",%s"+i, v->name);
  }
}

```

Try it online!

# Answer
> 1 votes
# Wolfram Language (Mathematica), ~~90~~ 88 bytes

```
StringRiffle[S=StringSplit;List@@@Normal@Merge[Rule@@@S[#~S~"&","=",2],#&],"&","=",","]&

```

Try it online!

-2 thanks to LegionMammal978

```
S=StringSplit;
Rule@@@S[#~S~"&","=",2]         (* Convert to a list of Rules *)
Merge[ % ,#&]                   (* Combine rules into an Association, leaving values unchanged *)
Normal@ %                       (* Convert Association back into a list of Rules, *)
List@@@ %                       (* and turn Rules into Lists *)
StringRiffle[ % ,"&","=",","]   (* Concatenate, using "&", "=", and "," as separators *)

```

# Answer
> 1 votes
# , ~~174~~ 166 bytes

```
function(s,S=strsplit,A=sapply,P=paste,e=A(S(P(el(S(s,'&')),'=',sep=''),'='),c),n=unique(m<-e[1,]))P(n,A(n,function(x)P(e[2,m==x],collapse=',')),sep='=',collapse='&')

```

Try it online!

For some inexplicable reason I thought that this challenge wouldn't suffer from 's awfully-verbose string handling.
This didn't turn out to be the case, at least based on my attempt so far...

Commented before golfing:

```
compactify=
function(s,                         # s = string to compactify
S=strsplit,                         # S = alias to strsplit() function
A=sapply,                           # A = alias to sapply() function
P=paste,                            # P = alias to paste() function
a=el(                               # a = the first element of ...
  S(s,'&'))                         #  ...s split on '&'
b=S(a,,'=')                         # b = each element of a, split on '='
                                    # Now, unfortunately if there's nothing after the '=',
                                    # the strsplit() function fails to add an empty string ''
                                    # so we need to do this ourselves:
e=A(b,function(x)c(x,'')            # e = for each element of b, add a '' ...
                        [1:2])      #  ...and then take the first two elements
                                    # This gives us a 2-row matrix, with the names in row 1,
                                    # and the values in row 2
n=unique(m<-e[1,]))                 # n = unique names, m = all names of name-value pairs
m=A(n,function(x)                   # m = for each element of n...
      P(e[2,m==x],collapse=','))    #  ...paste together the values for this name, using ',' as separator
P(n,m,sep='=',collapse='&')         # Finally, paste together the pairs of elements in m, using '=' as separator...
                                    #  ...and collapse them all into one string using '&' as separator

```

# Answer
> 1 votes
# Red, 221 bytes

```
func[s][m: copy #()s: split s"&"forall s[s/1: split s/1"="append s/1/1"="put m s/1/1
copy""]foreach v s[m/(v/1): append m/(v/1) rejoin[v/2","]]t: copy""foreach k keys-of
m[take/last m/:k repend t[k m/:k"&"]]take/last t t]

```

Try it online!

This is awfully long and I'll try to golf it at least a bit. Too bad Red doesn't have a handy `join` function...

# Answer
> 1 votes
# , ~~162~~ ~~157~~ 151 bytes

```
function(s,S=substring)paste0(z<-unique(k<-S(x<-el(strsplit(s,"&")),1,y<-regexpr('=',x))),sapply(split(S(x,y+1),k),paste,collapse=',')[z],collapse='&')

```

Try it online!

*-6 bytes thanks to Dominic van Essen*

A nice single line function. Ungolfed:

```
function(s,S=substr){
pairs <- el(strsplit(s,"&"))					# split on '&' getting list of pairs
loc <- regexpr('=',pairs)					# find location of each '=' in each pair
keys <- substr(pairs,1,loc)					# get the key, including the '='
values <- substr(pairs,loc + 1,nchar(pairs))			# get the values (everything after '=')
unq_keys <- unique(keys)					# uniquify the keys. This retains the order.
split_vals <- split(values,keys)				# group the values into sublists by which key they are associated with
collapsed_values <- sapply(split_vals,paste,collapse=',')	# join each subgroup of values by ','
collapsed_values <- collapsed_values[unq_keys]			# and reorder them to match the order of the keys
paste0(unq_keys,collapsed_values,collapse='&')			# concatenate keys and values and join by '&'
}

```

# Answer
> 1 votes
# Charcoal, 42 bytes

```
≔Ｅ⪪Ｓ&⪪ι=θＷ⁻Ｅθ§κ⁰υ⊞υ§ι⁰⪫Ｅυ⁺⁺ι=⪫ＥΦθ¬⌕λι⊟λ,¦&

```

Try it online! Link is to verbose version of code. Explanation:

```
≔Ｅ⪪Ｓ&⪪ι=θ

```

Split the input on `&`s and split each token on `=`s.

```
Ｗ⁻Ｅθ§κ⁰υ⊞υ§ι⁰

```

Create a list of unique keys in order of their first appearance.

```
⪫Ｅυ⁺⁺ι=⪫ＥΦθ¬⌕λι⊟λ,¦&

```

For each key, extract and join the values with `,`, concatenate with the key and separator, and join the overall result with `&`.

---
Tags: code-golf, string, parsing
---