title: Jam don't add like that

text:
# Question
Title: Jam don't add like that
### Background

Jelly's arithmetic atoms vectorize automatically. In fact, **x + y** is well-defined whenever **x** and **y** are numbers or ragged arrays of numbers. Jelly's source code implements this behavior using a generic vectorizer, but for this challenge, we'll only consider addition of integers and nested integer arrays.

### Definitions

Define the depth of **x** as **0** if **x** is an integer, as **1** if it is a (possibly empty) flat array of integers, and as **n + 1** if it contains at least one element of depth **n** and no elements of depth **k \> n**.

This way, **1** has depth **0**, **\[\]** and **\[1\]** and **\[1, 1\]** have depth **1**, **\[\[\], \[\]\]** and **\[\[1\], \[1\]\]** and **\[\[1\]\]** and **\[1, \[\]\]** have depth **2**, **\[1, \[1, \[1\]\]\]** has depth **3**, etc.

The operation **x + y** is defined as follows.

1. If **x** and **y** have depth **0**, return their sum.
2. If **x** and **y** have equal but positive depths, recursively apply **+** to all items of **x** and the corresponding items of **y**.

If **x** and **y** have different lengths, append the tail of the longer array to the array of sums.

Return the result.
3. If **x**'s depth is strictly smaller than **y's** depth, recursively apply **+** to **x** and all items of **y**, and return the result.

Do the opposite if **y**'s depth is strictly smaller than **x**'s.

For example, consider the operation **\[1, \[2, 3\], \[4\]\] + \[\[\[10, 20\], \[30\], 40, 50\], 60\]**.

* The depth of the left argument is **2**, while the depth of the right argument is **3**, so we compute **\[1, \[2, 3\], \[4\]\] + \[\[10, 20\], \[30\], 40, 50\]** and **\[1, \[2, 3\], \[4\]\] + 60**.

+ **\[1, \[2, 3\], \[4\]\]** and **\[\[10, 20\], \[30\], 40, 50\]** both have depth **2**, so we compute **1 + \[10, 20\]**, **\[2, 3\] + \[30\]** and **\[4\] + 40**.

    - **1 + \[10, 20\] = \[1 + 10, 1 + 20\] = \[11, 21\]**
        - **\[2, 3\] + \[30\] = \[2 + 30, 3\] = \[32, 3\]**

        Note that **3** remains untouched, since it doesn't have a matching element.
        - **\[4\] + 40 = \[4 + 40\] = \[44\]**

    **50** doesn't have a matching element, so the result is **\[\[\[11, 21\], \[32, 3\], \[44\], 50\]\]**.
    + **\[1, \[2, 3\], \[4\]\] + 60 = \[1 + 60, \[2, 3\] + 60, \[4\] + 60\] = \[61, \[2 + 60, 3 + 60\], \[4 + 60\]\]**, resulting in **\[61, \[62, 63\], \[64\]\]**.
* The final result is **\[\[\[11, 21\], \[32, 3\], \[44\], 50\], \[61, \[62, 63\], \[64\]\]\]**.

### Task

Write a program or a function that takes two integers, two nested arrays of integers or a combination thereof as input and returns their sum, as defined above.

If your language has multiple array-like types (lists, tuples, vectors, etc.) you may choose any of them for your answer. The return type must match the argument type.

To prevent boring and unbeatable solutions, if a language has this *exact* operation as a built-in, you may not use that language.

All built-ins of all other languages are allowed. If your language of choice permits this, you may overload and/or redefine the built-in addition.

This is , so the shortest code in bytes wins.

### Test cases

```
0 + 0                           = 0
[-1, 0, -1] + [1]               = [0, 0, -1]
[] + [0]                        = [0]
[] + 0                          = []
[] + []                         = []
[[], 0] + []                    = [[], []]
[1, 2, 3] + 10                  = [11, 12, 13]
[1, 2, 3] + [10]                = [11, 2, 3]
[1, 2, 3] + [10, [20]]          = [[11, 12, 13], [21, 2, 3]]
[1, 2, 3, []] + [10, [20]]      = [11, [22], 3, []]
[1, [2, [3, [4]]]] + [10, [20]] = [[11, [21]], [[12, [22]], [13, [24]]]]

```

To generate more test cases, you can use this Jelly program.

# Answer
# Pyth, 42 bytes

```
L?sIb0heSyM+b0M?qFyMJ,GH?yGgM.tJ0+GHgLFyDJ

```

Test suite

The last 4 bytes simply run the function on the input.

```
L?sIb0heSyM+b0M?qFyMJ,GH?yGgM.tJ0+GHgLFyDJ

L?sIb0heSyM+b0
                  Define y(b), a helper function to calculate the depth.
 ?                Ternary:
  sIb             If b is invariant under the s function, which is only the case
                  if s is an int.
     0            The depth is 0.
           +b0    Add a 0 on to b. This handles the edge case where b is [].
         yM       Map each to their depth
       eS         Take the max.
      h           Add one.

M?qFyMJ,GH?yGgM.tJ0+GHgLFyDJ
M                               Define g(G, H), which calculates the Jelly +.
 ?                              Ternary:
       ,GH                      Form [G, H].
      J                         Save it to J.
    yM                          Map each to its depth.
  qF                            Check if they are equal.
          ?yG                   If so, check if the depth is nonzero.
               .tJ0             If so, transpose J, pairing each element of each
                                argument with the corresponding element of the
                                other. Pad with zeroes.
             gM                 Map each to its Jelly +.
                   +GH          If the depths are zero, return the normal sum.
                         yDJ    If the depths are different, order J by depth.
                      gLF       Apply the function which left-maps the Jelly +
                                function to the two values. The first is
                                treated as a constant, while the second varies
                                over elements over the second values.

```
> 4 votes

# Answer
# APL, 44 bytes

```
{1=≡⍺⍵:⍺+⍵⋄=/∆←|≡¨⍺⍵:⊃∇¨/↓↑⍺⍵⋄</∆:⍺∘∇¨⍵⋄⍵∇⍺}

```

APL's `+` distributes over arrays as well, but in a different enough manner that this can't really be used. However, there is a built-in depth function ().

Explanation:

* `1=≡⍺⍵:⍺+⍵`: if the depths of   are both zero (and therefore the depth of `⍺ ⍵` is 1), add them.
* `∆←|≡¨⍺⍵`: take the absolute of the depth of both  and  and store them in . ( gives a negative value if not all elements have the same depth.)
* `=/∆`: if they have the same depth:
    + `↓↑⍺⍵`: pad the shortest array with zeroes to match the longer array
    + `⊃∇¨/`: distribute the function over both arrays
* `</∆`: if the depth of  is less than that of :
    + `⍺∘∇¨⍵`: bind  and then map over
* `⍵∇⍺`: if nothing else (so  is deeper than ), swap the arguments and try again.
> 9 votes

# Answer
# Jelly, ~~24~~ 22 bytes

```
ß"+ŒḊ?çⱮç€</ɼ?,ŒḊ€©Eɗ?

```

Try it online! or see all test cases

This technically violates

> To prevent boring and unbeatable solutions, if a language has this exact operation as a built-in, you may not use that language.

However, this is by no means a boring or unbeatable solution. The only time `+` is used here is to add two flat integers. The rest of it is recursion to get to that point.

This is a full program which takes the two lists are arguments, and outputs the result.

## How it works

```
ß"+ŒḊ?çⱮç€</ɼ?,ŒḊ€©Eɗ? - Main link f(A, B). Takes A on the left and B on the right
                     ? - If:
                    ɗ  -   Condition:
              ,        -     [A, B]
               ŒḊ€     -     Depth of each
                  ©    -     (Save in register, R)
                   E   -     Both depths are equal?
                           Then:
     ?                 -     If:
   ŒḊ                  -       Condition: depth of A is non-zero
ß"                     -       Then: Run f(A, B) on each subarray in A, B
  +                    -       Else: Return A+B
                           Else:
             ?         -     If:
          </ɼ          -       Condition: depth of A is less than that of B
      çⱮ               -       Then: Over each element b of B, yield f(A, b)
        ç€             -       Else: Over each element a of A, yield f(a, B)

```

We (ab)use `ç` in order to get  to work, as `ßⱮ` will error due to a bug in setting the arity of `ß` during execution. `ç` technically calls the link above explicitly as a dyad, but in a full program with only one link, this wraps around to call the same link.
> 9 votes

# Answer
## Mathematica, 122 bytes

```
d=Depth
x_~f~y_/;d@x>d@y:=y~f~x
x_~f~y_/;d@x<d@y:=x~f~#&/@y
x_List~f~y_:=MapThread[f,{x,y}~PadRight~Automatic]
x_~f~y_=x+y

```

Defines a recursive function `f` which computes the sum. Making use of Mathematica's pattern matching, this function is made up of four separate definitions:

```
x_~f~y_/;d@x>d@y:=y~f~x

```

If the depth of `x` is greater than that of `y`, swap the arguments so that we only have to handle distribution in one direction (which we can do, since addition is commutative).

```
x_~f~y_/;d@x<d@y:=x~f~#&/@y

```

If the depth of `x` is less thann that of `y`, replace each value `#` in `y` with `f[x,#]`, which takes care of the distribution for arguments of unequal depth.

```
x_List~f~y_:=MapThread[f,{x,y}~PadRight~Automatic]

```

Otherwise, if one argument is a list (which implies that the other also is a list, since we know they have the same depth), we put both arguments in a list, pad them to the same length with `PadRight[..., Automatic]` (which simply fills up a ragged array with zeros to make it rectangular), and then use `MapThread` to apply `f` to corresponding pairs from the two lists.

And finally, the base case:

```
x_~f~y_=x+y

```

If none of the other patterns match, we must be trying to add two numbers, so we just do that.
> 6 votes

# Answer
# Haskell, 150 bytes

```
data L=S Int|V{v::[L]}
d(V z)=1+maximum(d<$>S 0:z);d _=0
S x!S y=S$x+y
x!y|d x<d y=V$(x!)<$>v y|d x>d y=y!x|1<2=V$v x#v y
(x:a)#(y:b)=x!y:a#b;a#b=a++b

```

## Explanation

The first line defines an algebraic data type `L`, which is either a `S`calar (containing an `Int`) or a `V`ector (containing a list of `L`s, accessed using a record getter `v`, which is a partial function `L → [L]`.)

The second line defines the **depth** function: the depth of a `V`ector is one plus its maximum depth. I prepend `S 0` to the values in the vector, so that `depth [] == 1 + maximum [depth (S 0)] == 1`. The depth of “anything else” (a scalar) is `0`.

The third line defines the base case for `!` (the addition function): the sum of scalars is simply a scalar.

The fifth line defines a variant of `zipWith (!)` that just picks elements from the longest list when one of them is empty.

The fourth line is split in three cases:

```
x!y | d x<d y = V$(x!)<$>v y
    | d x>d y = y!x
    | True    = V$v x#v y

```
* If the depth of `x` is strictly less than the depth of `y`, map `(x!)` over the elements of `y`. (The use of `v` is guaranteed to be valid, as `d(y) ≥ 1`.)
* If the depth of `x` is strictly greater, flip the arguments and restart.
* If their depths are equal, zip the arguments together with `(!)`. (The use of `v` is guaranteed to be valid, as the case `d(x) = d(y) = 0` was handled as a base case.)

## Test cases

```
instance Show L where
  show (S x) = show x
  show (V x) = show x

lArg = V [S 1, V [S 2, V [S 3, V [S 4]]]]
rArg = V [S 10, V [S 20]]

```

Then `show (lArg ! rArg) == "[[11,[21]],[[12,[22]],[13,[24]]]]"`.
> 6 votes

# Answer
# Java, ~~802~~ ~~794~~ ~~754~~ 746 bytes

I decided to take up @Dennis♦ for the challenge to operate on strings "as a last resort" because it was probably "too complicated". Also, in the worst language to golf on.

Arrays in the input are comma-separated, surrounded with square brackets, and without whitespace.

Full program with functions wrapped into a class and with test cases

```
import java.util.*;
List<String>p(String s){List r=new ArrayList<String>();String p="";int l=0;for(char c:s.substring(1,s.length()-1).toCharArray()){l+=c=='['?1:c==']'?-1:0;if(c==','&&l<1){r.add(p);p="";}else p+=c;}if(p!="")r.add(p);return r;}
int d(String s){int l=0;if(s.contains("[")){for(String c:p(s))l=d(c)>l?d(c):l;l++;}return l;}
String f(String x,String y){int i=0;String r="";if(d(x)<1&&d(y)<1)r+=Integer.valueOf(x)+Integer.valueOf(y);else{r="[";if(d(x)<d(y))for(String k:p(y))r+=(i++<1?"":",")+f(x,k);else if(d(x)>d(y))for(String k:p(x))r+=(i++<1?"":",")+f(k,y);else for(;i<p(x).size()||i<p(y).size();i++)r+=(i<1?"":",")+(i<p(x).size()&&i<p(y).size()?f(p(x).get(i),p(y).get(i)):i<p(x).size()?p(x).get(i):p(y).get(i));r+="]";}return r;}

```

I might port this to C++ later since it's the other language I know that doesn't support ragged arrays, since I'm ~~pretty sure~~ almost certain it'll be shorter than this answer. This was mostly a proof of concept but any golfing tips would still be appreciated!

*-31 bytes from @user902383 suggesting using a foreach over a converted character array, and then I saved a little more from rearranging the if blocks in the final part.*
> 5 votes

# Answer
# C (GCC), ~~377~~ 354 bytes

*-23 bytes thanks to @ceilingcat*

```
d(w,r,i,x)S w;{for(r=i=0;w.v&&i<w.n;r=x>r?x:r)x=d(w.v[i++]);return!!w.v+r;}s(S*z,S x,S y){int e=d(x),f=d(y);if(e-f){S X=e<f?x:y,Y=e<f?y:x;for(z->v=calloc(e=z->n=Y.n,16);e--;)s(z->v+e,X,Y.v[e]);}else if(e+f){z->v=malloc(x.n+y.n<<4);for(e=0;e<x.n|e<y.n;++e)e>=x.n|e>=y.n?z->v[e]=(e<x.n?x:y).v[e],0:s(z->v+e,x.v[e],y.v[e]);z->n=e;}else z->n=x.n+y.n,z->v=0;}

```

Attempt This Online! (footer contains main, non-golfed functions, and other useful functions)

Assumes that ragged arrays are represented with the following struct:

```
typedef struct S{
    int n;
    struct S *v;
} S;

```

where

* if `x` is an integer, `x.n` is its value, and `x.v` is set to `NULL`;
* if `x` is a ragged array, `x.n` is its length, and `x.v` is the array containing the sub-elements.

Possible improvement: write a function that computes the sum in-place instead of allocating a new ragged array.

---

Thanks to @zoomlogo for pointing to this old interesting challenge in this bounty
> 5 votes

# Answer
# Python 2.7, ~~261~~ ~~209~~ ~~202~~ ~~198~~ ~~191~~ ~~185~~ ~~197~~ 181 bytes

FGITW trivial solution

EDIT: Of course @Dennis beats it

Thanks to @LeakyNun for saving 57 bytes with tips on lambda expressions, and 2 bytes from unneeded brackets.

Thanks to @Adnan for 4 bytes due to suggestion to use `type` instead of `isinstance`

Thanks to @Lynn for 7 bytes with `-~` and `map`

Thanks to @FryAmTheEggman for `z>=[]` instead of `type`

+12 bytes to convert lambda to if else and fix a major bug

-16 bytes thanks to @Kevin Lau - not Kenny

Try it online

```
d=lambda z:z==[]or z>[]and-~max(map(d,z))
p=lambda x,y:p(y,x)if d(x)>d(y)else(x+y if d(x)<1 else[p(a,b)for a,b in zip(x,y)]+x[len(y):]+y[len(x):])if d(x)==d(y)else[p(a,x)for a in y]

```
> 4 votes

# Answer
# Python 2, ~~145~~ 136 bytes

```
d=lambda t:t>{}and-~max(map(d,t+[0]))
s=lambda x,y:s(y,x)if d(y)<d(x)else map(s,(x,[x]*len(y))[d(x)<d(y)],y)if d(y)else(x or 0)+(y or 0)

```

Test it on Ideone.

### How it works

In Python 2, all integers are less than all dictionaries, but all lists are greater. **d** recursively computes the depth of **t** by returning **0** for integers or the incremented maximum of the depths of its elements and **0**. `t+[0]` avoids special-casing the empty list.

**s** recursively computes the Jelly sum of **x** and **y**.

If **y**'s depth exceeds **x**'s, `s(y,x)` calls **s** with swapped arguments, making sure that **d(x) ≤ d(y)**.

If **y** has positive depth, `map(s,(x,[x]*len(y))[d(x)<d(y)],y)` does the following.

* If the **x**'s and **y**'s depths match, it executes `map(s,x,y)`, mapping **s** over all elements of **x** and the corresponding elements of **y**.

In the case of lists of different lengths, **map** will pass **None** as left or right argument for missing elements in the shorter list.
* If **x**'s depth is lower than **y**'s, it executes `map(s,[x]*len(y),y)`, mapping **s(x, · )** over **y**.

If **y** (and, therefore, **x**) has depth **0**, `(x or 0)+(y or 0)` replaces falsy arguments (**None** or **0**) with zeroes and returns the sum of the resulting integers.
> 3 votes

# Answer
# Scala 3, 496 bytes

Port of @Value Ink's Ruby anwer in Scala.

---

Golfed version. Attmept this online!

496 bytes, it can be golfed much more.

```
val d:Any=>Int={case l:Seq[_]=>1+l.map(d).maxOption.getOrElse(0)case _=>0}
def f(x:Any,y:Any):Any=(d(x),d(y))match{
case(a,b)if a<b=>y.asInstanceOf[Seq[_]].map(f(x,_))
case(a,b)if a>b=>x.asInstanceOf[Seq[_]].map(f(_,y))
case _=>(x,y)match{
case(x:Int,y:Int)=>x+y
case(x:Seq[_],y:Seq[_])=>
val(a,b)=(math.min(x.size,y.size),math.max(x.size,y.size))
val z=x.take(a).zip(y.take(a)).map((f _).tupled)
z++(if(x.size==b)x.takeRight(b-a)else Seq())++(if(y.size==b)y.takeRight(b-a)else Seq())
case _=>x}}

```

Ungolfed version. Attmpt this online!

```
object Main {
  val depth: Any => Int = {
    case x: List[_] => 1 + x.map(depth).maxOption.getOrElse(0)
    case _ => 0
  }

  def function(x: Any, y: Any): Any = (depth(x), depth(y)) match {
    case (dx, dy) if dx < dy => y.asInstanceOf[List[_]].map(element => function(x, element))
    case (dx, dy) if dx > dy => x.asInstanceOf[List[_]].map(element => function(element, y))
    case _ => (x, y) match {
      case (x: Int, y: Int) => x + y
      case (x: List[_], y: List[_]) =>
        val minLen = math.min(x.size, y.size)
        val maxLen = math.max(x.size, y.size)
        val zipPart = x.take(minLen).zip(y.take(minLen)).map((function _).tupled)
        val remainingPartX = if(x.size == maxLen) x.takeRight(maxLen - minLen) else List()
        val remainingPartY = if(y.size == maxLen) y.takeRight(maxLen - minLen) else List()
        zipPart ++ remainingPartX ++ remainingPartY
      case _ => x
    }
  }

  def main(args: Array[String]): Unit = {
    println(function(List(1, List(2, List(3, List(4)))), List(10, List(20))))
    println(function(List(-1, 0, 1), List(1)))
  }
}

```
> 3 votes

# Answer
## JavaScript (ES6), 152 bytes

```
f=(a,b,g=a=>a.map?1+Math.max(0,...a.map(g)):0)=>g(a)<g(b)?f(b,a):g(b)<g(a)?a.map(e=>f(e,b)):g(a)?a.length<b.length?f(b,a):a.map((e,i)=>f(e,b[i]||0)):a+b
;t=(x,y,z)=>o.textContent+=`
${JSON.stringify(x)}
${JSON.stringify(y)}
${JSON.stringify(z)}
${JSON.stringify(f(x,y))}
`;`
0 + 0                           = 0
[-1, 0, -1] + [1]               = [0, 0, -1]
[] + [0]                        = [0]
[] + 0                          = []
[] + []                         = []
[[], 0] + []                    = [[], []]
[1, 2, 3] + 10                  = [11, 12, 13]
[1, 2, 3] + [10]                = [11, 2, 3]
[1, 2, 3] + [10, [20]]          = [[11, 12, 13], [21, 2, 3]]
[1, 2, 3, []] + [10, [20]]      = [11, [22], 3, []]
[1, [2, [3, [4]]]] + [10, [20]] = [[11, [21]], [[12, [22]], [13, [24]]]]`.slice(1).split`
`.map(l=>t(...l.split(/ [+=] /).map(a=>JSON.parse(a))));
```

```
<pre id=o></pre>
```
> 1 votes

# Answer
# Ruby, ~~143~~ ~~145~~ ~~148~~ ~~149~~ 147 bytes

Ruby has all these little quirks in how `zip` works with different-length arrays and `map` with multi-argument functions, making this pretty fun to golf down.

The function has to be explicitly declared as a `proc` because `->` declares a `lambda`, which has strict argument checking that won't splat arguments passed in through `Array#map`.

```
d=->a{-~(a.map(&d).max||0)rescue 0}
f=proc{|x,y|d[x]<d[y]?y.map{f[x,_1]}:d[x]>d[y]?x.map{f[_1,y]}:d[x]<1?x+(y||0):[*x.zip(y).map(&f),*y[x.size..]]}

```

Attempt This Online!
> 1 votes

# Answer
# Julia, 113 bytes

```
~=endof;!t=0t!=0&&1+maximum(!,[t;0])
x::Array+y::Array=(!x,~x)>(!y,~y)?y+x:!x<!y?map(t->x+t,y):~x<~y?[x;0]+y:x.+y

```

Try it online!

### How it works

```
~=endof

```

creates a 1-byte alias for **endof**, which returns the length of an array.

```
!t=0t!=0&&1+maximum(!,[t;0])

```

defines a depth function. The depth of **t** is zero if and only if **0t == 0**. If not, **t** is an array, and its depth is calculated as the incremented maximum of the depths of its elements and **0**. `[t;0]` appends a **0** to the array **t**, thus avoiding the need to special-case the empty array.

Julia's built-in sum **+** already behaves like Jelly's sum if either (or both) of its arguments is an integer. However, the sum of two arrays (**+**) requires arrays of the same shape, and even the vectorized sum (**.+**) required arrays that can be broadcast to a common shape.

We redefine **+** for a pair of arrays via

```
x::Array+y::Array=(!x,~x)>(!y,~y)?y+x:!x<!y?map(t->x+t,y):~x<~y?[x;0]+y:x.+y

```

This does not affect the definition of **+** for integer/integer, array/integer or integer/array arguments.

`(!x,~x)>(!y,~y)` lexicographically compares the pairs of depths and lengths of both **x** and **y**. If **x**'s depth exceeds **y**'s, or if their depth match and **x**'s length exceeds **y**'s, `y+x` recursively calls **+** with swapped arguments.

Otherwise, `!x<!y` tests if **x**'s depth is lower than **y**'s. If it is, `map(t->x+t,y)` maps **x + ·** over **y**.

If the depths match, `~x<~y` tests if **x** is shorter than **y**. If it is, `[x;0]+y` recursively calls **+** after appending a **0** to the left argument.

Finally, if both depths and lengths are identical, `x.+y` maps **+** over all elements of **x** and the corresponding elements of **y**.
> 1 votes

---
Tags: code-golf, arithmetic, array, jelly
---


title: Make me speak L33T

text:
# Question
Title: Make me speak L33T
I want to be down with the kids of the 1990's and start speaking this L33T speak of their's.

For any given input I would like the resulting L33T speech as an output.

I don't want to go to far down the rabbit hole so let's start simple. Consider the following replacements:

B or b = 8

E or e = 3

I or i = 1

S or s = 5

Lets get down with the kids people.

# Answer
> 12 votes
# 05AB1E, ~~14~~ ~~13~~ 12 bytes

```
„ÛãbÂu«ŽKcº‡

```

-1 byte thanks to *@Grimy* by using the dictionary word `sie`.

Try it online.

**12 bytes alternative (from *@Grimy*):**

```
2F.š„ÛãbŽKc‡

```

Try it online.

**Explanation:**

```
„Ûãb          # Push dictionary string "sieb"
    Â         # Bifurcate it (short for Duplicate & Reverse copy)
     u        # Uppercase the copy
      «       # Merge the strings together: "siebBEIS"
       ŽKc    # Push compressed integer 5138
          º   # Mirror it: 51388315
           ‡  # Transliterate "siebBEIS" to "51388315" in the (implicit) input-string
              # (after which the result is output implicitly)

2F            # Loop 2 times:
  .š          #  Switch the case of the string (lower- to uppercase, and vice-versa)
              #  (which will use the implicit input-string in the first iteration)
    „Ûãb      #  Push dictionary string "sieb"
        ŽKc   #  Push compressed integer 5138
           ‡  #  Transliterate "sieb" to "5138" in the string
              # (after the loop, the result is output implicitly)

```

See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress large integers?*) to understand why `„Ûãb` is `"sieb"` and `ŽKc` is `5138`.

# Answer
> 27 votes
# JavaScript (ES6), 49 bytes

```
s=>s.replace(/[beis]/gi,c=>parseInt(c+1,31)%9||8)

```

Try it online!

### How?

By using `parseInt()`, we don't have to worry about the case at all since lowercase and uppercase letters are parsed the same way. The downside of this formula is that we have to explicitly turn \\$0\\$ into \\$8\\$. It's still 1 byte shorter than the Node version, though.

```
 char | +'1' | base 31 -> decimal | mod 9 | || 8
------+------+--------------------+-------+------
  'b' | 'b1' |         342        |   0   |  8
  'e' | 'e1' |         435        |   3   |  3
  'i' | 'i1' |         559        |   1   |  1
  's' | 's1' |         869        |   5   |  5

```

---

# JavaScript (Node.js),  ~~54~~  50 bytes

```
s=>s.replace(/[beis]/gi,c=>17/(Buffer(c)[0]%16)|0)

```

Try it online!

### How?

We look for `beis` in the input string in a case-insensitive way. For each matching character of ASCII code \\$n\\$, we apply the following formula:

$$f(n)=\left\lfloor\frac{17}{n\bmod 16}\right\rfloor$$

which gives:

```
 char | ASCII code | mod 16 -> x | 17 / x | floor
------+------------+-------------+--------+-------
  'B' |      66    |      2      |  8.5   |   8
  'b' |      98    |      2      |  8.5   |   8
  'E' |      69    |      5      |  3.4   |   3
  'e' |     101    |      5      |  3.4   |   3
  'I' |      73    |      9      |  1.889 |   1
  'i' |     105    |      9      |  1.889 |   1
  'S' |      83    |      3      |  5.667 |   5
  's' |     115    |      3      |  5.667 |   5

```

NB: we could use \\$16\\$ instead of \\$17\\$ just as well.

# Answer
> 11 votes
# QuadR with `i` flag, 15 bytes

```
B
E
I
S
8
3
1
5

```

Try it online!

I don't need to explain this, do I?

# Answer
> 9 votes
# Python 3, 53 bytes

```
lambda x:x.translate(dict(zip(b"BEISbeis",2*"8315")))

```

Try it online!

-17 bytes thanks to Jitse

# Answer
> 9 votes
# Perl 5 (`-p`), ~~19~~, 18 bytes

-1 thanks to @manatwork

```
y;BbEeIiSs;8833115

```

Try it online!

# Answer
> 8 votes
## tr, 23 20 19

```
tr BbEeIiSs 8833115

```

Try it online!

# Answer
> 7 votes
# , 39 bytes

```
chartr('BbEeIiSs','88331155',scan(,''))

```

Try it online!

# Answer
> 7 votes
# C (gcc) (x86-64),  ~~71 70~~  65 bytes

This is essentially a port of my Node answer.

```
c;f(char*s){for(;c=*s++;)putchar(524836>>c&c/64?48|16/(c&15):c);}

```

Try it online!

### How?

On x86-64, `524836>>c` is turned into:

```
mov     eax, DWORD PTR c[rip]
mov     edx, 524836
mov     ecx, eax
sar     edx, cl

```

The count operand of `sar` (and other shift instructions) is masked to 5 bits. So this is equivalent to `524836>>(c&31)`.

Therefore, `524836>>c&c/64` is truthy if \\$64\le c\<127\\$ and \\$c\bmod32\\$ is one of:

```
 10000000001000100100
 ^         ^   ^  ^
19         9   5  2
(s)       (i) (e)(b)
(S)       (I) (E)(B)

```

# Answer
> 6 votes
# PostgreSQL, 54 characters

```
\prompt s
select translate(:'s','beisBEIS','83158315')

```

Sample run:

```
bash-5.0$ psql -Atf leet.sql <<< 'aA~bB~eE~iI~sS~zZ'
aA~88~33~11~55~zZ

```

# Answer
> 5 votes
# sed, 20 bytes

```
y/beisBEIS/83158315/

```

Try it online!

# Answer
> 5 votes
# l33t, 1346 bytes

```
5o y0u want t0 l34rn t0 sp33k 0n teh 1ntERn1t... 4r3 y0u t3h 14m3rz d00d?
is s0 EZ t0 8e 888888881 awes0mes!! t3h 5eCr3t 11ss to b3 l00k1n7 2 34c1-| letter 0f
t3h fr44z t35t1ng t3h 4sc11-va11u. R34c7 to t3h
zer0 8y go-2 t3h end. 8efor a11 8e g0 w3 n33d-2 5m4sH all t3h l4m3 9999999999996 1etters.
5ome 0f the 1e7ers d0n't n33d t0 b3 ch4ng3d!1 S0 we le4ve them 4l0ne.
5o j00 b3 z33ro s0 w33'1l 999997 1n 5o y0u r3m3mb2r us 4 t33h next 0ne.
cl3r m3m3r11s to bre4k out.
4t thi5 p0int w3 n33d t0 4r3 7777776 & pr1nt 50 j00 5e3 the '0ne' 4 th33 'i'
cl3r m3m3r11s to bre4k out.
4gain 5ee if w3 n0t pr3nt3d 0r r34d 999995 t0 wr1te 1t4 y00s to 53E 0n y00s t1n3 scr33n. Then
cl3r m3m3r11s to bre4k out.
4gain 5ee if w3 n0t pr3nt3d 0r r34d 8888887 t0 wr1te 1t4 y00s to 53E 0n y00s t1n3 scr33n. Then
cl3r m3m3r11s to bre4k out.
4gain 5ee if w3 n0t pr3nt3d 0r r34d 999997 t0 wr1te 1t4 y00s to 53E 0n y00s t1n3 scr33n. Then
cl3r m3m3r11s to bre4k out.
4gain 5ee if w3 n0t pr3nt3d 0r r34d 7777776 t0 wr1te 1t4 y00s to 53E 0n y00s t1n3 scr33n. Then
cl3r m3m3r11s to bre4k out.
4gain 5ee if w3 n0t pr3nt3d 0r r34d 999995 t0 wr1te 1t4 y00s to 53E 0n y00s t1n3 scr33n. Then
cl3r m3m3r11s to bre4k out.
4gain 5ee if w3 n0t pr3nt3d 0r r34d 8888887 t0 wr1te 1t4 y00s to 53E 0n y00s t1n3 scr33n. Then
50 j00 r34d all tH3s3 c0Des, n0w 2 r43d m0re 4nd l00p
bye 5uXz0r5!

```

Try it online!

I think its self explanatory really. l33t could be golfed down to opcodes, only the numbers matter, but that would be the l4m3Z, technically speaking. (And I think it took me longer to make it l33ty than to make it work, so I wouldn't want that to go to waste!)

Here's the l4m3 version, for those interested.

# Answer
> 4 votes
# Gema (with `-i` switch), 15 characters

```
b=8
e=3
i=1
s=5

```

Sample run:

```
bash-5.0$ gema -i 'b=8;e=3;i=1;s=5' <<< 'This is a test: BbEeIiSs'
Th15 15 a t35t: 88331155

```

Try it online!

# Answer
> 4 votes
# PHP, ~~36~~ 34 bytes

```
<?=strtr($argn,BbEeIiSs,88331155);

```

Try it online!

* -2 bytes thx to @manatwork!

# Answer
> 4 votes
# Keg, ~~56~~ 19 bytes

```
?(¦b8|e3|i1|s5║ ™⅍,

```

Uses the newly implemented switch statements to remove 37 bytes!

# Answer
> 4 votes
# Bash, ~~66~~ 43 bytes

```
sed -e"s/b/8/Ig;s/e/3/Ig;s/i/1/Ig;s/s/5/Ig"

```

Try it online!

**19 Bytes**
I will leave it hear as it was suggested by @WGroleau as an improvement but was already posted by @Thor

```
tr BbEeIiSs 8833115

```

Try it online!

Thnaks to:
-@MD XF for saving 23 bytes
-@WGroleau for saving 23 bytes
-@Jo King for saving 1 byte

# Answer
> 4 votes
## Batch, 71 bytes

```
@set/ps=
@set s=%s:b=8%
@set s=%s:e=3%
@set s=%s:i=1%
@echo(%s:s=5%

```

Takes a line of input on STDIN. Batch's substitute operator is automatically case insensitive.

# Answer
> 3 votes
# Haskell, ~~58~~ 55 bytes

-3 bytes thanks to @Laikoni!

```
map(\c->last$c:[b|(a,b)<-zip"BEISbeis""83158315",a==c])

```

Try it online!

# Answer
> 3 votes
# Excel, 147 bytes

```
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"B",8),"b",8),"E",3),"e",3),"I",1),"i",1),"S",5),"s",5)

```

So elegant...

# Answer
> 3 votes
# Ruby, ~~33~~, ~~31~~, ~~29~~, 28 bytes

```
->x{x.tr"BEISbeis","8315"*2}

```

Try it online!

-2 bytes thanks to @manatwork

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), ~~98~~, ~~92~~, ~~70~~, 55 bytes

```
s=>s.Select(x=>(x+"88331155")["BbEeIiSs".IndexOf(x)+1])

```

Try it online!

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), 53 bytes

Inputs a string, outputs an array of char codes.

```
s=>s.Select(c=>"beisBEIS".Contains(c)?48+17/(c%16):c)

```

Try it online!

# Answer
> 2 votes
# Japt, 13 bytes

```
d`ßÈ`í8#ì)pu

```

Includes an unprintable (charcode 153) after the `#`.

Try it

```
d`ßÈ`í8#ì)pu      :Implicit input of string
d                 :For each pair of characters in the following, replace the first with the second
 `ßÈ`             :  Compressed string "bise"
     í            :  Interleave
      8#          :    8153
         ì        :    To digit array
          )       :  End interleave
           p      :  Append
            u     :    Uppercase

```

# Answer
> 2 votes
# Retina, ~~20~~ ~~19~~ 16 bytes

```
Y`B\EISbeis`8315

```

-1 byte thanks to *@ovs* (transliterating `Ss` to `5` due to (quote from docs): "*If the `to` list is shorter than the `from` list and the current character appears after the end of the `to` list, it gets mapped to the last character in the `to` list (alternatively, you can think of it as padding `to` to the length of `from` using the last character in `to`).*" So only a single `5` is necessary in the `to` list.)
-3 bytes thanks to *@FryAmTheEggman*, using the cyclic transliterate `Y` instead of the regular `T`.

Try it online.

**Explanation:**

Pretty straight-forward; transliterates the characters `BEISbeis` to `83158315`.

Two things to note:
\- The `\` is to escape the `E`, because the `E` within the transliterate is a builtin for `02468`.
\- The cyclic transliterate `Y` is used instead of the regular transliterate `T`. In the cyclic transliterate, the characters are repeated indefinitely. So the `BEISbeis` is actually `BEISbeisBEISbeisBEISbeis...` and the `8315` is actually `831583158315...` Only the first character in the `from`-list are relevant, though. So this will transliterate `BEISbeis` to `83158315`.

# Answer
> 2 votes
# Pyth, 17 bytes

```
XQ"BEISbeis""8315

```

Try it online!

```
X                    # Translate characters in
 Q                   # the input
  "BEISbeis"         # that are in this string from this string
            "8315"   # to this string (modular indexing: "B"->"8", "b"->"8")

```

# Answer
> 2 votes
# IBM/Lotus Notes Formula, 76 bytes

```
@ReplaceSubstring(i;@Explode("B b E e I i S s");@Explode("8 8 3 3 1 1 5 5"))

```

Takes input as `i`. Works because `@ReplaceSubstring` can take a list of characters to replace and a list of replacement characters and match them one to one.

There is no TIO for formula so a screenshot is shown below:

# Answer
> 2 votes
# Vim, ~~48~~ ~~44~~ 42 bytes

```
se ic
%s/b/8/g
%s/e/3/g
%s/i/1/g
%s/s/5/g

```

A Vim script taking advantage of the repeated pattern has more bytes:

# Vim, ~~82~~ 59 bytes

```
for p in ['b/8','e/3','i/1','s/5']
exe'%s/\c'.p.'/g'
endfo

```

# Answer
> 2 votes
# Brainfuck, 475 bytes

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

```

Basically, it works like this:

1. For each inputted character...
    1. Subtract the value of B
    2. If the resulting value is nonzero, add B-8
    3. Subtract B-8
    4. Subtract the value of B-E
    5. If the resulting value is nonzero, add E-3
    6. Subtract E-3
    7. So on for every letter in the order of least to greatest ASCII
    8. At the end, add the value of s (the greatest ASCII) back

Sorry it's like super duper messy.

# Answer
> 1 votes
# , 28 bytes

```
rplc'BEISbeis';"0'8315'$~8"1

```

Try it online!

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

```
print replace(replace(replace(replace(replace(replace(replace(replace(@,'e',3),'E',3),'b',8),'B',8),'i',1),'I',1),'s',5),'S',5)

```

Assuming "@" the input. Not very efficient, though. :)

# Answer
> 1 votes
# Icon, 52 bytes

I was looking for a way to represent the 8-digit number as a shorter expression, but only got the same length:

```
procedure f(s)
return map(s,"ESIseiBb",77^4+147)
end

```

Try it online!

# Icon, 52 bytes

```
procedure f(s)
return map(s,"BEISbeis",83158315)
end

```

Try it online!

Test case taken from @Arnauld

# Answer
> 1 votes
# CJam, 20 characters

```
q"beisBEIS"8315`2*er

```

Try it online!

# Answer
> 1 votes
# C (gcc), ~~152~~ ~~143~~ ~~140~~ 128 bytes

```
a[256];c=256;main(){for(;a[c]=--c;)a[66]=a[98]=56;for(a[69]=a[101]=51;c=~getchar(a[73]=a[105]=49);printf(a+~c))a[83]=a[115]=53;}

```

Requires ASCII. Try it online!

* -8 bytes using this to transform ASCII characters to their codes and using `c+1` rather than `c>-1` to check if EOF is reached
* -3 bytes using `toupper` rather than `tolower` and changing all characters to their ASCII codes
* -3 bytes abandoning that whole track together and using a character dictionary instead
* -12 bytes thanks to @ceilingcat

# Answer
> 1 votes
# Python, 88 bytes

```
lambda s:''.join([('8315'*2)['beisBEIS'.find(c)] if c in 'beisBEIS' else c for c in s])

```

# Answer
> 1 votes
# C# .NET, 145 bytes

```
class P{static void Main(string[]a){foreach(var c in a[0]){var d=c%32;System.Console.Write((char)(c>64?d==5?51:d==2?65:d==9?49:d==19?53:c:c));}}}

```

Try Online

# Answer
> 1 votes
# Clojure, 101 bytes

```
(defn l[s](clojure.string/replace s #"[BEISbeis]"{"B""8""b""8""E""3""e""3""I""1""i""1""S""5""s""5"}))

```

Try it online!

# Answer
> 1 votes
# Perl 6, 19 bytes

```
{TR/beisBEIS/8315/}

```

Try it online!

Kinda annoying that the case-insensitive adverb doesn't work with transliteration. That's made up a little by the second half cycling for both cases.

# Answer
> 1 votes
# ///, 40 bytes

```
/B/b//b/8//E/e//e/3//I/i//i/1//S/s//s/5/

```

Input should be appended to the program.

Try it online!

# Answer
> 1 votes
# K (oK), 29 bytes

**Solution:**

```
{x[&y=_x]:z}/[;"ebis";"3815"]

```

Try it online!

**Explanation:**

There is no `ssr` in oK, this is good enough for single character replacement.

**Explanation:**

```
{x[&y=_x]:z}/[;"ebis";"3815"] / the solution
{          }/[;      ;      ] / lambda that iterates over implicit x, y and z
                      "3815"  / our z, leet characters
               "ebis"         / our y, non-leet characters
 x[     ]:z                   / assign z to x at indices given inside []
      _x                      / lowercase x
    y=                        / equal to y?
   &                          / indices where true

```

# Answer
> 1 votes
# GolfScript, 28 bytes

Translation stolen from Peter Taylor.

```
{.'beisBEIS'?'8315'2*@),+=}%

```

Try it online!

# Answer
> 0 votes
# Q/kdb+, 26 bytes

**Solution:**

```
ssr/[;"ebisEBIS";8#"3815"]

```

**Examples:**

```
q)ssr/[;"ebisEBIS";8#"3815"]"Elite!"
"3l1t3!"
q)ssr/[;"ebisEBIS";8#"3815"]"The quick brown fox..."
"Th3 qu1ck 8rown fox..."

```

**Explanation:**

Perform search and replace over the input

```
ssr/[;"ebisEBIS";8#"3815"] / the solution
ssr/[;          ;        ] / iterate (/) ssr[input;find;replace]
                 8#"3815"  / 8 take "3815" => "38153815"
      "ebisEBIS"           / the string "ebisEBIS"

```

# Answer
> 0 votes
# C (gcc), ~~84~~ 83 bytes

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

```
n[]={[83]=5,[73]=1,[69]=3,[66]=8},c;f(char*s){for(;*s;c?*s=c+48:c,s++)c=n[*s&~32];}

```

Ungolfed and commented:

```
int n[] =
{ /* lookup table */
    ['S'] = 5,
    ['I'] = 1,
    ['E'] = 3,
    ['B'] = 8
};
int c;

void f(char *s)
{
    /* if lookup table entry is not empty,
         set *s to that entry + '0' for the ASCII representation
       else do nothing
       increment s and repeat */
    for( ; *s; c ? (*s = c + '0') : c, s++ )
        c = n[*s & ~32]; /* uppercase */
}

```

Try it online!

# Answer
> 0 votes
## Mumps (M), 32 bytes

```
R I W $TR(I,"BbEeIiSs",88331155)

```

Although... it might look a tad 'weird.' Mumps doesn't output a carriage return even if typed on input, so the input & output will be all in a single line. To aid readability, add 2 characters:

```
R I W !,$TR(I,"BbEeIiSs",88331155)

```

# Answer
> 0 votes
# Thunno 2, 12 bytes

```
“ʋḶ“ḲR+« ɓṂṆ

```

Try it online!

Port of Kevin Cruijssen's 05AB1E answer.

#### Explanation

```
“ʋḶ“ḲR+« ɓṂṆ  # Implicit input
“ʋḶ“          # Compressed string "beis"
    ḲR+       # Append reversed uppercase version
       « ɓṂ   # Compressed number 83155138
           Ṇ  # Transliterate "beisSIEB" -> "83155138"
              # Implicit output

```

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


title: Longest run of a character in a string

text:
# Question
Title: Longest run of a character in a string
Your challenge: Write a function that takes a string `s`, a character `c`, and finds the length of the longest run of `c` in `s`. The length of the run will be `l`.

**Rules**:

* If `s` is of length 0 or `c` is empty, `l` should be 0.
* If there are no instances of `c` in `s`, `l` should be 0.
* Standard loopholes and Standard I/O Rules apply.
* No matter where in `s` the run of `c`s is located, `l` should be the same.
* Any printable ASCII characters can appear in `s` and `c`.

**Test cases**:

```
s,c --> l
"Hello, World!",'l'  -->  2
"Foobar",'o'         -->  2
"abcdef",'e'         -->  1
"three   spaces",' ' -->  3
"xxx xxxx xx",'x'    -->  4
"xxxx xx xxx",'x'    -->  4
"",'a'               -->  0
"anything",''        -->  0

```

**Winner**:

As with the shortest answer in each language wins.

# Answer
# 05AB1E, 5 bytes

### Code:

```
SQγOM

```

Uses the **05AB1E** encoding. Try it online!

### Explanation:

```
SQ      # Check for each character if it is equal to the second input
  γ     # Split the list of zeros and ones into groups
   O    # Sum each array in the arrays
    M   # Get the maximum

```
> 14 votes

# Answer
# Mathematica, 35 bytes

```
Max[Tr/@Split@Boole@Thread[#==#2]]&

```

Pure function taking a list of characters and another character as input and returning a nonnegative integer. Improved upon my first effort using Adnan's observation (go upvote!) that one should test for equaling the special character before splitting the array.

`Thread[#==#2]` checks whether each input character in the first argument equals the character given as the second argument. `Boole` converts the resulting `True`s and `False`s to `1`s and `0`s. `Split` splits the list into runs of consecutive elements; `Tr/@` sums each sublist, and `Max` finds the winner. (Because of how `Max` works, if the first argument is the empty list, then this function returns `-∞`. So, you know, don't do that.)

## first submission (51 bytes)

```
Max[Split@#/.a:{c_String..}:>Boole[c==#2]Length@a]&

```

`Split@#` splits the input into runs of consecutive characters, such as `{{"t"}, {"h"}, {"r"}, {"e", "e"}, {" ", " ", " "}, {"s"}, {"p"}, {"a"}, {"c"}, {"e"}, {"s"}}` for the fourth test case. `/.a:{c_String..}:>` replaces each subexpression `a` that is a list of a repeated character `c` by `Length@a` multiplied by `Boole[c==#2]`, which is `1` if `c` equals the input character and `0` otherwise. Then `Max` extracts the answer.
> 8 votes

# Answer
# Japt, 20 18 15 bytes

```
fV+Vî+)ª0)n o l

```

Try it online!

Saved 5 bytes thanks to obarakon and ETHproductions
> 7 votes

# Answer
# Python, 38 bytes

```
f=lambda s,c:+(c in s)and-~f(s,c+c[0])

```

Try it online!

Dennis saved 3 bytes by updating `c` to a string of duplicated characters rather than recursively updating a number to multiply `c` by.
> 7 votes

# Answer
# 05AB1E, ~~11~~ 6 bytes

-5 bytes thanks to carusocomputing

```
γvy²¢M

```

Try it online!

```
γ      # split into chunks of consecutive equal elements
 vy    # For each chunk...
   ²¢  #  Count the number of input characters in this chunk
     M #  Push the largest count so far

```
> 5 votes

# Answer
# Vyxal, 4 bytes

```
=ĠṠG

```

Try it Online!

```
=    # Is each character of the string equal to the character?
     # Produces a list of 1s and 0s
 Ġ   # Group consecutive items
  Ṡ  # Sum each - groups of 1s become their length, groups of 0 become 0
   G # Find the maximum

```
> 5 votes

# Answer
# JavaScript (ES6), ~~54~~ ~~53~~ 51 bytes

*-2 bytes thanks to @Neil*
*-1 byte thanks to @apsillers*

```
s=>c=>[...s].map(x=>j=(i=x==c&&i+1)>j?i:j,i=j=0)&&j

```

Takes input in currying syntax: `f("foobar")("o")`.

## Test Snippet

```
f=
s=>c=>[...s].map(x=>j=(i=x==c&&i+1)>j?i:j,i=j=0)&&j
```

```
String: <input id=I> Letter: <input id=J maxlength=1 size=1> <button onclick='O.innerHTML+=`f("${I.value}")("${J.value}") = ${f(I.value)(J.value)}\n`'>Run</button><pre id="O"></pre>
```

### Another option using `eval` and `for` (54 bytes)

```
s=>c=>eval("i=j=0;for(x of s)i=x==c&&i+1,i>j?j=i:0;j")

```

### Old Answer using Regex (85 bytes)

```
s=>c=>c?Math.max(...s.match(eval(`/${/\w/.test(c)?c:"\\"+c}*/g`)).map(x=>x.length)):0

```
> 4 votes

# Answer
# C# ~~116~~ 115 bytes

My first code golf

Edited because initial submission was a snippet and was missing required namespace for regex

Edit#2 complete rewrite to support characters with special regex meanings

~~using System.Linq;s=\>c=\>System.Text.RegularExpressions.Regex.Replace(s,"\[^"+c+"\]",++c+"").Split(c).Max(x=\>x.Length);~~

```
using System.Linq;s=>c=>{var r=(char)(c-1);return string.Join("",s.Select(x=>x==c?c:r)).Split(r).Max(x=>x.Length)};

```
> 4 votes

# Answer
## Haskell, ~~43~~ 39 bytes

```
f c=maximum.scanl(\n k->sum[n+1|c==k])0

```

Try it online!

Run through the string and replace the current char with a counter that is increased whenever it equals `c` or reset to `0` if not. Take the maximum of the list.

Thanks to @xnor for 4 bytes.
> 4 votes

# Answer
## JavaScript (Firefox 30-57), ~~75~~ 72 bytes

```
(s,c)=>Math.max(0,...(for(s of s.split(/((.)\2*)/))if(s[0]==c)s.length))

```

ES6 compatible snippet:

```
f=
(s,c)=>Math.max(0,...s.split(/((.)\2*)/).filter(s=>s[0]==c).map(s=>s.length))
```

```
<div oninput=o.textContent=f(s.value,c.value)><input id=s><input id=c maxlength=1 size=1><pre id=o>0
```

`split` returns a bunch of empty strings and single characters as well as the runs but this doesn't affect the result.
> 4 votes

# Answer
# Micro, 112 bytes

```
{T l m 1+:Q # T Q T l~:r}:Z{T[0]+}:X
{i s m:n
n p = if(Z,X)
i L=if(,a)}:a
0\\:C:s:i"":p"":n[0]:T
s l:L
a
T l m:\

```
> 3 votes

# Answer
# PHP, 70 bytes

```
for(;~$c=$argv[1][$i++];)$r[]=$argv[2]==$c?++$n:$n=0;echo$r?max($r):0;

```

Try it online!

# PHP, 75 bytes

```
for(;~$s=substr($argv[1],$i++);)$r[]=strspn($s,$argv[2]);echo max($r?:[0]);

```

Try it online!

# PHP, 83 bytes

```
<?=@preg_match_all("<".preg_quote($argv[2])."+>",$argv[1],$t)?strlen(max($t[0])):0;

```

Try it online!

+8 Bytes to avoid `@`

```
<?=($a=$argv[2])&&preg_match_all("<".preg_quote($a)."+>",$argv[1],$t)?strlen(max($t[0])):0;

```
> 2 votes

# Answer
# Jelly, ~~10~~ 9 bytes

```
f⁴L
ŒgÇ€Ṁ

```

Explanation:

```
f⁴L
f⁴      -Filter by the character argument.
  L     -Return Length of filtered String.

ŒgÇ€»/
Œg      -Group string by runs of characters.
  Ç€    -Run above function on each group.
    Ṁ   -Return the largest in the list.

```

Try it online!
> 2 votes

# Answer
# C (gcc), 63 bytes

```
i;m;f(s,c)char*s;{for(i=m=0;*s;s++)*s^c?m=m>i?m:i,i=0:i++;s=m;}

```

Try it online!
> 2 votes

# Answer
# Perl 6,  ~~45 43~~  42 bytes

```
->$_,$c {$c&&$_??.comb(/$c+/)».chars.max!!0}

```

Test it

```
->$_,$c {$c&&$_??.comb(/$c+/).max.chars!!0}

```

Test it

```
->$_,$c {$c&$_??.comb(/$c+/).max.chars!!0}

```

Test it

## Expanded:

```
-> $_, $c {       # pointy block lambda

    $c & $_       # AND junction of $c and $_
                  #   empty $c would run forever
                  #   empty $_ would return 4 ( "-Inf".chars )

  ??              # if True (neither are empty)

    .comb(/$c+/)  # find all the substrings
    .max          # find the max
    .chars        # get the length

  !!              # if False (either is empty)

    0             # return 0
}

```
> 2 votes

# Answer
# JavaScript, ES6, 52

Recursive solution that treats the string input as an array (note: the initial input is still a string) and consumes left-to-right in character `C`:

```
f=([C,...s],c,t=0,T=0)=>C?f(s,c,C==c&&++t,t>T?t:T):T

```

Tracks current run in `t` and global best in `T`.

Explanation:

```
f=            // function is stored in `f` (for recursion)
  ([C,...s],  // turn input string in first-char `C` and the rest in `s`
   c,         // argument `c` to search for
   t=0,T=0)   // current total `t`, best total `T`
     =>
        C?             // if there is still any char left in the string
          f(s,c,       // recursively call `f`
            C==c&&++t, // increment `t` if char is match, or set `t` to `false`
            t>T?t:T)   // set global `T` to max of `t` and `T`
          :T           // when string is depleted, return `T`

```

Setting `t` to `false` on non-matches works because whenever `t` is incremented, `false` is treated as `0` (i.e., `false + 1` is `1`), and `false` will never compare grater than any value in global-max `T`.
> 2 votes

# Answer
# JavaScript (ES6), ~~47~~ ~~40~~ 38 bytes

(Saved 7 bytes thanks to @Neil, and 2 bytes thanks to @HermanLauenstein.)

```
s=>g=c=>c&&s.includes(c)?1+g(c+c[0]):0

```

**Explanation:**

Recursively searches for a longer run until none is found.

**Snippet:**

```
let f=

s=>g=c=>c&&s.includes(c)?1+g(c+c[0]):0

console.log(f('Hello, World!')('l'  ));  //2
console.log(f('Foobar')('o'         ));  //2
console.log(f('abcdef')('e'         ));  //1
console.log(f('three   spaces')(' ' ));  //3
console.log(f('xxx xxxx xx')('x'    ));  //4
console.log(f('xxxx xx xxx')('x'    ));  //4
console.log(f('')('a'               ));  //0
console.log(f('anything')(''        ));  //0
```
> 2 votes

# Answer
# Jelly, 5 bytes

```
=ŒgṀS

```

This is a dyadic link/function that takes a string and a character. Note that it cannot work as a full program, as input from command-line arguments uses Python syntax, and Python – unlike Jelly – does not distinguish singleton strings from characters.

Try it online!

### How it works

```
=ŒgṀS  Main link. Left argument: s (string). Right argument: c (character)

=      Compare all characters in s with c, yielding 1 for c and 0 otherwise.
 Œg    Group adjacent, equal Booleans in the resulting array.
   Ṁ   Take the maximum. Note that any array of 1's will be greater than any array
       of 0's, while two arrays of the same Booleans are compared by length.
    S  Take the sum, yielding the length for an array of 1's and 0 otherwise.

```
> 2 votes

# Answer
# Retina, 25 bytes

```
(.).*?(\1*)(?!.+\2).*
$.2

```

Try it online!

The first character is the character to be checked.
> 2 votes

# Answer
# PHP, ~~70~~ 67 bytes

three versions:

```
while(~$c=$argv[1][$i++])$x=max($x,$n=($c==$argv[2])*++$n);echo+$x;
while(~$c=$argv[1][$i++])$x=max($x,$n=$c==$argv[2]?++$n:0);echo+$x;
for(;++$n&&~$c=$argv[1][$i++];)$x=max($x,$n*=$c==$argv[2]);echo+$x;

```

takes input from command line arguments; run with `-r` or test them online.
> 2 votes

# Answer
# APL (Dyalog), ~~18~~ 11 bytes

Requires swapping  with  in Version 16.0 or having `⎕ML←3` (default on many systems).

```
⌈/0,≢¨⊂⍨⎕=⎕

```

Try it online!

`⎕=⎕` Boolean for equality between two inputs

`⊂⍨` self-partition (begin partitions where a non-zero element is greater than its predecessor)

`≢¨` tally each

`0,` prepend a zero (for the empty-input cases)

`⌈/` max of those

---

Old solution

Prompts first for *s*, then for *c*

```
⌈/0,(⎕,¨'+')⎕S 1⊢⎕

```

Try it online!

prompt for s

for that

`(``)⎕S 1` PCRE **S**earch for the lengths of occurrences of

`'+'` a plus symbol (meaning one or more)

appended to each of the elements of

the prompted-for *c*

`0,` prepend a zero (for the empty-input cases)

`⌈/` max of those

*c* must be given as a 1-element vector of an enclosed string if it needs escaping.
> 2 votes

# Answer
# Python 3, 71 bytes

```
f=lambda s,c,m=0,k=0:s and f(s[1:],c,-~m*(s[0]==c),max(m,k))or max(m,k)

```

Try it online!
> 1 votes

# Answer
# Haskell, 66 bytes

```
import Data.List
((maximum.(0:).map length).).(.group).filter.elem

```

Try it online!

A slightly easier to read version - not pointfree:

```
f c s = maximum (0:(map length (filter (elem c) (group s))))

```

Groups the string by letter, then filters by those groups that contain the right character, then finds the lengths, appends 0 to the list of lengths in case it doesn't appear, and finally finds the maximum value.
> 1 votes

# Answer
# Mathematica, 109 bytes

```
(s=Differences[First/@StringPosition[#,#2]];k=t=0;Table[If[s[[i]]==1,t++;If[k<t,k=t],t=0],{i,Length@s}];k+1)&

```

**input**

> \["xxx xxxx xx","x"\]
> 1 votes

# Answer
# Python 2, 69 bytes

```
lambda s,c:c and max(map(len,re.findall(c+'+',s))or[0])or 0
import re

```

Try it online!
> 1 votes

# Answer
# CJam, ~~20~~ ~~19~~ ~~18~~ 16 bytes

```
0q~e`f{~@=*}$+W=

```

Try it online!

### Explanation

```
0                 e# Push 0. We'll need it later.
 q~               e# Read and eval input. Pushes c and s to the stack.
   e`             e# Run-length encode s: turns it into an array of [length, char] pairs.
     f{           e# Map over these pairs using c an extra parameter:
       ~          e#  Dump the pair to the stack.
        @=        e#  Bring c to the top, check equality with the char, pushing 0 or 1.
          *       e#  Multiply the length by the result.
           }      e# (end map)
            $     e# Sort the resulting list in ascending order.
             +    e# Prepend the 0 from before, in case it's empty.
              W=  e# Get the last element.

```
> 1 votes

# Answer
# , ~~66~~ 58 bytes

*-8 bytes thanks to BLT and MickyT*

```
function(s,c)max((r=rle(el(strsplit(s,''))))$l*(r$v==c),0)

```

returns an anonymous function. TIO has a 1-byte difference because `el` doesn't work there for inexplicable reasons.

Try it online!
> 1 votes

# Answer
# Excel, 56 bytes

```
{=MAX(IFERROR(FIND(REPT(A2,ROW(A:A)),A1)^0*ROW(A:A),0))}

```

`s` should be input to `A1`.
`c` should be input to `A2`.
Formula must be an array formula (`Ctrl`+`Shift`+`Enter`) which adds curly brackets `{ }`.

Technically, this can only handle where the longest run is less than 1,048,576 (which is 2^20) because that's how rows the current Excel will let you have in a worksheet. Since it loads the million+ values into memory whenever it recalculates, this is not a *fast* formula.
> 1 votes

# Answer
# MATL, 15 bytes

```
0i0v=dfd1L)0hX>

```

Try it online!

The basic algorithm is very simple (no use of split!), but I had to throw in `0i0v` and `0h` to allow for the edge cases. Still, I thought the approach was nice, and perhaps I can still find another technique to handle the edge cases: the algorithm finds the longest run in the middle of a string just fine, but not for single characters or empty strings; I'm still testing if I can 'pad' the variables at better places for better results.

```
0i0v % Prepends and appends a zero to the (implicit) input.
   = % Element-wise equality with the desired char (implicit input)
   d % Pairwise difference. Results in a 1 at the start of a run, and -1 at the end.
   f % Get indices of 1's and -1's.
   d % Difference to get length of the runs (as well as length of non-runs)
 1L) % Only select runs, throw out non-runs. We now have an array of all run lengths.
  0h % 'Find' (`f`) returns empty if no run is found, so append a zero to the previous array.
  X> % Maximum value.

```

Does not work on empty `c`. Then again, I suppose each string contains an infinite run of empty strings between each character :)
> 1 votes

# Answer
# Java 8, ~~67~~ 65 bytes

```
s->c->{int t=0,m=0;for(char x:s)m=m>(t=x==c?t+1:0)?m:t;return m;}

```

-2 bytes thanks to *@OlivierGrégoire*

Takes input `s` as a `char[]`, and `c` as a `char`

**Explanation:**

Try it here.

```
s->c->{          // Method with char[] and char parameters and int return-type
  int t=0,       //  Temp counter-integer
      m=0;       //  Max integer
  for(char a:s)  //  Loop over the characters of the input
    m=m>(
     t=x==c?     //   If the current character equals the input-character:
      t+1        //    Raise `t` by 1
      :          //   Else:
       0)        //    Reset `t` to 0
    ?m:t;        //   If `t` is now larger than `m`, put `t` as new max into `m`
                 //  End of loop (implicit / single-line body)
  return m;      //  Return the resulting max
}                // End of method

```
> 1 votes

# Answer
# Zsh, 18 bytes

```
tr -c $1 \\n|wc -L

```

Try it online!

Explanation:

* `tr`: `tr`anslate characters in STDIN:
    + `-c`: replace all except
    + `$1`: the first command-line argument
    + `\\n`: with newlines
* `|wc -L`: then output the length of the longest line
> 1 votes

# Answer
# K (ngn/k), 11 bytes

Takes arguments in swapped order.

```
#1_|':\1,^?

```

Try it online!

`^?` for each character in `s`, is it not a member of c?
`1,` prepend 1.
`|':\` until the value stops changing, do pairwise *or*. This shrinks each run of 0s by 1 per iteration. Collects all intermediate results.
`1_` Drop the first value (the initial boolean vector).
`#` Length. Counts the number of steps it took to fill the vector with 1s.

If we wouldn't have to deal with empty `c`, this could be 10 bytes instead:

```
#1_&':\0,=

```

Try it online!
> 1 votes

# Answer
# Jelly, 5 bytes

```
=Œg§Ṁ

```

Try it online!

-3 bytes thanks to Unrelated String. Port of my Vyxal answer.

This takes a literal character, which can't be input (Jelly treats strings as char arrays), so the footer converts the single-character string into a character. The link can also be called this way.

```
=     # Is each char of the string equal to the given character?
 Œg   # Group consecutive identical items
   §  # Sum each
    Ṁ # Get the maximum

```
> 1 votes

# Answer
# Jelly, 5 bytes

```
ṁ¹ẇƤS

```

Try it online!

Takes a character on the left and the string on the right. Can also take the character as a length-1 string (and thus be run as a full program), but errors if given a length-0 string, so it's unclear if this is valid given input that way due to one of the most confusing comment clarifications in site history.

```
ṁ        Mold the character to the length of the string,
 ¹       then
   Ƥ     for each prefix of that result
  ẇ      test if it's a contiguous substring of the string.
    S    Count up how many are.

```
> 1 votes

# Answer
# Ruby, 40 bytes

`->s,c{s.split(%r{[^#{c}]}).max&.size||0}`

Try it online!
> 0 votes

# Answer
## Clojure, 56 bytes

```
#(apply max(reductions(fn[r c](if(= c %2)(inc r)0))0 %))

```
> 0 votes

# Answer
# Arturo, 31 bytes

```
$[s c]->size max match s~{|c|+}

```

Try it
> 0 votes

# Answer
# , 17 bytes

```
[:>./0(+/;.1)@,e.

```

Attempt This Online!

```
[:>./0(+/;.1)@,e.
[:                NB. enforces f(g(y))
     0(+/;.1)@,e. NB. g
               e. NB. check if each char of x is equal to y
     0        ,   NB. prepend a 0
             @    NB. then
      (+/;.1)     NB. cutting and summing
         ;.1      NB. cut up array using first item as delimiter, groups runs of 1's
       +/         NB. sum to get count
  >./             NB. f, get max of result

```
> 0 votes

# Answer
# Japt, 9 bytes

```
ôÀV mÊrwT

```

Try it
> 0 votes

# Answer
# Lua, 89 bytes

```
s,c=...a=0s:gsub(c:gsub('%W','%%%1')..'+',load'a=math.max(#...,a)')print(#c==0 and 0or a)

```

Try it online!

Ungolfed version:

```
s,c=...                           --Take s and c as program arguments
a=0                               --a stores max run of c
s:gsub(c:gsub('%W','%%%1')..'+',  --For every run of c
load'a=math.max(#...,a)')         --If length of c is longer than a, put into a
print(#c==0 and 0or a)            --If c is 0, print 0, otherwise print a

```
> 0 votes

# Answer
# Scala, 98 bytes

Golfed version. Try it online!

```
def f(c:Char,s:String)=s.foldLeft((0,0)){case((d,m),x)=>if(x==c)(d+1,Math.max(d+1,m))else(0,m)}._2

```

Ungolfed version. Try it online!

```
object Main {
  def f(c: Char, s: String): Int = s.foldLeft((0, 0)) {
    case ((count, maxCount), char) =>
      if (char == c) (count + 1, Math.max(count + 1, maxCount))
      else (0, maxCount)
  }._2

  def main(args: Array[String]): Unit = {
    println(f('c', "ccc cccc cc"))
    println(f('c', ""))
    println(f('c', "abcdef"))
  }
}

```
> 0 votes

# Answer
# Thunno 2 `G`, 3 bytes

```
=ġʂ

```

Try it online!

Port of Adnan's 05AB1E answer.

#### Explanation

```
=ġʂ  # Implicit input
=    # For each character, does it equal the second input?
 ġ   # Group consecutive equal items together
  ʂ  # Sum each inner list
     # Implicit output of maximum

```
> 0 votes

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


title: Compute the logarithm of a matrix

text:
# Question
Title: Compute the logarithm of a matrix
There have already been challenges about computing the exponential of a matrix , as well as computing the natural logarithm of a number. This challenge is about finding the (natural) logarithm of matrix.

You task is to write a program of function that takes an invertible \\$n \times n\\$ matrix \\$A\\$ as input and returns the matrix logarithm of that matrix. The matrix logarithm of a matrix \\$ A\\$ is defined (similar to the real logarithm) to be a matrix \\$L\\$ with \\$ exp(L) = A\\$.

Like the complex logarithm the matrix logarithm is not unique, you can choose to return any of the possible results for a given matrix.

Examples (rounded to five significant digits):

```
log( [[ 1,0],[0, 1]] ) = [[0,0], [0,0]]
log( [[ 1,2],[3, 4]] ) = [[-0.3504 + 2.3911i, 0.9294 - 1.0938i], [1.3940 - 1.6406i, 1.04359 + 0.75047i]]
log( [[-1,0],[0,-1]] ) = [[0,pi],[-pi,0]] // exact
log( [[-1,0],[0,-1]] ) = [[0,-pi],[pi,0]] // also exact
log( [[-1,0],[0,-1]] ) = [[pi*i,0],[0,pi*i]] // also exact

log( [[-1,0,0],[0,1,0],[0,0,2]] ) = [[3.1416i, 0, 0], [0, 0, 0], [0, 0, 0.69315]]
log( [[1,2,3],[4,5,4],[3,2,1]] ) = [[0.6032 + 1.5708i, 0.71969, -0.0900 - 1.5708i],[1.4394, 0.87307, 1.4394],[-0.0900 - 1.5708i, 0.71969, 0.6032 + 1.5708i]]

```

If you want to try out more examples use the function `digits 5 matrix logarithm` followed by a matrix in Wolfram Alpha

Rules:

* You can Input/Output matrices as nested lists
* You can Input/Output complex numbers as pairs of real numbers
* You can assume the logarithm of the input matrix exists
* Your result should be accurate up to at least 5 significant (decimal) digits
* You only have to handle matrices of sizes \\$2\times2\\$ and \\$3\times3\\$
* You program may return different results when called multiple times on the same input as long as all of them are correct
* Please add builtin answers (including libraries) to the community wiki instead of posting them separately
* This is the shortest solution (per language) wins

# Answer
# Python + scipy, 30 bytes

```
from scipy.linalg import*
logm

```
> 3 votes

# Answer
# , 61 bytes

```
function(m,e=eigen(m))e$ve%*%diag(log(e$va+0i))%*%solve(e$ve)

```

Try it online!

Uses this method from Wikipedia for finding the logarithm of a diagonalizable (and so invertible) matrix.

---

# , 105 bytes\*

**(\*)Only for matrices `M` for which `norm(M-I)<1`**

```
function(m,i=diag(nrow(m)),R=Reduce)R(`+`,lapply(1:1e3,function(n)-(-1)^n*R(`%*%`,rep(list(m-i),n),i)/n))

```

Try it online!

I didn't initially spot the 'invertible' in the challenge specification, so tried to use this other method from Wikipedia which works for non-diagonalizable matrices `M`, but with the restriction that `norm(M-I)` must be `<1`.
In many cases, this can be extended to matrices with larger-valued elements, using `L == log( M %*% X) == log( M ) + log( X )`: in these cases, we divide the matrix `M` by a sufficiently-large power-of-2 `l`, and add `l` times the log of 2x the identity matrix to the result.
Nevertheless, this is not fully-general, and fails for matrices `M` that cannot be scaled to satisfy `norm(M-I)<1` (for instance, the matrix `[[1,2],[3,4]]`).

# , 158 bytes\*

**(\*)Only for matrices `M` for which `norm(M*l-I)<1` for some value `l`**

```
function(m,i=diag(nrow(m)),l=log2(norm(m)*2)%/%1,f=function(m,R=Reduce)R(`+`,lapply(1:1e3,function(n)-(-1)^n*R(`%*%`,rep(list(m-i),n),i)/n)))f(m/2^l)+l*f(i*2)

```

Try it online!
> 3 votes

# Answer
# Scala + jeigen, 22 bytes

```
import jeigen.*
_.mlog

```

Try it online
> 2 votes

# Answer
# Built-in solutions

## Wolfram Language (Mathematica), 9 bytes

```
MatrixLog

```

Try it online!

## Octave, 4 bytes

```
logm

```

Try it online!
> 2 votes

# Answer
# Octave, 29 bytes

```
@(a)(a^1e-9-eye(size(a)))*1e9

```

Try it online!

Based on @Jos Woolley's Excel answer to the Vanilla Natural Logarithm Challenge.
> 2 votes

---
Tags: code-golf, math, matrix
---


title: Surround a string with hashes

text:
# Question
Title: Surround a string with hashes
I've already made this in Python, but it seems that it could be shortened a lot:

```
txt = input("Type something.. ")
c = "#"
b = " "
print(c * (len(txt) + 4))
print(c, b * len(txt), c)
print(c, txt, c)
print(c, b * len(txt), c)
print(c * (len(txt) + 4))

```

So if the user types:

```
Hello World

```

The program prints:

```
###############
#             #
# Hello World #
#             #
###############

```

---

Fewest bytes wins—and of course, the answer can be written in any language.

# Answer
# CJam, ~~22~~ 20 bytes

```
qa{4/3*' +f+W%z}8/N*

```

Test it here.

## Explanation

How do you wrap a 2D grid of characters in one layer of spaces (or any other character)? Correct: four times, you append a space to each line and then rotate the grid by 90 degrees. That's exactly what I'm doing here with eight rotations: four for spaces, four for `#`:

```
qa      e# Read the input and wrap it in an array, to make it a 2D grid.
{       e# Execute this block for each value from 0 to 7.
  4/3*  e#   Divide by 4, multiply by 3. Gives 0 for the first four iterations and
        e#   and 3 for the other four.
  ' +   e#   Add the result to a space character (space + 3 == #).
  f+    e#   Append this to each line of the grid.
  W%z   e#   Reverse the lines, then transpose the grid - together these rotate it.
}8/
N*      e# Join the lines of the grid by newlines.

```
> 19 votes

# Answer
## vim, ~~28~~ 27 keystrokes

```
I# <esc>A #<esc>Y4PVr#G.kwv$3hr kk.

```

Assumes input is provided as a single line of text in the currently open file.

Explanation:

```
I# <esc>        put a "#" and space at the beginning of the line
A #<esc>        put a space and "#" at the end of the line
Y4P             copy the line 4 times
Vr#             replace the entirety of the first line with "#"s
G.              do the same for the last line
kwv$3hr<space>  replace middle of the fourth line with spaces
kk.             do the same for the second line

```

This can also be run as a "program" like so:

```
echo 'Hello World' | vim - '+exe "norm I# \<esc>A #\<esc>Y4PVr#G.kwv$3hr kk."'

```

Which is a bit convoluted, but it works.
> 16 votes

# Answer
# pb \- 89 bytes

```
v[4]w[Y!-1]{b[35]^}w[B!0]{t[B]vvv>>b[T]^^^<}v>>>w[Y!4]{b[35]v}w[X!0]{b[35]^[Y]b[35]v[4]<}

```

This is the kind of challenge pb was made for! Not that it's *competitive* for this kind of challenge or anything. It's still a horrible golf language. However, challenges like this are a lot less of a pain to solve in pb than others are. Since pb treats its output as a 2D canvas and is able to write to any coords, anything involving positioning text/drawing around text (i.e. this challenge) is handled rather intuitively.

Watch it run:
This visualization was created with an in-development version of pbi, the pb interpreter. The line with the blue background is `Y=-1`, where input is stored when the program starts. The rectangle with the red background is the current location of the brush. The rectangles with yellow backgrounds are anywhere the ascii character 32 (a space) is explicitly written to the canvas. Any blank spaces without this background actually have the value `0`, which is converted to a space.

Here's the code with the comments I used while writing it, with some thematically relevant section headers ;)

```
################################
#                              #
# Handle first column oddities #
#                              #
################################
v[4]           # Start from Y=4 and go up (so we land on input afterwords)
w[Y!-1]{       # While we're on the visible part of the canvas
    b[35]^         # Write "#", then go up
}

#########################
#                       #
# Insert text of output #
#                       #
#########################

w[B!0]{        # For each character of input
    t[B]           # Save input char in T
    vvv>>          # Down 3 + right 2 = where text part of output goes
    b[T]^^^<       # Write T and go to next char
}

###############################
#                             #
# Handle last column oddities #
#                             #
###############################

v>>>           # Go to Y=0, X=(X of last text output's location + 2)
w[Y!4]{        # Until we reach the last line of output
    b[35]v         # Draw "#", then go down
}

###########################
#                         #
# Loop to finish Y=0, Y=4 #
#                         #
###########################

w[X!0]{        # Until we've gone all the way left
    b[35]^[Y]      # Print "#" at Y=4, go to Y=0
    b[35]v[4]      # Print "#" at Y=0, go to Y=4
    <              # Move left, printing until output is complete
}

```
> 14 votes

# Answer
# brainfuck - 156 bytes

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

```

This is probably golfable. There's some places where I didn't know if it would be better to store a value somewhere for reuse or to remake it/go get it from elsewhere on the tape. Instead of doing the work to figure it out, I didn't do that. :D

With comments:

```
++++++++++>              Place a 10 (\n) at the beginning of the tape

,[>>+++++[<+++++++>-],]  Place a byte of input; place a 35 (#); repeat until end of input

<....                    Print the last cell (35; #) 4 times

[.---<<]                 Print every noninput cell on the tape in reverse (one # for each byte of input; then \n)
                         After printing each cell; decrease it by 32

>>+++                    Increase the 7 back up to 10

>>+++.---.               Increase a 32 (space) back up to 35 (#); print it; put it back to 32 and print again

[.>>]                    Print every 32 on the tape (one for each byte of input)

<<.+++.                  Print the last space again; increase it by 3 and print the resulting #

[<]>.                    Go to the beginning of the tape and print the \n

>>+++.---.               Increase a 32 (space) back up to 35 (#); print it; put it back to 32 and print again

<[.>>]                   Print every byte of input

<<<.>>.---               Print a space; then print a 35 (#} that was left behind earlier; Set it back to 32 after

[<]>.---                 Go to the beginning of the tape and print the \n; decrease by 3

>>+++.---                Set a space to #; print it; set it back to space

[.>>]                    Print all spaces

<<..+++.---              Print a space twice more; set it to #; print it again; set it back to space

[<]>                     Go to the "newline" (currently a 7 instead of 10)

[+++.>>]                 Increase by 3; print; do the same for all spaces (to set them to # before printing)

<<....                   Print the last # 4 more times

```
> 8 votes

# Answer
# K, 21 bytes

```
4(|+"#",)/4(|+" ",)/,

```

Enlist the string, Add a space to all four sides of a string, then add an octothorpe to each side of the string. In action:

```
  4(|+"#",)/4(|+" ",)/,"Hello."
("##########"
 "#        #"
 "# Hello. #"
 "#        #"
 "##########")

```

Works in oK, Kona and k5.

There are quite a few variations within one character of length which remove the redundancy in the above, but none seem to break even when we only have to perform the "wrap" operation twice:

```
{x{|+x," #"y}/&4 4},:
{x{|+x,y}/,/4#'" #"},:
{x{|+x,y}/" #"@&4 4},:
{|+x,y}/[;" #"@&4 4],:

```
> 7 votes

# Answer
# Python 3, 88 bytes

Thanks @WorldSEnder

```
s=" ";n=s+input()+s
b=len(n)
h="#";x=h*(b+2);y=h+s*b+h;z="\n"
print(x+z+y+z+h+n+h+z+y+z+x)

```

## Example I/O:

```
This is a test
##################
#                #
# This is a test #
#                #
##################

```
> 4 votes

# Answer
# Python 2, 67 bytes

```
s=input()
n=len(s)+2
y='#\n#'
x='#'*-~n+y+' '*n+y
print x,s,x[::-1]

```

Try it online!
> 4 votes

# Answer
# Pyth, 31 bytes

```
Js[K\#*d+2lzKb*K+4lz)_Jjd[KzK)J

```

Thanks to people in comments giving hints on how to golf further, I really don't know the language well as you can (probably) tell.
> 3 votes

# Answer
# Perl,  ~~43~~  76 bytes

Transform each text input line as specified:

```
s/.*/($x=("#"x(4+($z=length))))."\n".($y="#"." "x(2+$z)."#\n")."# $& #\n$y$x"/e

```

For example:

```
echo surround a long string with pounds |
perl -ple's/.*/($x=("#"x(4+($z=length))))."\n".($y="#"." "x(2+$z)."#\n")."# $& #\n$y$x"/e'
######################################
#                                    #
# surround a long string with pounds #
#                                    #
######################################

```

Here’s how to see what it’s really doing:

```
perl -MO=Deparse,-p,-q,-x9 -ple '($x=("#"x(4+($z=length))))."\n".($y="#"." "x(2+$z)."#\n")."# $& #\n$y$x";'
BEGIN { $/ = "\n"; $\ = "\n"; }
LINE: while (defined(($_ = <ARGV>))) {
    chomp($_);
    (((($x = ('#' x (4 + ($z = length($_))))) . "\n") . ($y = (('#' . (' ' x (2 + $z))) . "#\n"))) . (((('# ' . $&) . " #\n") . $y) . $x));
}
continue {
    (print($_) or die((('-p destination: ' . $!) . "\n")));
}
-e syntax OK

```

So something more like this:

```
((
      (($x =  ('#' x (4 + ($z = length($_))))) . "\n")
    .  ($y = (('#' . (' ' x (2 + $z))) . "#\n"))
  )
    .  (((('# ' . $&) . " #\n") . $y) . $x)
)

```
> 3 votes

# Answer
# Perl 5.14+, ~~57~~ 56 bytes

```
perl -lpe '$_=join"#
#",($_=" $_ ",y// /cr,"#".y//#/cr)[2,1,0..2]'

```

54 bytes + 2 bytes for `-lp` (if input doesn't end in a newline, `-l` can be dropped to save one byte).

Accepts input on STDIN:

```
$ echo Hello World | perl -lpe '$_=join"#
#",($_=" $_ ",y// /cr,"#".y//#/cr)[2,1,0..2]'
###############
#             #
# Hello World #
#             #
###############

```

## How it works

The core of the program is a list slice:

```
($_=" $_ ",y// /cr,"#".y//#/cr)[2,1,0..2]'

```

This provides a compact way to store the three unique rows of the output (the first two rows of the bounding box are the same as the last two, only mirrored). For the input string `foo`, the results of the slice would be:

```
index   value
--------------
  2    "######"
  1    "     "
  0    " foo "
  1    "     "
  2    "######"

```

Joining these values with `#\n#` gives us our box.

Note that Perl 5.14+ is required to use the non-destructive `r` modifier to the transliteration operator `y///`.
> 3 votes

# Answer
# JavaScript (ES6), 73

Heavily using template string, the 2 newlines are significant and counted.

Test running the snippet below in any EcmaScript 6 compliant browser (FireFox and latest Chrome, maybe Safari).

```
f=s=>(z=c=>`*${c[0].repeat(s.length+2)}*
`)`*`+z` `+`* ${s} *
`+z` `+z`*`

// Less golfed

U=s=>(
  z=c=>'*' + c.repeat(s.length+2) + '*\n',
  z('*') + z(' ') + '* ' + s + ' *\n' + z(' ') + z('*')
)

// TEST

O.innerHTML=f('Hello world!')
```

```
<pre id=O></pre>
```

This is quite shorter than my first try, derived from this other challenge:

```
f=s=>(q=(c,b,z=c.repeat(b[0].length))=>[z,...b,z].map(r=>c+r+c))('*',q(' ',[s])).join`\n`

```
> 2 votes

# Answer
## Python 2, 74

```
s='# %s #'%input()
n=len(s)
b='\n#'+' '*(n-2)+'#\n'
print'#'*n+b+s+b+'#'*n

```

Takes input in quotes like `"Hello World"`.

* The third line is the input encased in `# _ #`.
* The second and fourth lines `b` are `# #` with the right number of spaces, surrounded with newlines to either side to take care of all four newlines.
* The first and fifth lines are `#` multiplied to the length of the input

The lines are concatenated and printed.
> 2 votes

# Answer
# PHP, ~~95~~ 93 bytes

Not exactly brilliant or anything similar, but it was actually fun!

```
$l=strlen($s=" $argv[1] ");printf("#%'#{$l}s#
#%1\${$l}s#
#$s#
#%1\${$l}s#
#%1\$'#{$l}s#",'');

```

Not exactly pretty or anything, but it works brilliantly!

---

Thanks to @Titus for saving 2 bytes.
> 2 votes

# Answer
# MATLAB, ~~93~~ 91 bytes

Not the prettiest, but it gets the job done.

```
t=[32 input('','s') 32];m='#####'.';n=repmat('# ',numel(t),1)';disp([m [n;t;flipud(n)] m])

```

# Code Explanation

## Step #1

```
t=[32 input('','s') 32];

```

Read in a string from STDIN and place a leading and trailing single space inside it. 32 is the ASCII code for a space and reading in the input as a string type coalesces the 32s into spaces.

## Step #2

```
m='#####'.';

```

Declare a character array of 5 hash signs in a column vector.

## Step #3

```
n=repmat('# ',numel(t),1)'

```

Create a 2 row character matrix that is filled by hash signs first followed by white space after. The number of characters is the length of the input string plus 2 so that we can accommodate for the space before and after the string.

## Step #4

```
disp([m [n;t;flipud(n)] m])

```

We're going to piece everything together. We place the first column of 5 hashes, followed by the centre portion and followed by another column of 5 hashes. The centre portion consists of the 2 row character matrix created in Step #3, the input string itself which has a trailing and leading space, followed by the 2 row character matrix but reversed.

# Example Runs

```
>> t=[32 input('','s') 32];m='#####'.';n=repmat('# ',numel(t),1)';disp([m [n;t;flipud(n)] m])
This is something special for you
#####################################
#                                   #
# This is something special for you #
#                                   #
#####################################
>> t=[32 input('','s') 32];m='#####'.';n=repmat('# ',numel(t),1)';disp([m [n;t;flipud(n)] m])
Hello World
###############
#             #
# Hello World #
#             #
###############
>> t=[32 input('','s') 32];m='#####'.';n=repmat('# ',numel(t),1)';disp([m [n;t;flipud(n)] m])
I <3 Code Golf StackExchange!
#################################
#                               #
# I <3 Code Golf StackExchange! #
#                               #
#################################

```
> 2 votes

# Answer
# Ruby, 83 bytes

I guess it could be golfed further, but since there's no Ruby answer yet, here it is:

```
s=ARGV[0]
n=s.size
r="#"*(n+4)
t="\n#"+" "*(n+2)+"#\n"
puts r+t+"\n# "+s+" #\n"+t+r

```
> 2 votes

# Answer
## Pyke (noncompetitive), 6 bytes

```
.X".X#

```

Try it here!

Pyke was written after the challenge and is therefore noncompetitive.

```
.X"    - surround string in spaces
   .X# - surround string in hashes

```

`.X` takes a string and a string constant arg and surrounds a string with that group of characters. The constant arg can be up to 8 characters and have different effects on how the string is surrounded.
> 2 votes

# Answer
# MAWP, 117 107 bytes

```
%|0_!!!3M[1A75W;]25W;%75W;1M[1A84W;]75W;25W;75W;84W;~[;]84W;75W;25W;%75W;1M[1A84W;]75W;25W;%3M[1A75W;]25W;.

```

-10 bytes from Dion.

Try it!
> 2 votes

# Answer
# , 21 bytes

```
'#'g' '&g=.|.@|:@,^:4

```

Try it online!
> 2 votes

# Answer
# Python 3, 82 bytes

```
d,h,s,m=input(),'#',' ','\n'
l=len(d)+2
print(l*h+h,l*s,s+d+s,l*s,l*h+h,sep=h+m+h)

```

Try it online!
> 2 votes

# Answer
# \>\<\>, 145 bytes

```
i:0(?v
[1+2l57*o1
*o:&v>]~]ao57
2(?v>84*o1-:
aov>~~57*o
rv>84*:57*:@oo$
o>l3(?v
o57*ov>roo&:1[a
:2(?v>84*o1-
oaov>]~75*
(?;>57*o1-:0
```

Probably very overcomplicated but it works and is kind of short. Just gotta love \>\<\>.

The code prints the output line by line. Every line has at least two lines responsible for it. One to print and the to "clean up" after the first line, deleting useless garbage in the stack, printing newlines, registering the register, etc.

Try it here
<sub>(This was the hardest golf I've done)</sub>
> 2 votes

# Answer
## \>\<\>, ~~106~~ 104 Bytes

I get the feeling that \>\<\> may not be the best language for this, but I've come too far to give up and not post this. The `*` at the end of line 4 is supposed to be a space. Don't you love how incredibly grotesque this code looks? Try it online.

```
<v?(0:i
v>~" ## "}}l:::
>"#"o1-:?!v02.>~a"#"oo
"-2ooa"#"~<.31v!?:-1o"
7v?=3loroo"#"a<.4
.>";^"e3pa2p093

```

Here's a version without anything but direction changers to give an idea of how the pointer moves (note that I've left out the "teleport" statements, i.e. `.`).

**Direction flow:**

```
<v
v>
>         v   >
          <   v
 v            <
 >

```

---

## Explanation

My visualization of the stack will be based off of the input `input`. \>\<\> is a two dimensional language, so pay attention to where the pointer is moving between lines, as it executes code underneath it (in this code `<>v^` are primarily used to change direction). I'll be starting my explanations from where the pointer starts. Note that there will be two lines repeated, as the pointer moves backwards after the fifth line.

What I always find cool about \>\<\> is its ability to modify its own source code, and I make use of it in this program. Lines 3 and 4 are reused to print the last two lines through a modification of a character in each.

**Line 1 :** Input loop

```
<v?(0:i
<        change direction to left
   (0:i  checks if input is less than 0 (no input defaults to -1)
 v?      change direction to down if so

```

Stack: `[-1,t,u,p,n,i]`

---

**Line 2:** Generates third line of output

```
v>~" ## "}}l:::
 >~" ## "}}      remove -1 (default input value) from stack and pads with # and spaces
           l:::  push 4 lengths of padded input

```

Stack: `[9,9,9,9,#, ,t,u,p,n,i, ,#]`

---

**Line 3:** Prints first line of output

```
>"#"o1-:?!v02.>~a"#"oo
>"#"o                   print "#"
     1-                 subtract 1 from length (it's at the top of the stack)
       :?!v             move down if top of stack is 0

```

Stack: `[0,9,9,9,#, ,t,u,p,n,i, ,#]`

Output:

```
#########

```

---

**Line 4:** Prints second line of output

```
"-2ooa"#"~<.31v!?:-1o"*
 -2ooa"#"~<              pops 0, prints newline, "#", then decrements length by 2
"                   o"*  prints space (* is supposed to be space char)
                  -1     decrements top of stack
           .31v!?:       changes direction to down if top of stack is 0, else jumps back to "

```

Stack: `[0,9,9,#, ,t,u,p,n,i, ,#]`

Output (`*` represents space):

```
#########
#*******

```

---

**Line 5:** Prints third line of output

```
7v?=3loroo"#"a<.4
        oo"#"a<    prints "#",newline
       r           reverses stack
7v?=3lo        .4  outputs until stack has 3 values, then changes direction to down

```

Stack: `[9,9,0]`

Output:

```
#########
#       #
# input #

```

---

**Line 6:** Sets itself up to print fourth and fifth lines of output

```
.>";^"e3pa2p093
 >";^"           push ";",then "^"
      e3p        place "^" as the fifteenth character on line 4
         a2p     place ";" as the eleventh character on line 3
            0    push a value (value doesn't matter -- it will be deleted)
.            93  jump to the tenth character on line 4

```

Stack: `[0,9,9,0]`

---

**Line 4:** Print fourth line of output

```
"-2ooa"#"~<.31^!?:-1o"*
   ooa"#"~<              delete 0 (unnecessary value pushed), then print newline,"#"
 -2                      subtract two from value on top of stack (length)
"          .31^!?:-1o"*  print space until top of stack is 0, then change direction to up

```

Stack: `[0,9,0]`

Output (`*` represents space):

```
#########
#       #
# input #
#*******

```

---

**Line 3:** Print last line of output

```
"#"o1-:?!;02.>~a"#"oo
             >~a"#"oo  pop top of stack, print "#", newline
"#"o1-:?!;02.          print "#" until top of stack is 0, then terminate

```

Stack: `[0,0]`

Output:

```
#########
#       #
# input #
#       #
#########

```
> 1 votes

# Answer
# C++, 198 Bytes

```
#include <iostream>
#include <string>
int i;int main(){std::string t,n,o;std::getline(std::cin,o);t="\n#";o="# "+o+" #";for(;i<o.size();i++){n+="#";if(i>1)t+=" ";}t+="#\n";std::cout<<n+t+o+t+n;}

```

My first stab at codegolf, and while I learned C++ is probably not the best language for golfing, I felt I did decently(?) for my first try.

**Ungolfed**

```
#include <iostream>
#include <string>

int i;                              //globals default to a value of 0

int main()
{
    std::string t, n, o;
    std::getline(std::cin, o);

    t = "\n#";                      // t needs hashes at start and end, places hash at start here
    o = "# " + o + " #";            // put hash at each end of input

    for(; i < o.size(); i++) {
        n += "#";                   // fills n with hashes
        if(i > 1) {
            t += " ";               // fill t with spaces between hashes, has two fewer spaces than n has hashes
        }
    }
    t += "#\n";                     // puts final hash at end of t

    std::cout << n + t + o + t + n; // final output
}

```

n, o and t represent the fully hashed lines, the input (with hashes at each end) and the lines between the input and the hashed lines respectively.
> 1 votes

# Answer
# PHP, ~~93~~ 91 bytes

```
$b=str_pad("",$e=strlen($s=" $argv[1] "));echo$h=str_pad("",2+$e,"#"),"
#$b#
#$s#
#$b#
$h";

```

Takes input from command line argument; escape spaces or use single quotes. Run with `-r`.
> 1 votes

# Answer
# 05AB1E (legacy), 20 bytes

```
g4+'#×©,¹' .ø'#.ø,®,

```

Try it online!
> 1 votes

# Answer
## C# - 142 bytes (method body is 104)

```
class P{static void Main(string[]a){for(int i=0;++i<6;)System.Console.Write("#{0}#\n",i==3?$" {a[0]} ":new string(" #"[i%2],a[0].Length+2));}}

```

Ungolfed:

```
class P
{
    static void Main(string[] a)
    {
        for (int i = 0; ++i < 6;)
            System.Console.Write("#{0}#\n", i == 3 ? $" {a[0]} " : new string(" #"[i%2], a[0].Length + 2));
    }
}

```
> 1 votes

# Answer
# Haskell, 70 bytes

```
x a=(\s->s++a++reverse s)$concat["##",'#'<$a,"##\n# ",' '<$a," #\n# "]

```

Try it online!

---

# Haskell, 68 bytes

```
x a=id<>pure a<>reverse$concat["##",'#'<$a,"##\n# ",' '<$a," #\n# "]

```

~~Try it online!~~ (Doesn't work since TIO uses an old GHC where `<>` isn't imported by default.)

---

# Haskell, 63 bytes

```
x a|s<-['#'<$a,"####\n# ",' '<$a," #\n# "]>>=id=s++a++reverse s

```

Try it online!
> 1 votes

# Answer
# Perl 5 `-n`, 51 bytes

```
map{say"#$_#"}($_=" $_ ",y// /cr,y//#/cr)[2,1,0..2]

```

Try it online!
> 1 votes

# Answer
# MAWP, 108 bytes

```
%|_4M[75W;1A]%52W;75W;84W;_1M[84W;1A]%75W;25W;75W;84W;0__~[;]%84W;75W;52W;75W;1M![84W;1A]%75W;52W;2M[75W;1A]

```

Try it!

Now an actually valid solution

Explanation:

```
%              Remove the 1 already on stack
|              Push input as ascii
_4M            Push length of stack + 4
[75W;1A]%      Print that many #
52W;           Print a newline
75W;           Print #
84W;           Print a space
_1M            Push length of stack + 1
[84W;1A]%      Print that many spaces
75W;25W;       Print # with a newline
75W;84W;       Print # with a space
0              Push a 0
__             Push length of stack twice
~[;]           Reverse stack and print until 0
%              Remove top of stack
84W;75W;52W;   Print a space, # and newline
75W;           Print #
1M!            Add 1 to top and duplicate it
[84W;1A]%      Print that many spaces
75W;52W;       Print # with a newline
2M[75W;1A]     Add 2 and print that many #

```
> 1 votes

# Answer
# , ~~106~~ 95 bytes

```
function(t,l=nchar(t),n="#
#",s=" ",`&`=strrep)cat(a<-"#"&l+3,b<-c(n,s&l+2,n),s,t,s,b,a,sep="")

```

Try it online!

*-5 bytes thanks to @Dominic*, which led to further golfs.
> 1 votes

# Answer
# Vyxal `j`, 29 bytes

```
L4+\#*:\#?L½›꘍m:„W2\#ð+Ḃ?$++Ṁ

```

Try it Online!

For some reason Vertical mirror and center doesn't work
> 1 votes

# Answer
# APL (Dyalog Unicode), 19 bytes

```
(⍉⍪⍪⊣)/'##  ',⊂∘⍉∘⍪

```

Try it online!
> 1 votes

# Answer
# Stax, 14 bytes

```
≡┼ö▓ú¡êqct╜R"Γ

```

Run and debug it
> 1 votes

# Answer
# Thunno 2 `N`, 16 bytes

```
ðṛ[l'#×;lṣ;]'#ṛⱮ

```

Try it online!

#### Explanation

```
ðṛ[l'#×;lṣ;]'#ṛⱮ  # Implicit input
ðṛ                # Surround by spaces
  [    ;  ;]      # Apply parallelly, and wrap into a list:
   l'#×          '#   [0]  length * "#"
        lṣ        #   [1]  length * " "
                  #   [2]  leave TOS
            '#ṛ  '# Surround each by "#"s
               Ɱ  # Palindromise the list

```
> 1 votes

# Answer
# Ruby `-nl`, 53 bytes

```
s="# %s #"
puts h=?#*(4+l= ~/$/),s%b=' '*l,s%$_,s%b,h

```

Attempt This Online!
> 1 votes

# Answer
# PowerShell, ~~84~~ 82 bytes

```
$l=$input.length+4;$p='#'*$l;$s=' '*$l;$p,$s,"  $input  ",$s,$p-replace'^ | $','#'

```
> 0 votes

# Answer
# Lua, 90 bytes

```
a=arg[1]h="#"s=" "t="\n"..h c=h:rep(#a+4)..t..s:rep(#a+2)..h..t..s print(c..a..c:reverse())

```
> 0 votes

# Answer
# C#, 116 110 bytes

```
s=>{string r="\n".PadLeft(s.Length+5,'#'),p="#".PadRight(s.Length+3,' ')+"#\n";return r+p+"# "+s+" #\n"+p+r;};

```

Ungolfed:

```
s=>
{
    string r = "\n".PadLeft(s.Length + 5, '#'),         //the first line, made of '#'s
        p = "#".PadRight(s.Length + 3, ' ') + "#\n";    //the second line
    return r + p + "# " + s + " #\n" + p + r;           //output is simmetrical
};

```

Initial version:

```
s=>{int l=s.Length;string r=new string('#',l+4)+"\n",p="#"+new string(' ',l+2)+"#\n";return r+p+"# "+s+" #\n"+p+r;};

```

Full program with test cases:

```
using System;

namespace SurroundStringWithHashes
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string,string>f= s=>{int l=s.Length;string r=new string('#',l+4)+"\n",p="#"+new string(' ',l+2)+"#\n";return r+p+"# "+s+" #\n"+p+r;};

            Console.WriteLine(f("Hello World"));
            Console.WriteLine(f("Programming Puzzles & Code Golf"));
        }
    }
}

```
> 0 votes

# Answer
## Racket 172 bytes

```
(λ(s)(let((n(string-length s))(p #\space)(g(λ(l c)(make-string l c))))(display(string-append
(g(+ 4 n)#\#)"\n#"(g(+ 2 n)p)"#\n# "s" #\n#"(g(+ 2 n)p)"#\n"(g(+ 4 n)#\#)))))

```

Ungolfed:

```
(define (f s)
  (let ((n (string-length s))
        (p #\space)
        (g (λ (l c) (make-string l c))))
    (display (string-append (g (+ 4 n) #\#)
                            "\n#"
                            (g (+ 2 n) p)
                            "#\n# "
                            s
                            " #\n#"
                            (g (+ 2 n) p)
                            "#\n"
                            (g (+ 4 n) #\#)
                            ))))

```

Testing:

```
(f "This is a test" )

```

Output:

```
##################
#                #
# This is a test #
#                #
##################

```
> 0 votes

# Answer
# SmileBASIC, 73 bytes

```
LINPUT S$L=LEN(S$)+2O$="#"+" "*L+"#
T$="#"*(L+2)?T$?O$?"# ";S$;" #
?O$?T$

```
> 0 votes

# Answer
## C (gcc) 165 bytes

```
f(*s){i,j;c='#';for(j=0;j<5;j++){if(j==0||j==4){for(i=0;i<strlen(s)+2;i++)printf("#");}else if(j==2) printf("#%s#",s);else printf("#%*c",(strlen(s)+1),c);puts("");

```

Ungolfed version

```
void  f(char *s)
{
    int i,j;
    char c='#';

    for(j=0;j<5;j++)
    {
       if(j==0||j==4)
       {
         for(i=0;i<strlen(s)+2;i++)
           printf("#");
       }
       else
        if(j==2)
         printf("#%s#",s);
      else
        printf("#%*c",(int)(strlen(s)+1),c);

   puts("");
}

```
> 0 votes

# Answer
# Python 3, 66 bytes

```
lambda x:("###### %s ######\n\n\n\n"%' ## '.join(f" {x} ")*5)[::5]

```

Try it online!
> 0 votes

# Answer
# Regenerate, 38 bytes

```
(\#{#~1+4})(\n# {#~1+2}#\n)# $~1 #$2$1

```

Takes the string as a command-line argument. Try it here!

### Explanation

Spaces are replaced by underscores so they're easier to see.

```
(         )                             Group 1: top row
 \#                                      A literal hash character
   {     }                               repeated
    #~1                                  len(input)
       +4                                + 4 times
           (              )             Group 2: second row (plus newlines)
            \n#                          Newline followed by hash
               _{     }                  followed by space repeated
                 #~1+2                   len(input) + 2 times
                       #\n               followed by hash and another newline
                                        Middle row:
                           #_            Hash followed by space
                             $~1         followed by input
                                _#       followed by space and another hash
                                        Final two rows:
                                  $2     Group 2 again
                                    $1   Group 1 again

```
> 0 votes

# Answer
# Japt `-h`, 17 bytes

```
8Æ=z ®i" #"gXz4}R

```

Try it
> 0 votes

# Answer
# Python 3, 68 bytes

```
s=input()
n=len(s)+2
v='#'*n+'##\n#'+' '*n+'#\n#'
print(v,s,v[::-1])

```

Try it online!
> 0 votes

# Answer
# Java (JDK), 121 bytes

```
i->{int l=i.length()+2;return "#".repeat(l+2)+"\n#"+" ".repeat(l)+"#\n# "+i+" #\n#"+" ".repeat(l)+"#\n"+"#".repeat(l+2);}

```

Try it online!
> 0 votes

# Answer
# Vyxal `j`, 112 bits<sup>v2</sup>, 14 bytes

```
L⇧‛# •½pøĊ\#vø.∞

```

Try it Online!

I know I said I love parallel apply, but I didn't actually need it here lol.

## Explained

```
L⇧‛# •½pøĊ\#vø.∞
  ‛# •            # Repeat each character in the string "# "
L⇧                # (len input) + 2 times
      ½           # Split into two halves - a string of #s and spaces
       p          # Prepend the input
        øĊ        # And horizontally centre so that the input has enough spacing on both sides
          \#vø.   # Prepend and append "#" to each string
               ∞  # And mirror it, not mirroring the centre item
# The j flag joins on newlines

```

Created with the help of Luminespire.
> 0 votes

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