title: Diamond creator +

text:
# Question
Title: Diamond creator +
# Challenge :

Given an integer `n` as input. Create a diamond that is 2x the given number `n`.

# Input :

Input is integer `n` and 2 \< n ≤ 3000.

# Output :

Output will be a string and it will be in form of a diamond consisting of `+` with an addition line at the start showing `n` using `+`

# Examples :

```
D(3) :

+++
  +
 +++
+++++
+++++
 +++
  +

D(5) :

+++++
    +
   +++
  +++++
 +++++++
+++++++++
+++++++++
 +++++++
  +++++
   +++
    +

D(6) :

++++++
     +
    +++
   +++++
  +++++++
 +++++++++
+++++++++++
+++++++++++
 +++++++++
  +++++++
   +++++
    +++
     +

```

# Winning Criteria :

This is so shortest code in bytes for each programming language wins.

# Answer
# brainfuck, ~~151~~ 139 bytes

```
,[.[<]<+[>>]++++[-<++++++++>],]<[<]<<<++++++++++.>>[[>]>[-<+>]>[-<+>]>>[.>>]<<[<]<<.<<[..<<]<.>>-]>[[>]>[.>>]<<[<<]>.>>[..>>]<<,<[<]<<.>>>]

```

Try it online!

Takes input via unary, with `+`s as tally marks (allowed by the poster). Decided to rework this, as I thought the old one was a bit longer than it could be (though this one is too!).

### Old Version (151 bytes):

```
>--[>+<++++++]<[->+>.<<]++++++++[-<+<++++>>]<++>>[<<.>>-[-<+<<.>>>]<[->+<]>>>+[-<.>>+<]>+[-<+>]<<<]>>[<<<<.>>[-<+<<.>>>]<[->+<]>+>>-[-<.>>+<]>-[-<+>]<]

```

Try it online!

Takes input as the starting cell. I couldn't think of a way to leverage the first half to help with the second, so there's a loop for each of them.

### How It Works:

```
 >--[>+<++++++]  Create 43 ('+') two space to the left of n
 <[->+>.<<]      Print n '+'s while preserving n
 ++++++++[-<+<++++>>]<++  Create 32 (' ') and 10 ('\n')
                         Tape: 32 10 0 n 43 t
 >>
 [ Loop over the first half of the diamond
   <<.>>         Print a newline
   -[-<+<<.>>>]  Decrement n and print n spaces
   <[->+<]       Restore n
   >>>+[-<.>>+<] Increment t and print t '+'s
   >+[-<+>]<<<   Increment t again and restore it
]>>
[ Loop over the second half
  <<<<.>>        Print a newline
  [-<+<<.>>>]<   Print n spaces
  [->+<]>+       Restore and increment n
  >>-[-<.>>+<]   Decrement t and print t '+'s
  >-[-<+>]<      Decrement t again and restore it
]

```

And just for fun:

```
+++++++++
        >
       --[
      >+<++
     ++++]<[
    ->+>.<<]+
   +++++++[-<+
  <++++>>]<++>>
 [<<.>>-[-<+<<.>
>>]<[->+<]>>>+[-<
.>>+<]>+[-<+>]<<<
 ]>>[<<<<.>>[-<+
  <<.>>>]<[->+<
   ]>+>>-[-<.>
    >+<]>-[-<
     +>]<]++
      +++++
       +++
        +

```

Try it online!
> 36 votes

# Answer
# Canvas, 9 bytes

```
+×Ｏ｛+×］±╪

```

Try it here!

Explanation (some characters have been replaced to look monospace):

```
+×O{+×]±╪
+×         repeat "+" input times
  O        output that
   {  ]    map over 1..input
    +×       repeat "+" that many times
       ±   interpret the array as a 2D string, and reverse it
        ╪  quad-palindromize with 1 horizontal overlap and 0 vertical overlap

```
> 16 votes

# Answer
# Python 3, 95 94 75 bytes

```
def f(n):a=[' '*(n+~i)+'+'*(i-~i)for i in range(n)];return['+'*n]+a+a[::-1]

```

Try it online!

---

My first attempt at some golfing, any suggestions for improvement are welcome.

EDIT: saved 1 byte thanks to Kevin Cruijssen

EDIT: removed misunderstanding about byte count

EDIT: Saved many more bytes thanks to Jo King and user202729
> 13 votes

# Answer
# 05AB1E, 14 bytes

```
'+×sL·<'+×∊.c»

```

Try it online!

**Explanation**

```
'+×              # push "+" repeated <input> times
   sL            # push range [1 ... input]
     ·<          # multiply each element by 2 and decrement (x*2-1)
       '+×       # replace each number with the corresponding number of "+"'s
          ∊      # mirror vertically
           .c    # center
             »   # join with the "+"-row created at the start

```

Also 14 bytes: `L‚˜'+×ćs.∞∊.c»`
> 9 votes

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

```
def f(n):x=[('++'*i+'+').center(n*2)for i in range(n)];return[n*'+']+x+x[::-1]

```

Try it online!

Thanks to this Tips for golfing Python answer for informing me about the `.center` function. Returns a list of strings.
> 5 votes

# Answer
# , ~~135 110~~ 96 bytes

```
function(n){cat("+"<n,"
",sep="")
for(i in c(1:n,n:1))cat(" "<n-i,"+"<2*i-1,"
",sep="")}
"<"=rep

```

Try it online!

@JayCe with the final cut.

The `rep` function is assigned to an existing infix operator, such as `<` or `^` so that `rep("+", n)` is equivalent to `"<"("+", n)` which can be written out using `<` as an infix operator as in `"+" < n` and shortened to `"+"<n`.
> 4 votes

# Answer
# Charcoal, 15 bytes

```
Ｇ→→↙Ｎ+↓‖Ｍ↑×⊕ⅈ+‖

```

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

```
Ｇ→→↙Ｎ+

```

Print an inverted triangle of `+`s the height of the input and almost twice the width.

Move the cursor down so it lands on the additional line after the reflection.

```
‖Ｍ↑

```

Make a mirror image of the triangle.

```
×⊕ⅈ+

```

Draw the additional line using the current column to avoid having to read the input again.

Reflect the output so that the additional line points to the left.
> 3 votes

# Answer
# , ~~29~~ 22 bytes

-7 bytes thanks to Jonah!

```
' +'{~#&1,]>:[:+/~|@i:

```

Try it online!

### Original solution:

# , 29 bytes

```
'+'(,]\(}:@|."1,.])@,]\.)@$~]

```

Try it online!

## Explanation:

```
'+'$~] - generates the line at the start, which is a seed for the diamond:

   '+'$~]  3
+++

]\,]\. - finds the prefixes (]\) and suffixes (]\.) of the line, making "half" the diamond

   '+'(]\,]\.)@$~] 3
+
++
+++
+++
++
+

}:@|."1,.] - makes the other "half" of the diamond by reversing each line (|."1)
and dropping its last '+' (}:) and stitches the first half to it (,.])

 '+'(]\(}:@|."1,.])@,]\.)@$~] 3
  +
 +++
+++++
+++++
 +++
  +

, - prepends the initial line to the diamond

'+'(,]\(}:@|."1,.])@,]\.)@$~] 3
+++
  +
 +++
+++++
+++++
 +++
  +

```
> 3 votes

# Answer
# Python 3, ~~76~~ 75 bytes

```
lambda n:['+'*n]+[' '*(n+~i)+'+'*(i-~i)for i in[*range(n),*range(n)[::-1]]]

```

Try it online!
> 3 votes

# Answer
# Stax, 11 bytes

```
ñ1┌╙@↔g+┤a☻

```

Run and debug it
> 3 votes

# Answer
## QB64, 82 79 bytes

```
INPUT n
?STRING$(n,43):FOR a=1TO 2*n:d=a-(a>n)*2*(n-a):?SPC(n-d);STRING$(2*d-1,43):NEXT

```
> 3 votes

# Answer
# Scala, ~~95~~ 94 bytes

saved 1 byte(s) thanks to the comment.

---

Golfed version. Try it online!

```
def f(n:Int)={val a=(0 until n).map(i=>" "*(~i+n)+"+"*(2*i+1)).toSeq;Seq("+"*n)++a++a.reverse}

```

Ungolfed version.

```
object Main {
  def f(n: Int): Array[String] = {
    val a = (0 until n).map(i => " "*(n-1-i) + "+"*(2*i+1)).toArray
    Array("+"*n) ++ a ++ a.reverse
  }

  def main(args: Array[String]): Unit = {
    val result = f(10)
    println(result.mkString("\n"))
  }
}

```
> 3 votes

# Answer
# JavaScript (Node.js), 106 105 bytes

* thanks to @Kevin Cruijssen for reducing by 1 byte

```
n=>[...Array(n*2+1)].map((_,i)=>" ".repeat(i?i>n?i+~n:n-i:0)+"+".repeat(i?i>n?4*n-2*i+1:i*2-1:n)).join`
`

```

Try it online!

## \________________________________________________

Second approach

# JavaScript (Node.js), 105 100 99 98 bytes

* thanks to @Kevin Cruijssen for reducing by 1 byte
* thanks to @ovs for reducing by 1 byte

```
n=>[X="+"[r="repeat"](n),...x=[...X].map((_,i)=>" "[r](n+~i)+"+"[r](i-~i)),...x.reverse()].join`
`

```

Try it online!
> 2 votes

# Answer
# Haskell, ~~85~~ 82 bytes

Saved 3 bytes thanks to nimi!

```
n!c=[1..n]>>c
f n|x<-[(n-i)!" "++(i*2-1)!"+"|i<-[1..n]]=unlines$n!"+":x++reverse x

```

Try it online!
> 2 votes

# Answer
# Japt `-R`, ~~18~~ 17 bytes

```
õÈ+Y î+Ãû ê1 iUî+

```

Try it online!
> 2 votes

# Answer
# PowerShell, 55 bytes

```
param($l)'+'*$l;1..$l+$l..1|%{" "*($l-$_)+'+'*($_*2-1)}

```

Try it online!
> 2 votes

# Answer
# Python 3, 98 bytes

```
def d(s):print("+"*s);t=[("+"*i).center(2*s-1)for i in range(1,2*s,2)];print("\n".join(t+t[::-1]))

```

Try it online!

Readable version:

```
def diamond(size):
    print(size * "+")
    top = [("+" * i).center(2*size - 1) for i in range(1, 2*size, 2)]
    print("\n".join(top))
    print("\n".join(reversed(top)))

```
> 2 votes

# Answer
# 05AB1E, ~~9~~ 8 bytes

```
Dη€û.C∊»

```

Try it online! Takes input in unary with `+` as a tally mark; allowed as per OP's comment.

```
Dη€û.C∊»  # full program
       »  # join...
D         # implicit input...
       »  # and...
 η        # prefixes of...
D         # implicit input...
  €       # with each element...
   û      # concatenated with...
          # (implicit) current element in list...
   û      # reversed excluding the first character...
    .C    # with...
          # (implicit) each element...
    .C    # centered by spaces to length of longest element in this list (extra space on the left if unequal spaces)...
      ∊   # mirrored vertically...
       »  # by a newline
          # implicit output

```
> 2 votes

# Answer
# Ruby, ~~71~~ 61 bytes

```
->n{[?+*n]+(a=(1..n).map{|x|?\s*(n-x)+?+*(x+x-1)})+a.reverse}

```

Try it online!
> 1 votes

# Answer
# PHP, 103 bytes

```
for(;$i++<$argn;$s.="
".str_pad(str_pad("",$i*2-1,"+",2),$argn*2-1," ",2))echo"+";echo"$s
",strrev($s);

```

Run as pipe with \`-nR´ or try it online.
> 1 votes

# Answer
# PowerShell, 58 bytes

```
param($n)'+'*$n;1..$n+$n..1|%{" "*($n-$_)+"+"*$_+"+"*--$_}

```

Try it online!

Simply a loop-up and -down, each iterating outputting the appropriate number of spaces and then the appropriate number of plus signs. Ho-hum.
> 1 votes

# Answer
# F# (Mono), 123 bytes

```
let d n=
 let t n=String('+',n)
 let s n=t(n*2-1)
 [1..n]@[n.. -1..1]|>Seq.fold(fun a x->a+sprintf"\n%*s"(n+x-1)(s x))(t n)

```

Try it online!
> 1 votes

# Answer
# PHP 102 bytes

```
for($r=str_pad;$i++<$a;$s.="\n".$r($r("",$i*2-1,"+",2),$a*2-1," ",2))echo"+";echo"$s\n",strrev($s);

```

Ik know it can be much smaller than this ;) Greetz mangas
> 1 votes

# Answer
# Yabasic, 102 bytes

An anonymous function that takes input as a unary number with `+` tally marks and outputs to the console.

```
Input""s$
n=Len(s$)
?s$
For i=-n To n
j=Abs(i)
If i For k=2To j?" ";Next:?Mid$(s$+s$,1,2*(n-j)+1)
Next

```

Try it online!

### Alternate Version, 117 bytes

An anonymous function answer that takes input as a decimal integer and outputs to the console.

```
Input""n
For i=1To n s$=s$+"+"Next
?s$
For i=-n To n
j=Abs(i)
If i For k=2To j?" ";Next:?Mid$(s$+s$,1,2*(n-j)+1)
Next

```

Try it online!
> 1 votes

# Answer
# sed 4.2.2, 69

Score includes +1 for the `-r` option to sed.

```
h
y/1/+/
p
x
s/1\B/ /g
y/1/+/
p
:
s/ \+/+++/p
t
p
:a
s/\+\+/ /p
ta
d

```

Try it online!
> 1 votes

# Answer
# Ruby, 59 bytes

```
->i{[?+*i,b=(1..i).map{|c|' '*(i-c)+?+*(2*c-1)},b.reverse]}

```

Try it online!
> 1 votes

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

```
a=x=>{g='\n';r=(m,n)=>String.prototype.repeat.call(m,n);k='+';l=r(k,x)+g;c=d='';for(i=0;i++<x;c+=r(' ',x-i)+r(k,i)+r(k,i-1)+g,d+=r(' ',i-1)+r(k,x+1-i)+r(k,x-i)+g);console.log(l+c+d);}

```

Try it online!

Updated my answer thanks to **@JoKing**
> 1 votes

# Answer
# APL (Dyalog Unicode), 25 bytesSBCS

```
⍪∘⊖⍨c,⍨⌽1↓[2]c←↑,\⎕←⎕/'+'

```

Try it online!

Explanation:

```
⍪∘⊖⍨c,⍨⌽1↓[2]c←↑,\⎕←⎕/'+'  ⍝ Full program
                       ⎕/'+'  ⍝ Get input from user as N, replicate '+' N times
                    ⎕←        ⍝ Print above string
                  ,\           ⍝ Find all prefixes of above string, e.g. '+','++','+++' etc.
                 ↑             ⍝ Mix the above into a matrix - right-pads with spaces as needed
               c←              ⍝ Assign above matrix to 'c' for 'corner'
          1↓[2]                ⍝ Drop the first column
        ⌽                     ⍝ Reverse the resulting matrix
     c,⍨                      ⍝ Append 'c' to above - this gives us the top half
⍪∘⊖⍨                         ⍝ Take the above, flip it about the horizontal axis,
                              ⍝ and append it to itself

```
> 1 votes

# Answer
# Canvas (v8), ~~8~~ 5 bytes

```
［］↔╪∔

```

Try it here!

Takes input as unary using `+` as tally.

The other Canvas answer here uses v2.
> 1 votes

# Answer
# Vyxal `j`, 6 bytes

```
¦ʁøĊmJ

```

Try it Online!

## How?

```
¦ʁøĊmJ
¦      # Prefixes of implicit input
 ʁ     # Palindromize each
  øĊ   # Center
    m  # Mirror each
     J # Join the (implicit) input with this

```
> 1 votes

# Answer
# Japt `-R`, ~~18~~ ~~16~~ 15 bytes

```
õÈç+²Ãû ê ÕiUç+

```

Try it
> 0 votes

# Answer
# Java 11, ~~159~~ ~~155~~ ~~154~~ 153 bytes

```
n->{var r="";for(int i=n,j;i-->0;r+=i>0?"\n":"")for(j=-n;++j<n;)r+=(j<0?-j:j)<n-i?"+":" ";return"+".repeat(n)+"\n"+r+"\n"+new StringBuffer(r).reverse();}

```

-5 bytes thanks to *@ceilingcat*.

**Explanation:**

Try it online.

```
n->{                       // Method with integer parameter and String return-type
  var r="";                //  First-line String, starting empty
  for(int i=n,j;i-->0      //  Loop `i` in the range (n,0]
      ;                    //    After every iteration:
       r+=i>0?"\n":"")     //     Add a new-line, unless it's the last iteration of `i`
    for(j=-n;++j<n;)       //   Inner loop `j` in the range (-n,n]
      r+=                  //    Append the result with:
         (j<0?-j:j)        //     If the absolute value of `j`
         <n-i?             //     is smaller than the input `n` minus `i`:
              "+"          //      Append a "+"
             :             //     Else:
              " ";         //      Append a space " " instead
  return"+".repeat(n)+"\n" //  Return the input `n` amount of "+", plus a new-line,
        +r+"\n"            //  plus the result-String, plus another new-line,
        +new StringBuffer(r).reverse();}
                           //  plus the result-String again reversed

```
> 0 votes

# Answer
# Attache, 62 bytes

```
{"+"*_+lf+UnGrid!Bounce=>"+ "[Table[`>,1:_]|>~`'#Reverse|>@N]}

```

Try it online!

A lambda which takes the integer as an argument.

## Example

```
A> n := 3
3
A> Table[`>,1:n]
 false false false
  true false false
  true  true false
A> Table[`>,1:n]|>~`'#Reverse
  true  true false
  true false false
 false false false
 false false false
  true false false
  true  true false
A> Table[`>,1:n]|>~`'#Reverse|>@N
 1 1 0
 1 0 0
 0 0 0
 0 0 0
 1 0 0
 1 1 0
A> "+ "[Table[`>,1:n]|>~`'#Reverse|>@N]
 " " " " "+"
 " " "+" "+"
 "+" "+" "+"
 "+" "+" "+"
 " " "+" "+"
 " " " " "+"
A> Bounce=>"+ "[Table[`>,1:n]|>~`'#Reverse|>@N]
 " " " " "+" " " " "
 " " "+" "+" "+" " "
 "+" "+" "+" "+" "+"
 "+" "+" "+" "+" "+"
 " " "+" "+" "+" " "
 " " " " "+" " " " "
A> UnGrid!Bounce=>"+ "[Table[`>,1:n]|>~`'#Reverse|>@N]
"  +  \n +++ \n+++++\n+++++\n +++ \n  +  "
A> lf+UnGrid!Bounce=>"+ "[Table[`>,1:n]|>~`'#Reverse|>@N]
"\n  +  \n +++ \n+++++\n+++++\n +++ \n  +  "
A> "+"*n+lf+UnGrid!Bounce=>"+ "[Table[`>,1:n]|>~`'#Reverse|>@N]
"+++\n  +  \n +++ \n+++++\n+++++\n +++ \n  +  "
A> Print[_]
+++
  +
 +++
+++++
+++++
 +++
  +
["+++\n  +  \n +++ \n+++++\n+++++\n +++ \n  +  "]
A>

```
> 0 votes

# Answer
# T-SQL, 152 bytes

Per our IO rules, input is taken via pre-existing table **t** with a integer field **n**.

```
DECLARE @n INT,@ INT=1,@k INT=1SELECT @n=n FROM t
PRINT REPLICATE('+',@n)a:PRINT SPACE(@n-@)+REPLICATE('+',2*@-1)IF @=@n SET @k-=1SET @+=@k IF @>0GOTO a

```

Manual counting loop, not very "SQL-like". Formatted:

```
DECLARE @n INT,@ INT=1,@k INT=1
SELECT @n=n FROM t
PRINT REPLICATE('+',@n)
a:
    PRINT SPACE(@n-@)+REPLICATE('+',2*@-1)
    IF @=@n SET @k-=1
    SET @+=@k
IF @>0 GOTO a

```
> 0 votes

# Answer
# , 20 bytes

```
é+ÄÀñ>GMÙX2é+ÄHñÄÒ+

```

Try it online!

Hexdump:

```
00000000: e92b c4c0 adf1 3e47 4dd9 5832 e92b c448  .+....>GM.X2.+.H
00000010: f1c4 d22b                                ...+

```

Explanation:

```
é+                      " Insert a '+' character
  Ä                     " Duplicate this line
   À                   " 'arg' - 1 times...
     ñ          ñ       " Repeat the following code:
      >G                "   Indent every line
        M               "   Move to the center line
         Ù              "   Duplicate this line
          X             "   Delete the first character of it (the space)
           2é+          "   Insert two '+' characters
              Ä         "   Duplicate this new line we made
               H        "   Return to the first line
                 Ä      " After the loop is over, duplicate the top line
                  Ò+    " Replace every character on this line with a '+'

```
> 0 votes

# Answer
# Excel VBA, 89 bytes

Anonymous VBE immediate window function that takes input as a unary number with `+` tally marks from range `[A1]` (ie `[A1]="++++"`) that outputs to the VBE immediate window.

```
?[A1]:n=[Len(A1)]:For i=-n To n:i=i-(i=0):j=Abs(i):?Spc(j-1)Mid([A1&A1],1,2*(n-j)+1):Next

```

### Alternate Version, 96 bytes

Anonymous VBE immediate window function that takes input as a decimal number from range `[A1]` that outputs to the VBE immediate window.

```
?[Rept("+",A1)]:For i=[-A1]To[A1]:i=i-(i=0):[B1]=Abs(i):?Spc([B1]-1)[Rept("+",2*(A1-B1)+1)]:Next

```
> 0 votes

# Answer
# Phooey, 82 bytes

```
&.@@($c43-1)&>&1<[-1$c10@[-1$c32]&>@[-1$c43]&+2<][!$c10@[-1$c32]&+1>-2@[-1$c43]&<]

```

Try it online!

Phooey is an extended form of Foo, adding input, sane loops, and some helper functions.
> 0 votes

# Answer
# Swift, ~~218~~ 169 bytes

Sadly, I could not use `map` instead of for loops, since it timed out.

```
func r(i:Int)->String{var l="";for j in(0...i*2){for k in(0..<i*2-1){l+=j==0&&k<i||j>0&&(j>i ?j-i-1:i-j)...(j>i ?i*3-1-j:i+j-2)~=k ?"+":" "};if j<i*2{l+="\n"}};return l}

```

Prettyfied:

```
func r(i: Int) -> String {
    var l = "";

    for j in (0 ... i * 2) {
        for k in (0 ..< i * 2 - 1) {
            l += (j == 0 && k < i) ||
            (j > 0 && (j > i ? j - i - 1 : i - j) ... (j > i ? i * 3 - 1 - j : i + j - 2) ~= k) ? "+" : " "
        }

        if j < i * 2 {
            l += "\n"
        }
    }

    return l
}

```

Try it online!
> 0 votes

# Answer
# Retina, 35 bytes

```
¶<,-2`\+

\+` (\++)$
$&$%"$1++
^O`

```

Takes unary `+` as input

Try it online!
> 0 votes

# Answer
# Jelly, ~~18 17 14~~ 13 bytes

```
”+ẋṄ¹Ƥz⁶ŒBṚ;$

```

Try it online!

-1 byte thanks to Erik the Outgolfer

```
”+ẋṄ¹Ƥz⁶ŒBṚ;$
”+                  '+' literal
  ẋ                 repeat this <input> number of times: '+++'
   Ṅ                print this string + a new line
    ¹Ƥ              get the prefixes: ['+', '++', '+++']
      z             transpose and fill with...
       ⁶            space (' '). yields ['+++', ' ++', '  +']
        ŒB         palindromize each row: ['+++++', ' +++ ', '  +  ']
          Ṛ;$      reverse and append with itself.

```
> 0 votes

# Answer
# , ~~141 139 137 135~~ 126 bytes

Another approach borrowing from the other R answer to this challenge by ngm as well as this other answer from Kirill L.:

```
function(n)cat(c(g(n),format(sapply(c(1:n,n:1),function(i)g(2*i-1)),j="c",w=2*n-1)),sep="
")
g=function(x)intToUtf8(rep(43,x))

```

Try it online!

Below a fully recursive solution growing the initial line and the diamond at each step:

```
function(n)cat("
",intToUtf8(rbind(t(f(n)[c(1:n,n:1),-1]),13)),sep="")
f=function(n)"if"(n,{cat("+");rbind(cbind(32,f(n-1),32),43)},43)

```

Try it online!
> 0 votes

# Answer
# CJam, 34 bytes

```
q~:X,'+X*n{_X-~' *\2*)'+*+}%_W%+:n

```

Try it online!

Still wrapping my head around CJam, could probably be improved.
> 0 votes

# Answer
# MY-BASIC, 126 bytes

An anonymous function that takes input as a unary number with `+` tallys

```
Input"",s$
n=Len(s$)
Print s$;
For i=-n To n
j=Abs(i)
If i Then
For k=2 To j
Print" "
Next
Print Mid(s$+s$,1,2*(n-j)+1);
Next

```

Try it online!
> 0 votes

# Answer
# uBASIC, 114 bytes

```
0input"",s$:n=len(s$):?s$:fork=2ton:t$=t$+" ":nextk:fork=0-nton:f=abs(k):iffthen?mid$(t$+s$+s$,n-f+1,2*n-f)
1nextk

```

Try it online!
> 0 votes

# Answer
# C (gcc), 111 bytes

Rather than having two loops (one for \[0..i-1\] and \[i-i..0\]), I loop for 2\*i iterations and compute the offsets from 0 for the first half and from 2\*i for the last half. `printf()` takes care of the spacing!

```
f(i,j,k){char s[9999];for(memset(s,43,j=2*i+1),k=-1;printf("%*.*s\n",i+k,~k?2*k+1:i,s),--j;)k=(j>i)?2*i-j:j-1;}

```

Try it online!
> 0 votes

# Answer
# Oracle SQL, 166 bytes

```
select decode(x,1,lpad('x',n,'x'),lpad(' ',n-y,' ')||lpad('x',2*y-1,'x'))from(select level x,abs(trunc((level-2)/n)*(2*n+1)+1-level)y,n from t connect by level<2*n+2)

```

Test in SQL\*PLus (This table is used as an input `create table t(n) as select 5 from dual`)

```
SQL> set pages 0 lines 2000 feedback off
SQL> select decode(x,1,lpad('x',n,'x'),lpad(' ',n-y,' ')||lpad('x',2*y-1,'x'))
  2  from(select level x,abs(trunc((level-2)/n)*(2*n+1)+1-level)y,n from t connect by level<2*n+2)
  3  /
xxxxx
    x
   xxx
  xxxxx
 xxxxxxx
xxxxxxxxx
xxxxxxxxx
 xxxxxxx
  xxxxx
   xxx
    x

```
> 0 votes

# Answer
# C# (Visual C# Interactive Compiler), 105 bytes

```
n=>new int[2*n+1].Select((_,i)=>new String('+',i<1?n:i>n?4*n-2*i+1:2*i-1).PadLeft(i<1?0:i>n?3*n-i:n+i-1))

```

Try it online!

The idea is to create an enumerator with length equal to the number of returned lines. Iterate over the enumerator and return strings of `+` characters with varying padding dependent upon the current index in the enumeration.

```
// n is the diamond size
n=>
  // create an array to iterate over
  new int[2*n+1]
  // this version of select includes an index
  .Select((_,i)=>
    // create the diamond body
    new String('+',i<1?n:i>n?4*n-2*i+1:2*i-1)
    // pad according
    .PadLeft(i<1?0:i>n?3*n-i:n+i-1))

```
> 0 votes

# Answer
# Wolfram Language (Mathematica), 97 bytes

```
d[n_]:=Column[Row/@(Drop[Prepend[DiamondMatrix[n][[All,2;;]],Table[1,n]],{n+2}]/.{1->"+",0->""})]

```

Try it online!
> 0 votes

# Answer
# Zephyr, 241 bytes

```
input n as Integer
set s to""
for i from 1to n
set s to"+"+s
next
print s
for i from 1to n*2
set s to""
if i>n
set r to(i-n)-1
else
set r to n-i
end if
for j from 2to(n-r)*2
set s to"+"+s
next
for j from 1to r
set s to" "+s
next
print s
next

```

Try it online!

Not having a string multiplication operator really hurts here.

### Ungolfed/commented

```
# Input number
input n as Integer

# Build string of that many plusses in s
set s to ""
for i from 1 to n
  set s to s + "+"
next
# Output it
print s

# Output diamond
for i from 1 to n * 2
  # Build string for each line in s
  set s to ""
  # Set r to the number of spaces on the current line: n-1, ... , 1, 0, 0, 1, ... , n-1
  if i > n
    set r to (i - n) - 1
  else
    set r to n - i
  end if
  # Add that many spaces to s
  for j from 1 to r
    set s to s + " "
  next
  # Add (n - r) * 2 - 1 plusses to s
  for j from 2 to (n - r) * 2
    set s to s + "+"
  next
  # Output it
  print s
next

```
> 0 votes

# Answer
# Regenerate, 70 bytes

```
(\+{$~1})(
( {#3-1}! {#1-1})(\+\+$4!\+)){#1}(
( $6!)(\+{#7-2}!$4)){#1}

```

Attempt This Online!

### Explanation

For clarity, space is replaced with `_` and newline is replaced with  in the explanation.

```
(\+{$~1})

```

Group 1: Repeat `+` a number of times equal to the input.

```
(¶...){#1}

```

Group 2 generates the top half of the diamond. Repeat it (length of group 1) times. It contains groups 3 and 4.

```
(_{#3-1}!_{#1-1})

```

Group 3: Add spaces, one less than the last time we matched group 3; or, if group 3 hasn't been matched yet, one less than the length of group 1.

```
(\+\+$4!\+)

```

Group 4: Add plusses, two more than the last time we matched group 4; or, if group 4 hasn't been matched yet, a single plus.

```
(¶...){#1}

```

Group 5 generates the bottom half of the diamond. Repeat it (length of group 1) times. It contains groups 6 and 7.

```
(_$6!)

```

Group 6: Add spaces, one more than the last time we matched group 6; or, if group 6 hasn't been matched yet, none.

```
(\+{#7-2}!$4)

```

Group 7: Add plusses, two less than the last time we matched group 7; or, if group 7 hasn't been matched yet, copy the last match of group 4.
> 0 votes

---
Tags: code-golf, ascii-art, geometry
---


# Question
Title: Determine the Octet(/Duplet/18-electron) Rule
Given an atomic number in the inclusive range `[1,118]`, write the shortest program/function that outputs one of `{2,8,18}` if the element with that atomic number follows the duplet, octet, or 18-electron rule, respectively.

### Notes

* The Octet/Duplet/18-electron rule is a rule of thumb that describes how many electrons is needed for an element to completely fill their outer electron shells.
* The Duplet rule only applies to H, He, and Li (atomic numbers 1, 2, and 3)
* The 18-electron rule applies to all transition metals (21-30, 39-48, 72-80, 104-112), lanthanides (57-71), and actinides (89-103).
* The Octet rule applies to everything else (4-20, 31-38, 49-56, 81-88, 113-118).

### Test Cases

```
input => output
1 => 2
2 => 2
3 => 2
4 => 8
18 => 8
19 => 8
20 => 8
21 => 18
26 => 18
30 => 18
31 => 8
92 => 18
118 => 8

```

# Answer
# Excel, 60 bytes

```
=IFNA(8+10*ISEVEN(MATCH(A1,{4,21,31,39,49,57,81,89,113})),2)

```

Input in cell `A1`.
> 5 votes

# Answer
# Charcoal, 22 bytes

```
Ｉ⊗§”|↖⁵Z·⁰χ⦄P↑mＭρbl∨”Ｎ

```

Try it online! Link is to verbose version of code. Explanation: Most of the program is simply a compressed look-up table.

```
   ”...”    Compressed look-up table
  §         Indexed by
        Ｎ   Input as a number
 ⊗          Doubled
Ｉ           Cast to string
            Implicitly print

```
> 5 votes

# Answer
# Vyxal, ~~19~~ 18 bytes

```
»µ7!¾∷»₄τ¦>ḣ∑∷+›²d

```

Try it Online! or verify all test cases.

*-1 byte* by porting part of Jonathan Allan's Jelly answer.

```
»...»               # push compressed integer
     ₄τ             # convert to base 26
       ¦            # cumulative sum
                        this results in the list [3,20,30,38,48,56,80,88,112]
        >           # is less than input?
         ḣ          # extract head, pushes a[0] and a[1:] (a[0] == 0 iff input is less than 4)
          ∑         # sum
           ∷        # modulo 2 (this is 1 iff the 18-electron rule applies)
            +       # add
             ›      # increment
              ²     # square
               d    # double

```
> 5 votes

# Answer
# Python, ~~72 71 56~~ 55 bytes

```
lambda n:(n<4or sum(i>n for i in b"\x04\x15\x1f'19QYq")%2*5+4)*2

```

Attempt This Online!

(But the `\x04\x15\x1f` should be replaced with the actual unprintable characters)

Based off Jos Woolley's Excel answer.

*-15 thanks to dingledooper*
*-1 thanks to pan*

## Python, 66 bytes

```
lambda n:(n<4)*2+((20<n<31)+(38<n<49)+(56<n<81)+(88<n<113))*18or 8

```

Attempt This Online!
> 4 votes

# Answer
# Ruby, 42 bytes

```
->m{m>3?8+5*(2&70352637804063<<-m/2+12):2}

```

Try it online!

Unfortunately this fairly unimaginative approach works best.

Ruby rounds toward `-infinity`, so the minus sign in `-m/2` ensures that transitions occur in the right place. This expression evaluates to `-10` for both `19` and `20` input, and `-11` for both `21` and `22` input. To get the first `18` output, we take this `-11` and add `12` for an overall shift of `+1`. This gives a final answer of `8+5*(2)` which is 18. Larger numbers give negative leftshift, which Ruby interprets as positive rightshift.

the magic number can be replaced by `0x3ffc3ffc3e1f` which is the same number of bytes. If three leading zeroes are added to the hex number, `+12` can be deleted, but it's the same number of bytes.

# Ruby, 65 bytes

```
->m{n=0
" $(1:JZ".bytes{|i|n+=15<<i}
m>3?18-10*(1&n>>(m+67)/2):2}

```

Try it online!
> 4 votes

# Answer
# Jelly, 19 bytes

```
>“Þœ&08PXp“¤‘§ḂS‘²Ḥ

```

A monadic Link that accepts an integer from \\$\[1,118\]\\$ and yields the rule, \\$2\\$, \\$8\\$, or \\$18\\$.

**Try it online!**

### How?

```
>“...“¤‘§ḂS‘²Ḥ - Link: Atomic number, A   e.g. 48
 “...“¤‘       - lists of code-page indices -> [[20,30,38,48,56,80,88,112],[3]]
>              - (A) greater than? (that)      [[ 1, 1, 1, 0, 0, 0, 0,  0],[1]]
        §      - sums                          [3,1]
         Ḃ     - mod two                       [1,1]
          S    - sum                           2
           ‘   - increment                     3
            ²  - square                        9
             Ḥ - double                        18

```
> 4 votes

# Answer
# JavaScript (ES6), 42 bytes

A hash formula with a 32-bit lookup.

```
n=>n<4?2:60620415>>(-~n>>1)*223%511&1?18:8

```

Try it online!

---

# JavaScript (ES6), 47 bytes

A longer but slightly more subtle method.

```
n=>n<4?2:--n%16>="_468080"[n>>4]^n>29&n<32?18:8

```

Try it online!

### Method

This is based on the pattern that appears when the atomic numbers are arranged by groups of \\$16\\$, starting at \\$0\\$ instead of \\$1\\$. We use the following condition to determine whether it's *18-electon* or *octet*:

$$(n \bmod 16)\ge T\_{\lfloor n/16 \rfloor}$$

There's unfortunately an exception for \\$n=30\\$ and \\$n=31\\$ (atomic numbers \\$31\\$ and \\$32\\$) which is not golfed very efficiently, making this method overall less competitive than the one using a more basic hash.

In the diagram below, we use `+`, `.` and `x` for *duplet*, *octet* and *18-electron* respectively.

```
   | 0 1 2 3 4 5 6 7 8 9 A B C D E F
---+--------------------------------
00 | + + + . . . . . . . . . . . . .
10 | . . . . x x x x x x x x x x . .
20 | . . . . . . x x x x x x x x x x
30 | . . . . . . . . x x x x x x x x
40 | x x x x x x x x x x x x x x x x
50 | . . . . . . . . x x x x x x x x
60 | x x x x x x x x x x x x x x x x
70 | . . . . . .

```
> 3 votes

# Answer
# 05AB1E, 20 bytes

```
49Þ1š•N‚Ÿи––•₂вÅΓ·Iè

```

Port of *@Neil*'s Charcoal answer.

Try it online or verify all test cases.

A port of *@AndrovT*'s Vyxal answer is **20 bytes** as well:

```
•¶sWü„•₂вηO›ćsOÉ6«*Ì

```

Try it online or verify all test cases.

Make sure to upvote both *@Neil*'s and *@AndrovT*'s answers as well!

**Explanation:**

```
49              # Push 49
  Þ             # Cycle it indefinitely: [4,9,4,9,4,9,...]
   1š           # Prepend a 1: [1,4,9,4,9,4,9,...]
     •N‚Ÿи––•   # Push compressed integer 25350987139094
       ₂в       # Convert it to base-26 as list: [4,17,10,8,10,8,24,8,24,6]
         ÅΓ     # Run-length decode the two lists: [1,1,1,1,4,4,4,...]
           ·    # Double each: [2,2,2,2,8,8,8,...]
            Iè  # (0-based) index the input into it
                # (after which the result is output implicitly)

•¶sWü„•         # Push compressed integer 766210902312
  ₂в            # Convert it to base-26 as list: [3,17,10,8,10,8,24,8,24]
    η           # Get all prefixed of this list: [[3],[3,17],[3,17,10],...]
     O          # Sum each inner prefix: [3,20,30,38,48,56,80,88,112]
      ›         # Check if the (implicit) input-integer is larger than the values
       ć        # Extract head; push first item and remainder-list separately
        s       # Swap so the remainder-list is at the top of the stack
         O      # Sum it
          É     # Modulo-2 (with an is_odd check)
           6«   # Append a 6 to this 0 or 1
             *  # Multiply it to the extracted head
              Ì # Increase it by 2
                # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*) to understand why `•N‚Ÿи––•` is `25350987139094`; `•N‚Ÿи––•₂в` is `[4,17,10,8,10,8,24,8,24,6]`; `•¶sWü„•` is `766210902312`; and `•¶sWü„•₂в` is `[3,17,10,8,10,8,24,8,24]`.
> 3 votes

# Answer
# C (GCC), 81 76 71 68 57 bytes

*thanks neil for -11 bytes*

```
f(x){x=x<4?2:0x1fffffe01fffffe01ff807fell<<20>>x&1?18:8;}

```

Attempt This Online!

Return 2 for \<= 3, otherwise lookup the value in the 64-bit constants, where 0 is the 18 rule and 1 is the 8 rule.
> 2 votes

# Answer
# Pip, ~~61 47~~ 41 bytes

```
Ia<4P2EL{P%#({\a>a}FI(A*"&08PXp"))*t+8}

```

Attempt This Online!

*-20 thanks to @DLosc*

#### Explanation

```
Ia<4        # if the input is less than 4:
    P2      #  print 2
      EL{   # else:
P           #  print the following:
 %#(        #   length mod 2 of:
    {\a>a}  #    is the input greater than this number?
FI(A*"...") #    filter the list [20,30,38,48,56,80,88,112] by the above
)*t+8       #   times 10 plus 8
     }      # enf if

```

Old:

```
Ia<4        # if the input is less than 4:
    P2      #  print 2
      EL{   # else:
Fi       {  #  for i in ...
  A*"..."   #  the ASCII code points of the string
            #     [20,30,38,48,56,80,88,112]:
l:lAE       #   append the following to l
     (a>i)  #   is the input greater than i?
          } #  end for
P           #  print ...
  (1Nl)     #  ... the count of 1s in l ...
 %          #  ... mod 2 ...
*t+8        #  ... times 10 plus 8
     }      # end if

```
> 2 votes

# Answer
# Scala, 103 bytes

Modified from @The Thonnu's answer.

---

Golfed version. Try it online!

```
def f(n:Int)=if(n<4)2 else(Seq[Byte](0x04,0x15,0x1f,0x27,0x31,0x39,0x51,0x59,0x71).count(_ >n)%2*5+4)*2

```

Ungolfed version.

```
object PythonToScala {
  def f(n: Int): Int = {
    val b = Array[Byte](0x04, 0x15, 0x1f, 0x27, 0x31, 0x39, 0x51, 0x59, 0x71)
    if (n < 4) 2
    else (b.count(_ > n) % 2 * 5 + 4) * 2
  }

  def main(args: Array[String]): Unit = {
    for (i <- 1 to 118) {
      println(s"$i  \t-->\t  ${f(i)}")
    }
  }
}

```
> 1 votes

---
Tags: code-golf, integer, chemistry
---


title: Is the word coprime?

text:
# Question
Title: Is the word coprime?
Given a word, treat every letter as its number in English alphabet (so `a` becomes 1, `b` becomes 2, `z` becomes 26 and so on), and check if all of them, including duplicates, are pairwise coprime.

The input is exactly one word of lowercase English letters. The output is the fact if the word is coprime: any truthy/falsey values, but only two variants of them. Standard loopholes are forbidden.

Test cases:

* `man`: `True`
* `day`: `True` (thanks to Ørjan Johansen)
* `led`: `False` (`l=12` and `d=4` have `gcd=4`)
* `mana`: `True` (though `a` occurs multiple times, 1 and 1 are coprimes)
* `mom`: `False` (`gcd(13,13)=13)`)
* `of`: `False` (thanks to xnor; though `15∤6`, `gcd(15,6)=3`)
* `a`: `True` (if no pairs of letters, treat the word as coprime too)

This is a , so the shortest code in bytes wins!

# Answer
# Wolfram Language (Mathematica), 36 bytes

```
CoprimeQ@@LetterNumber@Characters@#&

```

Try it online!

---

# Wolfram Language (Mathematica), 33 bytes

* Thanks to Misha Lavrov for this three bytes shorter version.

```
CoprimeQ@@(ToCharacterCode@#-96)&
```

Try it online!
> 13 votes

# Answer
# Jelly, 10 bytes

```
ØaiⱮgþ`P$Ƒ

```

Try it online!

### How it works

```
ØaiⱮgþ`P$Ƒ  Main link. Argument: s (string)

Øa          Yield "abc...xyz".
  iⱮ        Find the 1-based index of each c of s in "abc...xyz".
        $Ƒ  Call the monadic chain to the left.
            Yield 1 if the result is equal to the argument, 0 if not.
    gþ`       Take the GCDs of all pairs of indices, yielding a matrix.
       P      Take the columnwise product.
            For coprimes, the column corresponding to each index will contain the
            index itself (GCD with itself) and several 1's (GCD with other indices),
            so the product is equal to the index.

```
> 8 votes

# Answer
# Haskell, 48 bytes

```
((==).product<*>foldr1 lcm).map((-96+).fromEnum)

```

Try it online!

Very straightforward: converts the string to a list of numbers and then checks whether the product is equal to the LCM.
> 7 votes

# Answer
# Python 2 - ~~122~~ 118 bytes

*-4 bytes thanks to @JonathanAllan*

This is honestly terrible, but I've spent way too long to not post this.

```
from fractions import*
def f(n):r=reduce;n=[ord(i)-96for i in n];return r(lambda x,y:x*y/gcd(x,y),n)==r(int.__mul__,n)

```

Try it Online
> 6 votes

# Answer
# Pyth, 9 bytes

```
{Ism{PhxG

```

Test suite

Explanation:
```
{Ism{PhxG   | Full code
{Ism{PhxGdQ | With implicit variables filled
------------+------------------------------------------
   m      Q | For each char d in the input:
    {P      |  list the unique prime factors of
      hx d  |  the 1-based index of d in
        G   |  the lowercase alphabet
  s         | Group all prime factors into one list
{I          | Output whether the list has no duplicates

```

did Pyth just outgolf Jelly?
> 6 votes

# Answer
# 05AB1E, 11 bytes

```
Ç96-2.Æ€¿PΘ

```

Try it online!

**Explanation**

```
Ç96-         # convert to character codes and subtract 96
    2.Æ      # get all combinations of size 2
       €¿    # gcd of each pair
         P   # product of gcds
          Θ  # is true

```
> 5 votes

# Answer
# Brachylog, 11 bytes

```
ạ{-₉₆ḋd}ᵐc≠

```

Try it online!

## Explanation

```
ạ{-₉₆ḋd}ᵐc≠
ạ              Split the input into its character codes
 {     }ᵐ      For each one
  -₉₆          Subtract 96 (a -> 1, b -> 2 etc.)
     ḋd        And find the unique (d) prime factors (ḋ)
         c     Combine them into one list
          ≠    And assert they are all different

```
> 5 votes

# Answer
# Perl 6, ~~34~~ 32 bytes

*-2 bytes thanks to nwellnhof*

```
{[lcm](@_)==[*] @_}o{.ords X-96}

```

Try it online!

An anonymous codeblock that takes a string and returns True or False. If the lowest common multiple of the letters is equal to the product of the letters than they share no common divisors.

### Explanation:

```
                     {.ords X-96}  # Convert the letters to a list of numbers
 {                 }o              # Pass result to the next codeblock
  [lcm](@_)           # The list reduced by the lcm
           ==         # Is equal to?
             [*] @_   # The list reduced by multiplication

```
> 4 votes

# Answer
# Python 2, ~~77~~ ~~68~~ 64 bytes

```
lambda a:all(sum(ord(v)%96%i<1for v in a)<2for i in range(2,26))

```

Try it online!

Basically, (some pair in the input is not co-prime) if and only if (there is a number i \> 1 which divides more than one of the inputs).
> 4 votes

# Answer
# Python 3, ~~61~~ 59 bytes

Using python bytes as argument:

```
lambda s:all(sum(c%96%x<1for c in s)<2for x in range(2,24))

```

The last divisor to check is 23, the largest prime below 26.

Try it online!

Thanks to @Dennis for saving two bytes.
> 4 votes

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

```
f=(s,v=23)=>n=v<2||f(s,v-1)&&Buffer(s).every(c=>c%32%v||n--)

```

Try it online!
> 4 votes

# Answer
# Jelly, 11 bytes

```
ŒcO_96g/€ỊẠ

```

Try it online!

* Thanks to Dennis for NOTing my booleans

---

```
ŒcO_96g/€ỊẠ
Œc           All pairs of characters without replacement
  O          Code point of each character
   _96       Subtract 96. a->1, b->2, etc.
        €    For each pair:
      g/       Get the greatest common denominator
         Ị   abs(z)<=1? If they are all 1 then this will give a list of 1s
          Ạ  "All". Gives 1 if they are coprime, 0 if not.

```
> 3 votes

# Answer
# J, 36 bytes

```
[:(1 =[:*/-.@=@i.@##&,+./~)_96+a.&i.

```

## Ungolfed

```
[: (1 = [: */ -.@=@i.@# #&, +./~) _96 + a.&i.

```

## Explanation

```
[: (                            ) _96 + a.&i.  NB. apply fn in parens to result of right
                                  _96 + a.&i.  NB. index within J's ascii alphabet, minus 96.
                                               NB. gives index within english alphabet
   (1 =                         )              NB. does 1 equal...
   (    [: */                   )              NB. the product of...
   (                    #&,     )              NB. Flatten the left and right args, and then copy
   (                        +./~)              NB. right arg = a table of cross product GCDs
   (          -.@=@i.@#         )              NB. the complement of the identity matrix.
                                               NB. this removes the diagonal.

```

Try it online!
> 3 votes

# Answer
# MATL, 10 bytes

```
96-YF&fdA&

```

Outputs `1` for coprime, `0` otherwise.

Try it online! Or verify all test cases.

### Explanation

Consider input `'man'` for example.

```
96-  % Implicit input: string. Subtract 96 from (the codepoint of) each element
     % STACK: [13 1 14]
YF   % Exponents of prime factoriation. Each number produces a row in the result
     % STACK: [0 0 0 0 0 1;
               0 0 0 0 0 0;
               1 0 0 1 0 0]
&f   % Two-output find: pushes row and column indices of nonzeros
     % STACK: [3; 3; 1], [1; 4; 6]
d    % Consecutive differences
     % STACK: [3; 3; 1], [3; 2]
A    % All: gives true if the array doesn't contain zeros
     % STACK: [3; 3; 1], 1
&    % Alternative in/out specification: the next function, which is implicit
     % display, will only take 1 input. So only the top of the stack is shown

```
> 3 votes

# Answer
# Markov algorithm, as interpreted by eMain (~~474~~ ~~484~~ 463 bytes, ~~76~~ ~~78~~ 76 rules)

```
a->
d->b
f->bc
h->b
i->c
j->be
l->bc
n->bg
o->ce
p->b
q->q
r->bc
t->be
u->cg
v->bk
x->bc
y->e
z->bm
cb->bc
eb->be
gb->bg
kb->bk
mb->bm
qb->bq
sb->bs
wb->bw
ec->ce
gc->cg
kc->ck
mc->cm
qc->cq
sc->cs
wc->cw
ge->eg
ke->ek
me->em
qe->eq
se->es
we->ew
kg->gk
mg->gm
qg->gq
sg->gs
wg->gw
mk->km
qk->kq
sk->ks
wk->kw
qm->mq
sm->ms
wm->mw
sq->qs
wq->qw
ws->sw
bb->F
cc->F
ee->F
gg->F
kk->F
mm->F
qq->F
ss->F
ww->F
b->
c->
e->
g->
k->
m->
q->
s->
w->
FF->F
TF->F
!->.
->!T

```

The first 17 rules factor the "composite letters" into their "prime letter" factors, ignoring multiplicity. (E.g., `t` becomes `be` because 20 factors as a product of a power of 2 and a power of 5.)

The next 36 rules (such as `cb->bc`) sort the resulting prime factors.

The next 9 rules (such as `bb->F`) replace a repeated prime factor by `F`, then 9 more rules (such as `b->`) get rid of the remaining single letters.

At this point, we either have an empty string, or a string of one or more `F`s, and the last rule `->!T` adds a `!T` at the beginning. Then the rules `FF->F` and `TF->F` simplify the result to either `!T` or `!F`. At this point, the `!->.` rule applies, telling us to get rid of `!` and halt: returning `T` for a coprime word, and `F` otherwise.

(Thanks to bodqhrohro for pointing out a bug in the earlier version that caused this code to give an empty string on input `a`.)
> 3 votes

# Answer
# Python 3, ~~90~~ 89 bytes

*-1 byte by numbermaniac*

```
f=lambda q,*s:s==()or all(math.gcd(ord(q)-96,ord(w)-96)<2for w in s)and f(*s)
import math

```

Try it online!

Use as `f(*'man')`.
> 2 votes

# Answer
# Retina 0.8.2, 45 bytes

```

;
{`\w
#$&
}T`l`_l
M`;(##+)\1*;(#*;)*\1+;
^0

```

Try it online! Explanation:

```

;

```

Insert separators between each letter and at the start and end.

```
{`\w
#$&

```

Prepend a `#` to each letter.

```
}T`l`_l

```

Move each letter 1 back in the alphabet, deleting the `a`s. Then repeat the above operations until all the letters have been deleted. This converts each letter to its 1-based alphabet index in unary.

```
M`;(##+)\1*;(#*;)*\1+;

```

Test whether any two values share a common factor greater than 1. (This can find more than one pair of letters with a common factor, e.g. in the word `yearling`.)

```
^0

```

Check that no common factors were found.
> 2 votes

# Answer
# R + pracma library, 75 bytes

`function(w){s=utf8ToInt(w)-96;all(apply(outer(s,s,pracma::gcd),1,prod)==s)}`

I'm using the `gcd` function in the `pracma` library as to my knowledge R does not have a built-in for that. I'm using the approach of comparing the product of the gcds to the numbers themselves.

## 65 bytes (credit: @J.Doe)

`function(w)prod(outer(s<-utf8ToInt(w)-96,s,pracma::gcd))==prod(s)`
> 2 votes

# Answer
# Japt, 14 bytes

```
;à2 e_®nR+CÃrj

```

Try it online!

Takes input as an array of characters.

### How it works

```
;à2 e_m_nR+C} rj
;                 Use alternative predefined variables (in this case, C = "a-z")
 à2               Get all pairs
    e_            Does all pairs satisfy that...
      m_            when the character pair is mapped over...
        nR+C}         conversion from "a-z" to [1..26]
              rj    then the two numbers are coprime?

```
> 1 votes

# Answer
# Ruby, 56 bytes

```
->s{s.bytes.combination(2).all?{|a,b|2>(a-96).gcd(a-b)}}

```

Try it online!
> 1 votes

# Answer
# Japt, 13 bytes

Takes input as a character array.

```
®c uHÃà2 e_rj

```

Try it or verify all test cases
> 1 votes

# Answer
# Java 10, 86 bytes

```
a->{var r=1>0;for(int i=1,s=0;++i<24;r&=s<2,s=0)for(var c:a)s+=c%96%i<1?1:0;return r;}

```

Port of *@Vincent*'s Python 3 answer.

Try it online.

**Explanation:**

```
a->{                 // Method with character-array parameter and boolean return-type
  var r=1>0;         //  Result-boolean, starting at true
  for(int s=0,       //  Sum integer, starting at 0
      i=1;++i<24     //  Loop `i` in the range (1, 24)
      ;              //    After every iteration:
       r&=s<2,       //     If the sum is >= 2: change the result to false
       s=0)          //     And reset the sum to 0
     for(var c:a)    //   Inner loop over the input-characters
       s+=c%96%i<1?  //    If the current character modulo-96 is divisible by `i`
           1         //     Increase the sum by 1
          :          //    Else
           0;        //     Leave the sum the same
  return r;}         //  Return the result-boolean

```
> 1 votes

# Answer
# Pyt, ~~23~~ 18 bytes

```
ą1Ĩ6²-⁺ϼƑ⁻ž⁺ĐỤŁ⇹Ł=

```

Try it online!

```
ą                     implicit input (string); convert to array of characters
 1Ĩ6²-⁺               use bug in arbitrary-base radix interpretation code to
                      convert lowercase letters to integers
       ϼ              get unique prime factors for each number
        Ƒ             flatten array
         ⁻ž⁺          remove all 1s
            ĐỤŁ⇹Ł=    is the resulting list the same length as the list of its
                      unique elements?; implicit print

```

#### Original Approach (23 bytes)

```
ą1Ĩ6²-⁺ĐĐɐǤƑ⁻⇹ŁřĐɐ≠Ƒ*↑¬

```

Try it online!

```
ą                              implicit input (string); convert to array of characters
 1Ĩ6²-⁺                        abuses bug in arbitrary-base radix interpretation code to
                               convert lowercase letters to integers
       Đ                       duplicate top of stack
        ĐɐǤ                    get all GCD pairs
           Ƒ⁻                  flatten array, and decrement each element
             ⇹                 swap top two items on stack
              ŁřĐɐ≠Ƒ           creates matrix of all 1s except for the main diagonal,
                               which contains only 0s; then flattens that array
                    *↑¬        multiplies element-wise the two arrays, gets the max, and
                               logically negates that value

```

Outputs "True" if coprime, "False" if not
> 1 votes

# Answer
# Vyxal, 9 bytes

```
øA2ḋvġΠċ¬

```

Try it Online (with test cases)

```
øA        # convert letters to index in alphabet
  2ḋ      # get all combinations of length 2
    vġ    # get the gcd of each
      Π   # get the product of this list
       ċ  # inequality to 1
        ¬ # logical not

```

Probably golfable.
> 1 votes

# Answer
# q, 121 111 bytes

```
{$[1=count x;1b;1b=distinct{r:{l:{$[0~y;:x;.z.s[y;x mod y]]}[y;]'[x];2>count l where l<>1}[x;]'[x]}[1+.Q.a?x]]}

```
> 0 votes

# Answer
# JavaScript (Node.js), ~~87~~ 82 bytes

```
a=>!/\b(11+)\1* (1+ )*\1+\b/.exec(Buffer(a).map(x=>w+=" ".padEnd(x-95,1),w="")&&w)

```

Try it online!

### Original approach (87B)

```
a=>!(b=Buffer(a)).some((x,i)=>b.some((y,j)=>i-j&&(g=(p,q)=>q?g(q,p%q):p)(x-96,y-96)>1))

```

Try it online!
> 0 votes

# Answer
# Stax, 16 bytes

```
è'B╕i4à!ùà╫æor4Z

```

Run and debug it

**Explanation**

```
2S{M{$e96-mm{E:!m|A     #Full program, unpacked, implicit input
2S                      #Generate all combinations of size 2
  {       m             #Map for each element
   M                    #Split into size of 1 element
    {       m           #Map for each element
     $e                 #Convert to number
       96-              #Subtract 96
           {    m       #Map for each element
            E:!         #Explode array onto stack, are they coprime
                 |A     #Are all elements of array truthy

```

Outputs 1 for True, 0 For false.

There is probably a better way to do the converting to number part, but it works.
> 0 votes

# Answer
# APL(NARS), 16 chars, 32 bytes

```
{(×/p)=∧/p←⎕a⍳⍵}

```

This use method other used that LCM()=×/, it is fast but overflow if input array is enough long; other alternative solutions a little slower:

```
{1=×/y∨y÷⍨×/y←⎕a⍳⍵}
{1=≢,⍵:1⋄1=×/{(2⌷⍵)∨1⌷⍵}¨{x←97-⍨⎕AV⍳⍵⋄(,x∘.,x)∼⍦x,¨x}⍵}

```

this below it seems 10 times faster(or+) than just above functions

```
∇r←h m;i;j;k;v
   r←i←1⋄k←≢v←97-⍨⎕AV⍳m
A: →F×⍳i>k⋄j←i+1⋄→C
B:   →E×⍳1≠(j⌷v)∨i⌷v⋄j←j+1
C:   →B×⍳j≤k
D: i←i+1⋄→A
E: r←0
F:
∇

```

i prefer this last because it is easier, faster, trusted (becaise less overflow possiblity), easier to write, and how it has to be (even if it has some bytes more...)
> 0 votes

# Answer
# Thunno, \\$ 13 \log\_{256}(96) \approx \\$ 10.70 bytes

```
O96-2zQ.AgP1=

```

Attempt This Online!

Port of Emigna's 05AB1E answer.

#### Explanation

```
O96-2zQ.AgP1=  # Implicit input
O              # Ordinal of each character in the input
 96-           # Subtract 96 from each
    2zQ        # Combinations of length 2
       .Ag     # GCD of each pair
          P    # Product of this list
           1=  # Equals 1?
               # Implicit output

```
> 0 votes

---
Tags: code-golf, decision-problem, number-theory, primes
---


title: Add two real numbers ... probably

text:
# Question
Title: Add two real numbers ... probably
The problem statement here is pretty simple, take two real numbers on the range \[0,1) as input and output their sum, with probability 1.

The catch here is that there are a lot of real numbers. There are in fact so many real numbers that it is impossible to fit all of them into any finite data type. As such, any way to input real numbers has to be potentially infinite, and any algorithm that handles arbitrary real numbers cannot consume all of the input.

For this challenge you will input (and output) real numbers as lazy sequence (e.g. stream, generator, lazy list, function) of bits, representing their binary expansion. You can assume that the input will be normalized and will not end in an infinite repetition of `1`.

Even with this special input format it isn't possible to add any two real numbers. Any potential algorithm can be tricked into an infinite loop.

So instead we are going to settle for *almost* working. To "work" on a pair of inputs your program needs to be able to output any bit of the output in finite time. For example, if you output a generator I should be able to read to the 5th bit without the program getting stuck in a loop. Your answer needs to work with probability 1, meaning that the measure of the set of inputs which your program does work needs to have measure 1. The behavior for which the program doesn't work is undefined it can loop forever give an incorrect answer etc. so long as these cases themselves have measure zero.

This is the goal is to minimize the size of your source code as measured in bytes.

## Examples

Here are some examples of rational numbers being added. You do not need to support any of these specific numbers.

```
1/3  = 0.01010101010101010...
+
1/5  = 0.00110011001100110...
=
8/15 = 0.10001000100010001...

```

```
3/8  = 0.011000000000000000...
+
3/16 = 0.001100000000000000...
=
9/16 = 0.100100000000000000...

```

```
17/95    = 0.001011011100111101111110101001110001001011011100111101111110101...
+
3/13     = 0.001110110001001110110001001110110001001110110001001110110001001...
=
506/1235 = 0.011010001110001100101111111000100010011010001110001100101111111...

```

# Answer
# Python, 75 bytes

```
def f(*I,n=0):
 for a,b in zip(*I):yield from[a,*n*[1^a]][:-(n:=1+n*(a^b))]

```

Attempt This Online!

Takes two iterables and returns one.

## How?

Count bits that differ between the inputs without outputting anything until an equal bit is encountered. Output this bit followed by counter times its complement. Reset counter and start over.
> 14 votes

# Answer
# Rust, ~~222~~ 199 bytes

```
|a:Box<dyn Iterator<Item=usize>>,b:Box<dyn Iterator<Item=usize>>|a.zip(b).scan(0,|z,(e,f)|Some(if e==f{let q=*z;*z=0;(e..=e).chain((1-e..2-e).cycle().take(q)).collect()}else{*z+=1;vec![]})).flatten()

```

Attempt This Online!

Just the type declaration of a iterator is already longer than some of the answers here :(
> 5 votes

# Answer
# Javascript, 103 104 105 bytes

```
function*g(a){for(;;){for(i=0;(A=a.next().value)!=a.next().value;)i++;yield*[A,...Array(i).fill(+!A)]}}

```

More nicely formatted:

```
function*g(a){
    for(;;){
        for(i=0;(A=a.next().value)!=a.next().value;) i++;
        yield A;
        yield* Array(i).fill(+!A)
    }
}

```

Expects a generator function which yields the bits of the numbers to be added, interleaved.
> 4 votes

# Answer
# Charcoal, 21 bytes

```
ＦＮ≔⁺ＮＮθＮηＷ⁻ηＮＮηＩ﹪⁺θη²

```

Try it online! Link is to verbose version of code. Takes input as `n` (1-indexed) and in interactive mode will prompt for interleaved input bits until it knows what value the `n`th output bit is but on TIO you just have to provide enough bits (if there aren't enough you'll see a prompt but the program will just halt). Explanation:

```
ＦＮ≔⁺ＮＮθ

```

Input `n` pairs of bits but only keep the sum of the last pair.

```
ＮηＷ⁻ηＮＮη

```

Input further pairs of bits until two match.

```
Ｉ﹪⁺θη²

```

Add the matching bit to the sum from earlier and reduce modulo `2`.
> 4 votes

# Answer
# , ~~62~~ 60 bytes

*Edit: -2 bytes thanks to pajonk*

```
{t=0
\(x,y){u=t
t<<-`if`(x-y,t+1,0)
if(x==y)c(x,rep(!x,u))}}

```

Attempt This Online!

Port of loopy walt's Python approach.

Function that accepts sequential pairs of bits from the two numbers to be added as input to successive calls, and gives output when it can, otherwise outputs nothing. So the full output is the concatenated output of successive calls.
Input corresponds to the bits *after* the binary point, output begins with a single bit *before* the binary point, followed by all bits *after* the binary point (since we need to one more bit in case the two input numbers add-up to greater-than one).

Unfortunately my maths isn't good enough to determine when an infinite number of infinitely-small values sum to a finite value or to zero, so I'm blindly trusting that this approach is valid...
> 4 votes

---
Tags: code-golf, math, number, arithmetic, open-ended-function
---


title: Tips for golfing in Scala

text:
# Question
Title: Tips for golfing in Scala
What general tips do you have for golfing in Scala? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Scala (e.g. "remove comments" is not an answer). Please post one tip per answer.

(This is a shameless copy of ... in Python)

# Answer
> 11 votes
*disclaimer: parts of this answers are generalizations of other answers found here.*

## Use lambdas without specifying their argument types

It's allowed to submit something like this: `a=>a.size` instead of `(a:String)=>a.size`.

## Use ascii-symbols as identifiers.

These include `!%&/?+*~'-^<>|`. Because they arent't letters, they get parsed separately when they're next to letters.

Examples:

```
a=>b       //ok
%=>%        //error, parsed as one token
% => %      //ok
val% =3     //ok
&contains+  //ok
if(x)&else* //ok

```

## Use Set instead of contains

```
if (Seq(1,2,3,'A')contains x)... //wrong
if (Set(1,2,3,'A')(x))...         //right

```

This is possible because `Set[A] extends (A => Boolean)`.

## Use a curried function when you need two arguments.

```
(a,b)=>... //wrong
a=>b=>...  //right

```

## Use the `_`-syntax when possible

The rules for this are somewhat obscure, you have to play a little bit around sometimes to find the shortest way.

```
a=>a.map(b=>b.size)) //wrong
a=>a.map(_.size)     //better
_.map(_.size)        //right

```

## Use partial application

```
a=>a+1 //wrong
_+1    //better, see above
1+     //right; this treats the method + of 1 as a function

```

## Use `""+` instead of `toString`

```
a=>a.toString //wrong
a=>a+""       //right

```

## Use strings as sequences

`""` is sometimes the shortest way to create an empty sequence if you don't care about the actual type

## Use BigInt to convert numbers to and from strings

The shortest way to convert a number to a string in a base other than base 10 is through BigInt's `toString(base: Int)`method

```
Integer.toString(n,b) //wrong
BigInt(n)toString b   //right

```

If you want to convert a string to a number, use `BigInt.apply(s: String, base: Int)`

```
Integer.parseInt(n,b) //wrong
BigInt(n,b)           //right

```

Be aware that this returns a BigInt, which is useable like a number most of the times, but can't be used as an index for a sequence, for example.

## Use Seq to create sequences

```
a::b::Nil   //wrong
List(...)   //also wrong
Vector(...) //even more wrong
Seq(...)    //right
Array(...)  //also wrong, except if you need a mutable sequence

```

Use Strings for Seqences of chars:

```
Seq('a','z') //wrong
"az"         //right

```

## Make use of Stream for infinite sequences

Some challenges ask for the n-th element of an infinite sequence. Stream is the perfect candidate for this. Remember that `Stream[A] extends (Int => A)`, that is, a stream is a function from an index to the element at that index.

```
Stream.iterate(start)(x=>calculateNextElement(x))

```

## Use symbolic operators instead of their wordy counterparts

`:\` and `:/` instead of `foldRight` and `foldLeft`

```
a.foldLeft(z)(f) //wrong
(z/:a)(f)        //right
a.foldRight(z)(f) //wrong
(a:\z)(f)         //right

```

`hashCode` -\> `##`

`throw new Error()` -\> `???`

Use `->` for creating and unpacking tuples

```
(a,b)  //wrong
a->b   //right

```

## Use `&` and `|` instead of `&&` and `||`

They work the same for booleans, but will always evaluate both operands

## Alias long method as functions

```
def r(x:Double)=math.sqrt(x) //wrong
var r=math.sqrt _            //right; r is of type (Double=>Double)

```

## Know the functions in the standard library

This especially applies to the methods of collections.

Very useful methods are:

```
map
flatMap
filter
:/ and :\ (folds)
scanLeft and scanRight
sliding
grouped (only for iterators)
inits
headOption
drop and take
collect
find
zip
zipWithIndex3
distinct and/or toSet
startsWith

```

# Answer
> 14 votes
The shortest way of repeating something is with `Seq.fill`.

```
1 to 10 map(_=>println("hi!")) // Wrong!
for(i<-1 to 10)println("hi!") // Wrong!
Seq.fill(10)(println("hi!")) // Right!

```

# Answer
> 13 votes
### suspicious identifier: ?

You can use ? as identifier:

```
val l=List(1,2,3)
val? =List(1,2,3)

```

Here it doesn't save you anything, because you can't stick it to the equal sign:

```
val ?=List(1,2,3) // illegal

```

But later on, it often saves one character, since you don't need a delimiter:

```
print(?size)  // l.size needs a dot
def a(? :Int*)=(?,?tail).zipped.map(_-_)

```

However, it is often tricky to use:

```
       print(?size)
3
       print(?size-5)
<console>:12: error: Int does not take parameters
       print(?size-5)
              ^

```

# Answer
> 12 votes
## Collections

The first choice for a random collection is often *List*. In many cases you can replace it with *Seq*, which saves one character instantan. :)

Instead of

```
val l=List(1,2,3)
val s=Seq(1,2,3)

```

and, while s.head and s.tail is more elegant in usual code, `s(0)` is again one character shorter than `s.head`.

Even shorter in some cases - depending on needed functionality is a tuple:

```
val s=Seq(1,2,3)
val t=(1,2,3)

```

saving 3 characters immediately, and for accessing:

```
s(0)
t._1

```

it is the same for direct index access. But for elaborated concepts, tuples fail:

```
scala> s.map(_*2)
res55: Seq[Int] = List(2, 4, 6)

scala> t.map(_*2)
<console>:9: error: value map is not a member of (Int, Int, Int)
       t.map(_*2)
         ^

```

### update

```
def foo(s:Seq[Int])
def foo(s:Int*)

```

In parameter declaration, Int\* saves 4 characters over Seq\[Int\]. It is not equivalent, but sometimes, Int\* will do.

# Answer
> 10 votes
Use infix syntax to remove the need for `.` characters. You don't need spaces unless adjacent items are both in alphanumeric or both in operator characters (see here), and not separated by reserved characters (brackets, commas etc).

E.g.

```
List(1,2,3,4).filter(_ % 2 == 0) // change to:
List(1,2,3,4)filter(_%2==0)

```

# Answer
> 10 votes
You can usually use `map` instead of `foreach`:

```
List("a","b","c") foreach println

```

can be replaced with

```
List("a","b","c") map println

```

The only difference is the return type (`Unit` vs `List[Unit]`), which you aren't interested in anyway when using `foreach`.

# Answer
> 9 votes
Call two times the same function for initialization:

```
val n,k=readInt

```

(Seen somewhere else, but can't find it now).

# Answer
> 9 votes
The `true` and `false` literals are shorter to write as `2>1` for true and `1>2` for false

# Answer
> 7 votes
define shorter Types:

If you have multiple declarations of a type, like

```
def f(a:String,b:String,c:String)

```

it is shorter to define a type alias, and use it instead:

```
type S=String;def f(a:S,b:S,c:S)

```

Original length is 3\*6=18 Replacement-code is 8(type S=;)+6+3\*1(=new length)=17

if (n\*length \< 8+length+n), then it is an advantage.

For classes which are instantiated via a factory, we can set a shorter variable name to point to that object. Instead of:

```
val a=Array(Array(1,2),Array(3,4))

```

we can write

```
val A=Array;val a=A(A(1,2),A(3,4))

```

# Answer
> 6 votes
Rename Methods, if their name is long, and if they're used multiple times - real world example:

```
 x.replaceAll(y,z)

 type S=String; def r(x:S,y:S,z:S)=x.replaceAll(y,z)

```

Depending on the possibility to save 'S=String' at different places too, this will only be economical, if you replace at least replaceAll 3 times.

# Answer
> 6 votes
Initialize several variables at once using a tuple:

```
var(a,b,c)=("One","Two","Three") //32 characters

```

vs.

```
var a="One";var b="Two";var c="Three" //37 characters

```

# Answer
> 3 votes
# Use `lazyZip` or `zipped` (and `_`) instead of `zip` when combining lists

Using `a.zip(b)` is shorter than `a.lazyZip(b)` or `(a,b).zipped`, but if you're using `map` on it later, the latter will be shorter, since with `zip`, `map` requires function taking a single `Tuple2`, but with `lazyZip`/`zipped`, you can use a function of two parameters with underscores.

Here's an example adding together two lists:

```
val list1 = List(1, 2, 3, 4)
val list2 = List(5, 6, 7, 8)

list1.zip(list2).map(t=>t._1+t._2)   //Not good
list1.lazyZip(list2).map((a,b)=>a+b) //Okay, this is worse
list1.lazyZip(list2).map(_+_)        //But underscores make it all better
(list1,list2).zipped.map((a,b)=>a+b) //Same as with lazyZip
(list1,list2).zipped.map(_+_)        //Same as with lazyZip

```

Since `zipped` is deprecated, I'd recommend `lazyZip`, as you can also use infix syntax with it. However, in some situations, such as when you're zipping more than 2 lists, `zipped` may still be better (and it's not available on TIO, which uses an older version of Scala - you'll need Scastie).

# Answer
> 3 votes
# Treat a String as a Sequence

## Use `filter` instead of `replace` or `replaceAll`

If you need to erase characters from a String use instead of `replace` / `replaceAll`

```
x replaceAll(y,"") // 18 bytes
x replace(y,"")    // 15 bytes

```

the `filter` method:

```
x filter(y!=)      // 13 bytes

```

## Do not use `charAt`

If you need a character from a specific index from a String, do not use `charAt`:

```
x charAt 7  // 10 bytes

```

Treat the String as a sequence:

```
x(7)        // 4 bytes

```

## Use `drop` / `slice` instead of `substring`

```
x substring y    // 13 bytes
x drop y         //  8 bytes

x substring(a,b) // 16 bytes
x slice(a,b)     // 12 bytes

```

**Thanks to user for extending the answer!**

# Answer
> 3 votes
0. Use syntactic sugar and built-in functions to save bytes.

syntactic sugar, e.g. use `/: operator (fold left)`

```
val sum = numbers.foldLeft(0) { (accumulator, element) => accumulator + element }

val sum = (0 /: numbers) { (accumulator, element) => accumulator + element }

```
1. Type conversion. `231+.0` instead of `231.toDouble`. `231+""` instead of `231.toString`
2. Use `Seq` instead of `Array` or `List`
3. Rewrite type name and method name.

Rewrite the type name if the type appears **very many times**.

Use generic parameter instead of external type definition to save more bytes.

```
/*42 bytes*/
def f(a:String,b:String,c:String,d:String)

/*36 bytes*/
type S=String
def f(a:S,b:S,c:S,d:S)

/*33 bytes*/
def f[S<:String](a:S,b:S,c:S,d:S)

```

If the method appears **very many times**, please rewrite the method name.

```
implicit class V[A](val x:A)extends AnyVal{def Q=x.toSet}

```
4. Avoid `def` return type if possible. Use `def` instead of lambda function `val f=`. e.g.

use `def f(a:Int)=a+1` instead of `val f:(Int=>Int)={a:Int=>a+1}` to save bytes.
5. Avoid unnecessary braces `{} ()`
6. Simultaneously initialize multiple variables `val r,c=new StringBuilder;`
7. use `0 to x-1` instead of `0 until x`

# Answer
> 2 votes
# If you need to reuse a function, make a `def` instead of a `val`

If you absolutely need to define a function in your answer to reuse multiple times, it's usually better to define it like a method rather than using a lambda.

Consider these two pairs of functions:

```
//Recursive
def f(i:Int):Int=if(i>0)i*f(i-1)else 1
val f:Int=>Int=i=>if(i>0)i*f(i-1)else 1

//Not recursive is also shorter with def
def f(i:Int)=i+1
val g=(i:Int)=>i+1

```

# Except when using pattern matching

However, if you're pattern matching, you can use Scala's special syntax and omit `match` when assigning an anonymous function to a `val`. As you can see, it's a lot shorter:

```
//Highly efficient way to sum a list
val g:List[Int]=>Int={case h::t=>h+f(t)case _=>0}
def f(l:List[Int]):Int=l match{case h::t=>h+f(t)case _=>0}

```

# Answer
> -1 votes
You can also use  instead of using `=>` for function definitions.

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


title: Tips for golfing in MATLAB

text:
# Question
Title: Tips for golfing in MATLAB
What general tips do you have for golfing in MATLAB? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to MATLAB (e.g. "remove comments" is not an answer). Please post one tip per answer.

# Answer
> 10 votes
Something that one must know before starting to golf:

In MATLAB calculations a character behaves the same as its ascii code.

```
'abc' - 'a'  % Returns: [0 1 2]
'123' - '0'  % Returns: [1 2 3]
'“' == 8220  % Returns: 1 (logical)
'a':'e'==100 % Returns: [0 0 0 1 0] (logical)

```

# Answer
> 10 votes
Shortening property names

In MATLAB, strings identifying properties can be shortened as long as it does not result in ambiguity.

```
plot(X,'C','k') % Ambiguous property found.
plot(X,'Co','k') % Expands to Color  (black)

```

This actually won me a challenge :)

# Answer
> 6 votes
Casting as char can be done by concatenation with a char:

```
x='a'+magic(5) % Array with character codes of several letters

char(x) % The standard way
['' x] % The compact way

```

Though it only saves one char, this can be used quite frequently.

# Answer
> 5 votes
Strings are just character row vectors. This means that instead of

```
for i=numel(str)
    a=str(i)
    ...
end

```

you can simply write

```
for(a=str)
    ...
end

```

First time I used this: https://codegolf.stackexchange.com/a/58387/32352

# Answer
> 4 votes
Related, but not identical tips for Octave.

A little known and little used feature of both MATLAB and Octave is that most builtin functions can be called without parentheses, in which case they will treat whatever follows it as a string (as long as it doesn't contain spaces). If it contains spaces you need quotation marks. This can frequently be used to save a byte when using `disp`:

```
disp('Hello, World!')
disp 'Hello, World!'

```

Other, less useful examples include:

```
nnz PPCG
ans = 4

size PPCG
ans = 1  4

str2num 12
ans = 12

```

I've actually used this twice in the *"How high can you count?"*-challenge:

```
strchr sssssssssssssst t

```

is equivalent to `strchr('sssssssssssssst','t')` and returns `15`.

```
nnz nnnnnnnnnnnnnn

```

is equivalent to `nnz('nnnnnnnnnnnnnn')` and returns `14`.

Stuff like `gt r s` works too (equivalent to `'r'>'s'` or `gt('r','s')`.

# Answer
> 4 votes
# Roots of unity via discrete Fourier transform

Given a positive integer `n`, the standard way to generate the `n`-th roots of unity is

```
exp(2j*pi*(0:n-1)/n)

```

This gives the roots starting at `1` and moving in the positive angular direction. If order doesn't matter, this can be shortened to

```
exp(2j*pi*(1:n)/n)

```

---

Since `exp(2j*pi/4)` equals the imaginary unit (`j`), this can be written more compactly as follows (trick due to @flawr):

```
j.^(4*(0:n-1)/n)

```

or

```
j.^(4*(1:n)/n)

```

---

But the discrete Fourier transform provides an even shorter way (thanks to @flawr for removing two unnecessary parentheses):

```
fft(1:n==n)

```

which gives the roots starting at `1` and moving in the positive angular direction; or

```
fft(1:n==2)

```

which starts at `1` and moves in the negative angular direction.

---

Try all of the above here.

# Answer
> 3 votes
`nnz` can sometimes save you a few bytes:

* Imagine you want the sum of a logical matrix `A`. Instead of `sum(sum(A))` or `sum(A(:))`, you can use `nnz(a)` (`nnz` implitictly applies `(:)`).
* If you want to know the number of elements of an array, and you can be sure there are no zeros, instead of `numel(x)` you can use `nnz(x)`. This is applicable for instance if `x` is a string.

# Answer
> 3 votes
Iteration over vectors in matrices.

Given a set of vector as matrix, you can actually iterate over them via a single for loop like

```
for v=M
    disp(v);
end

```

while "traditionally" you probably would have done it like

```
for k=1:n
    disp(M(:,k));
end

```

I've only learned about this trick just now from @Suever in this challenge.

# Answer
> 3 votes
### 2D Convolution Kernels

This is maybe a niche topic, but apparently some people like to use convolution for various things here. \[citation needed\]

In 2D following kernels are often needed:

```
0 1 0
1 1 1
0 1 0

```

This can be achieved using

```
v=[1,2,1];v'*v>1 %logical
v=[1,0,1];1-v'*v  %as numbers

```

which is shorter than

```
[0,1,0;1,1,1;0,1,0]

```

Another kernel often used is

```
0 1 0
1 0 1
0 1 0

```

which can be shortened using

```
v=[1,-1,1];v'*v<0   % logical
[0,1,0;1,0,1;0,1,0] % naive verison

```

# Answer
> 2 votes
I quite often find myself using `meshgrid` or `ndgrid`, let's say we want to compute a mandelbrot image, then we initialize e.g.

```
[x,y]=meshgrid(-2:1e-2:1,-1:1e-2,1)

```

Now for the mandelbrot set we need another matrix `c` of the size of `x` and `y` but initialized with zeros. This can easily be done by writing:

```
c=x*0;

```

You can also initialize it to another value:

```
c=x*0+3;

```

But you can actually save some bytes by just adding another dimension in `meshgrid/ndgrid`:

```
[x,y,c]=meshgrid(-2:1e-2:1,-1:1e_2,1, 0); %or for the value 3
[x,y,c]=meshgrid(-2:1e-2:1,-1:1e_2,1, 3);

```

And you can do this as often as you want:

```
[x,y,c1,c2,c3,c4,c5]=meshgrid(-2:1e-2:1,-1:1e_2,1, 1,pi,exp(3),1e5,-3i)

```

# Answer
> 2 votes
The built-in `ones` and `zeros` are a typically a waste of space. You can achieve the same result by simply multiplying an array/matrix (of the desired size) by 0 (to get the output of `zeros`) and add 1 if you want the output of `ones`.

```
d = rand(5,2);

%// Using zeros
z = zeros(size(d));

%// Not using zeros
z = d*0;

%// Using ones
o = ones(size(d));

%// Not using ones
o = 1+d*0

```

This also works if you want to create a column or row vector of zeros or ones the size of one dimension of a matrix.

```
p = rand(5,2);

z = zeros(size(p,1), 1);
z = 0*p(:,1);

o = ones(size(p, 1), 1);
o = 1+0*p(:,1);

```

If you want to create a matrix of a specific size you could use `zeros` but you could also just assign the last element to 0 and have MATLAB fill in the rest.

```
%// This
z = zeros(2,3);

%// vs. This
z(2,3) = 0;

```

# Answer
> 1 votes
Counting the number of non zero elements in a matrix

```
zeronum(i)=nnz C;
zeronum(i)=nnz(C);
zeronum(i)=sum(C~=0);
zeronum(i)=sum(abs(C)>=eps);
zeronum(i)=numel(find(C~=0));
zeronum(i)=prod(size(find(C~=0)));

```

Horizontal replication is 3 copies, vertical replication is 2 copies

```
repmat([1,2;3,4],2,3)
kron(ones(2,3),[1,2;3,4])

```

Multiple variables, all initialized with the same data

```
[A,B,C,D]=deal([1 4;2 5;3 6]);

%%%%
A = [1 4; 2 5; 3 6];
B=A;
C=A;
D=A;

```

Declare a zero matrix of the same size as matrix A

```
X=0*A(:,1);
X=zeros(size(A));
X=zeros(size(A),'like',A);

```

# Answer
> 0 votes
## Summation of a sequence of functions

* For summing up functions f(x\_n) where n is a vector of consecutive integers, feval is adviced rather than symsum.

```
Syms x;symsum(f(x),x,1,n);
Sum(feval(@(x)f(x),1:n));

```

Notice that an elementary operation `.*` and `./` is necessary instead of pairwise binary operations `*` and `/`
* If the function can be naively written no one from either last ways is suitable.

for example if the function is `log` you can simply do: `sum(log(1:n))` , which represents:

```
Sum(f(1:n));

```

for relatively sophisticated functions as `log(n)/x^n` you can do:

```
Sum(log(1:n)./5.^(1:n))

```

and even shorter in some cases when a function is longer as `f(x)=e^x+sin(x)*log(x)/x`....

```
Sum(feval(@(y)e.^(y)+sin(y).*log(y)./y,1:n))

```

that is remarkably shorter than `sum(feval(@(y)e.^(1:n)+sin(1:n).*log(1:n)./(1:n),1:n))`

---

**Note:** This trick can be applied for other inclusive operators as `prod` or `mean`

---

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


title: Gödel encoding - Part I

text:
# Question
Title: Gödel encoding - Part I
Related but different.

Part II

Taken from the book: Marvin Minsky 1967 – Computation:
Finite and Infinite Machines, chapter 14.

### Background

As the Gödel proved, it is possible to encode with *a unique positive integer* not just any string
but any *list structure*, with any level of nesting.

Procedure of encoding \\$G(x)\\$ is defined inductively:

1. If \\$x\\$ is a number, \\$G(x) = 2^x\\$
2. If \\$x\\$ is a list \\$\[n\_0, n\_1, n\_2, n\_3, …\]\\$, \\$G(x) = 3^{G(n\_0)} \cdot 5^{G(n\_1)} \cdot 7^{G(n\_2)} \cdot 11^{G(n\_3)} \cdot...\\$
Bases are *consecutive primes*.

### Examples:

`[0] → 3`

`[[0]] →` \\$3^3 =\\$ `27`

`[1, 2, 3] →` \\$3^{2^1} \cdot 5^{2^2} \cdot 7^{2^3} = \\$ `32427005625`

`[[0, 1], 1] →` \\$3^{3^{2^0} \cdot 5^{2^1}} \cdot 5^{2^1} = \\$ `15206669692833942727992099815471532675`

### Task

Create a program that encoding (in this way) any given (possibly ragged) list to integer number.
This is `code-golf`, so the shortest code in bytes wins.

### Input

Valid non-empty list.
**UPD**
Some considerations regarding *empty lists* are given here.

You may assume:

* There are no empty sublists
* Structure is not broken (all parentheses are paired)
* List contains only non-negative integers

### Output

Positive integer obtained by the specified algorithm

### Note

Numbers can be very large, be careful! Your code *must be correct in principle*, but it is acceptable that it cannot print some number. However, all test cases are checked for TIO with Mathematica program and work correctly.

### Test cases

```
[0,0,0,0,0] → 15015
[1, 1, 1] → 11025
[[1], [1]] → 38443359375
[0, [[0]], 0] → 156462192535400390625
[[[0], 0], 0] → 128925668357571406980580744739545891609191243761536322527975268535

```

# Answer
> 10 votes
# Jelly,  ~~11 10 9~~  8 bytes

-1 thanks to Unrelated String! (Use of a dyadic chain in place of a monadic compound link avoiding the need for argument manipulation with ```.)

```
ß€Żð%¡ÆẸ

```

A monadic Link that accepts a ragged list of non-negative integers and yields its Gödel encoding.

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

### How?

```
ß€Żð%¡ÆẸ - Link: non-empty list OR number, X
     ¡   - repeat...
    %    -   ...number of times: (X) modulo (X)
                                 positive ints -> 0
                                 zero -> nan*
                                 non-empty lists -> non-empty lists*
                                 * truthy non-integers are treated by ¡ as 1
   ð     -   ...action: the dyadic chain - f(X, X):
 €       -              for each E in X:
ß        -                call this Link with X=E
  Ż      -              prefix with a zero (if X=zero we get [0])
     ÆẸ  - recompose from prime exponent list
              e.g.:
                    [0,4,0,2] -> 3^4 × 7^2 = 3969
                          [0] -> 2^0 = 1
                            n -> 2^n (non-list n treated as [n])

```

# Answer
> 5 votes
# Brachylog, 24 bytes

```
;2^₍|↰ᵐGl~lℕ₃ᵐṗᵐ≠≜;Gz^ᵐ×

```

Try it online!

Surely there are shorter ways to generate a list of primes…

Brachylog is based on SWI-Prolog and can deal with arbitrarily large integers, but this will quickly run out of memory for even simple lists.

### Explanation

```
;2^₍                       Output = 2^Input
    |                      Or (if the input is not an integer)
     ↰ᵐG                   Recursive call of this predicate for all elements of the Input; call the result G
       Gl~l                Take a list with as many elements as G
           ℕ₃ᵐṗᵐ≠≜         It must be a list of primes greater than 3 and all different (it always unifies with increasing magnitudes)
                   ;Gz     Zip with G
                      ^ᵐ   Map power
                        ×  Multiply

```

# Answer
> 5 votes
# Vyxal, `A` ~~23~~ ~~21~~ 11 bytes

@AndrovT cool result:

```
Eλ-[żǎ$vxeΠ

```

Try it Online!

Unfortunately, can't explain in detail. Hope one of Vyxal' experts helps...

My old version, maybe useful for beginners in Vyxal:

```
ƛIȧ[:L›ÞpŻ$vx¨£e|E]fΠ

```

Every input must be list of lists, so first test case should be `[[1, 1, 1]]` etc.

-2 bytes thanks @emanresu (Vyxal chat)

```
ƛ                       #Begin lambda map
 Iȧ                     #Condition for If: is it list?
     [                  #Begin If
      :L›               #If list - get length and add 1
         ÞpŻ            #Get slice of given length from infinite  list of primes
            $           #Swap
             vx         #Recursively apply to list
               ¨£e      #Zip and reduce pairs with exponentiation
                  |     #Else
                   E    #If number - two power
                    ]   #End If and lambda map,
                     fΠ #Flatten and reduce by product

```

Try it Online!

# Answer
> 5 votes
# , ~~103~~ ~~102~~ 98 bytes

*Edit: -1 byte, and then -4 more, both thanks to pajonk*

```
`?`=\(x,p=3)`if`(sum(!p%%1:p)>2,x?p+1,`if`(is.list(x),`if`(length(x),(x[-1]?p+1)*p^?el(x),1),2^x))

```

Attempt This Online!

# Answer
> 4 votes
# JavaScript (ES13), 82 bytes

Expects a ragged list of Bigints. Returns a Bigint.

```
f=(a,k=2n,t=1n)=>a.at?a.map(a=v=>(g=d=>k%d--?g(d):d)(k++)?a(v):t*=k**f(v))&&t:k**a

```

Attempt This Online!

Or 79 bytes without Bigints.

# Answer
> 3 votes
# Arturo, 66 bytes

```
f:$[x][(block? x)?[p:3∏map x=>[p^f&until->prime? p->'p+2]]->2^x]

```

Try it

```
f:$[x][                       ; a function f taking an argument x
    (block? x)?[              ; is x a block? then...
        p:3                   ; assign 3 to p
        ∏                     ; product
        map x=>[              ; map over x, assign current elt to &
            p^f&              ; p raised to the Gödel encoding of the current elt
            until->prime? p-> ; until p is prime...
                'p+2          ; add 2 to p via in-place modification
        ]                     ; end map
    ]                         ; end the 'true' part of the ternary
    ->2^x                     ; ...otherwise, if x isn't a block, take 2^x
]                             ; end function

```

# Answer
> 3 votes
# Python, 103 bytes

```
g=lambda n,k=1,m=1:m%k>n or-~g(n,k+1,m*k)
f=lambda l,p=3:l*0==0and 2**l or p**f(l[0])*f(l[1:]or 0,g(p))

```

Attempt This Online!

Method for calculating next prime is shamelessly adapted from Dennis's answer.

# Answer
> 3 votes
# PARI/GP, 118 bytes

Modified from @Dominic van Essen's answer

---

Golfed version, try it online!

```
G(x,p=3)={if(sum(i=1,p,(p%i)==0)>2,G(x,p+1),if(type(x)=="t_VEC",if(#x,p^G(x[1])*G(vector(#x-1,i,x[i+1]),p+1),1),2^x))}

```

Ungolfed version

```
G(x, p = 3) =
{
  if (sum(i = 1, p, (p % i) == 0) > 2,
    G(x, p + 1),
    if (type(x) == "t_VEC",
      if (#x,
        p^G(x[1]) * G(vector(#x - 1, i, x[i + 1]), p + 1),
        1
      ),
      2^x
    )
  )
}

print(G(0)) \\ 1
print(G(1)) \\ 2
print(G([0,0])) \\ 15
print(G([0,1])) \\ 75
print(G([0])) \\ 3
print(G([[0]])) \\ 27
print(G([0,0,0,0,0])) \\ 15015
print(G([1,2,3])) \\ 32427005625
print(G([[0,1],1])) \\ 15206669692833942727992099815471532675

```

# Answer
> 3 votes
# Julia, ~~68~~ 66 bytes

```
!x::Int=2^x
!(x,p=2)=prod(i->(while(p+=1).%(2:p-1)∋0end;p^!i),x)

```

Attempt This Online!

-2 bytes by MarcMush.

Doesn't use prime built-ins, which are not in Base anyway. Feels a bit weird to include a type annotation while golfing in a language that doesn't require it, but it looks like a decent way to disambiguate between numbers and lists.

Note that this will only produce correct output within Int64. At the expense of 5 bytes, we can add a `big(...)` wrapper to get a version that processes all test cases as desired:

## Julia, ~~73~~ 71 bytes

```
!x::Int=big(2)^x
!(x,p=2)=prod(i->(while(p+=1).%(2:p-1)∋0end;p^!i),x)

```

Attempt This Online!

# Answer
> 2 votes
# 05AB1E, ~~23~~ 19 bytes

```
o"Ddië®δ.VāØsmP"©.V

```

Also works for loose integer inputs, instead of just (ragged) lists.

Try it online or verify all test cases.

**Explanation:**

Recursive functions are always so verbose in 05AB1E.. :/

```
o            # Take 2 to the power each inner-most integer of the (implicit) input
 "..."       # Push the recursive string explained below
      ©      # Store it in variable `®`
       .V    # Evaluate and execute it as 05AB1E code
             # (after which the result is output implicitly)

D            # Duplicate the current list
 di          # If it's a single integer:
             #  (do nothing, simply keep it as is)
  ë          # Else (it's a list instead):
    δ        #  Map over each inner item:
   ® .V      #   Do a recursive call
       ā     #  Then push a list in the range [1,length] (without popping)
        Ø    #  Map index each to the 0-based prime: [3,5,7,...]
         s   #  Swap the two lists on the stack
          m  #  Take the primes to the power of the values
           P #  Take the product of this list

```

# Answer
> 2 votes
# Charcoal, 67 bytes

```
≔Ｘ²Ａθ⊞υθＦυＦΦι⁺⟦⟧κ⊞υκＦ⮌υ«≔¹η≔²ζＦι«≦⊕ζＷ¬⬤…²ζ﹪ζμ≦⊕ζ≧×Ｘζ⊟⁺⟦⁰⟧κη»⊞ιη»Ｉ⊟θ

```

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

```
≔Ｘ²Ａθ

```

Vectorised raise `2` to the power of the input.

```
⊞υθＦυＦΦι⁺⟦⟧κ⊞υκＦ⮌υ«

```

Extract all of the sublists and loop over them in reverse.

```
≔¹η≔²ζ

```

Start with a product of `1` and a last prime of `2`.

```
Ｆι«

```

Loop over the elements of the list.

```
≦⊕ζＷ¬⬤…²ζ﹪ζμ≦⊕ζ

```

Get the next prime number by trial division (1 byte shorter than Wilson's theorem).

```
≧×Ｘζ⊟⁺⟦⁰⟧κη»

```

Multiply the product by the prime power of the next list element (but if that's a list, then use its last element, as that's where we put the value on a previous loop iteration).

```
⊞ιη

```

Save the resulting value to the sublist.

```
»Ｉ⊟θ

```

Output the resulting value of the original list.

# Answer
> 2 votes
# Pyth, 23 bytes

```
L?sIb^2b*F^V.fP_Zlb3yMb

```

Try it online!

Defines an encoding function `y(b)`.

### Explanation

```
L                          # define y(b)
 ?sIb                      # if b is invariant under s: (sums for list, int for int)
     ^2b                   #   2 ^ b
                           # else:
                    yMb    #   apply y to each element of b
            .fP_Zlb3       #   generate a list of len(b) primes starting with 3
          ^V               #   vectorized exponentiation
        *F                 #   fold over multiplication

```

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

```
1##&@@(i=1;Prime@++i^#&/@#)&//@(2^#)&

```

Try it online!

```
                               (2^#)    numbers: x -> 2^x
                            //@         lists:
1##&@@(                /@#)               product of
       i=1;Prime@++i^#&                     prime(n+1)^x_n

```

# Answer
> 2 votes
# , <sup>32</sup> 30 bytes

```
*/@(p:@#\^$:&>)`(2^x:)@.(0=L.)

```

Try it online!

*-2 thanks to att*

# Answer
> 1 votes
# Factor \+ `math.primes.lists math.unicode`, 83 bytes

```
: g ( a -- n ) dup real? [ 2^ ] [ [ lprimes cdr lnth swap g ^ ] map-index Π ] if ;

```

Try it online!

# Answer
> 1 votes
# PowerShell Core, 147 bytes

```
$f={$r,$p=1,2
$args|%{do{$p++;for($u,$k=1,0;++$u-$p){$k+=!($p%$u)}}while($k)$r=$r*($b=[bigint])::Pow($p,(&($f,{$b::Pow(2,$_)})[$_-is[int]]@_))}
$r}

```

Try it online!

Fun challenge!

Recursive function that expects the input list using splatting and returns a `[bigint]`

Please ignore the inconsistent output of the array in the tests result as PowerShell has a tendency to flatten them sometime.

## Explanation

This part updates `$p` to become the next prime after `$p`

```
do{$p++;for($u,$k=1,0;++$u-$p){$k+=!($p%$u)}}while($k)

```

This part checks whether the current list item `$_` is a number or not If it is a number, we take its power of two, otherwise, we do a recursive call.

```
$r=$r*($b=[bigint])::Pow($p,(&($f,{$b::Pow(2,$_)})[$_-is[int]]@_))}

```

# Answer
> 1 votes
# Wolfram Language (Mathematica), 71 bytes

Of course, answering your own challenge is a bit ridiculous, but it is rather a supplement to not break the main post.
Thanks @PaŭloEbermann for the idea!
It seems we can account for *the empty lists*, naively but correctly, using the next encoding:

1. If \\$x\\$ is non-negative integer, \\$G(x) = 2^{x+1}\\$
2. If \\$x\\$ is an empty list, `[ ]`, \\$G(x) = 2^0 = 1\\$
3. If \\$x\\$ is a list, \\$\[n\_0, n\_1, n\_2, n\_3, …\], G(x) = 3^{G(n\_0)} \cdot 5^{G(n\_1)} \cdot 7^{G(n\_2)} \cdot 11^{G(n\_3)} \cdot...\\$

Of course, this is a purely intuitive idea without proof. But I do not see contradictions at the moment.

So here is Mathematica program that encodes *any array-like structure* (with possible empty lists) with a unique positive integer.

```
Switch[#,{},1,{__},Times@@(Prime@Range[2,Length@#+1]^#0/@#),_,2^(#+1)]&

```

Some related test cases:

```
[] → 1
[[]] → 3
[[], 1, []] → 13125
[[], [0, []], 1] → 204721573027200065553188323974609375

```

Try it online!

# Answer
> 1 votes
# PARI/GP, 51 bytes

```
f(x)=if(x'===0,2^x,prod(i=1,#x,prime(i+1)^f(x[i])))

```

Attempt This Online!

---
Tags: code-golf, number, primes, encoding, ragged-list
---