title: Restricted-source, take this!

text:
# Question
Title: Restricted-source, take this!
a.k.a. You Can Output Anything With Labyrinth Or Hexagony™

## Challenge

In a recent challenge, I could print any character with only half of the allowed digits with very small character count, by abusing the "digit commands" and modulo-256 output function. Now, it's about time to make a general metagolfer for this kind of challenges.

For the sake of simplicity, we only consider Labyrinth programs of the form `<digits>.@`, i.e. construct a number, print it modulo 256 as character code, and halt. Also, the sequence of digits acts exactly like a number literal in this case.

Now let's assume we want to solve a challenge in the form of:

> Given the characters `.@` and a subset of `0-9`, print a character.

Given a subset of digits `D` and the target character `c`, find the **shortest** number `N` which will solve the hypothetical challenge above. In other words, `N` should satisfy the following:

* All the digits of `N` are in `D`.
* The Labyrinth program `N.@` prints the character `c`, i.e. `N % 256 == ord(c)`.
    + The byte value of `c` can be anything between 1 and 255 inclusive.
* Out of all possible `N`s satisfying the above, your program should output one that has the shortest length. If there are multiple possible answers, your program is free to output any of them.

You may take `c` as a character or an integer (charcode), and digits in `D` as integers or digit characters. Also, you may assume `D` is already sorted.

Assume the answer exists. Note that some conditions will lead to "no answer", e.g. only odd digits are allowed but you need to print an even character, or vice versa. You may assume that such conditions will never be given as input.

Standard rules apply. The shortest code in bytes wins.

## Test cases

The value of `c` is given as its character code.

```
D = [1, 2, 3, 4, 5]
c = 1 => N = 1
c = 57 => N = 313
c = 254 => N = 254
c = 100 => N = 1124 or 4452
c = 107 => N = 1131, 2155, 2411, or 3435

D = [1, 2, 4, 6, 8]
c = 58 => N = 826
c = 71 => N = 1111111
c = 255 => N = 26111

D = [7]
c = 49 => N = 777777

```

# Answer
# JavaScript (ES6), 46 bytes

*Saved 6 bytes thanks to @Neil*

Expects `(D)(c)`, where `D` is a string of digits and `c` is an integer.

```
D=>c=>eval(`for(;/[^${D}]/.test(c);)c+=256;c`)

```

Try it online!
> 7 votes

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

```
Ɠ+⁹$Dḟ³Ɗ¿

```

Try it online!

-1 byte thanks to Jonathan Allan

Full program that takes `D` as the first argument and `c` in STDIN

## How it works

```
Ɠ+⁹$Dḟ³Ɗ¿ - Main link. Takes D on the left
Ɠ         - Read c from STDIN, set N = c
        ¿ - While:
       Ɗ  -   Condition:
    D     -     Digits of N
     ḟ³   -     Remove all elements of D
                This is an empty list (falsey) iff all digits of N are in D
   $      -   Body:
 +⁹       -     Add 256 to N

```
> 6 votes

# Answer
# Scala, 59 bytes

```
d=>n=>Stream.from(1)find(x=>s"$x".forall(d.toSet)&x%256==n)

```

Try it in Scastie!

Just a brute force solution.
> 3 votes

# Answer
# Japt, ~~13~~ 12 bytes

Takes `D` as an array and `c` as an integer, in reverse order.

```
@ìkV}f@±X©G²

```

Try it
> 3 votes

# Answer
# Charcoal, 19 bytes

```
ＮθＷ⁻⪪Ｉθ¹⪪η¹≧⁺²⁵⁶θＩθ

```

Try it online! Link is to verbose version of code. Takes input of `N` and `D` as a string. Explanation:

```
Ｎθ

```

Input `N` as an integer.

```
Ｗ⁻⪪Ｉθ¹⪪η¹

```

Filter out the digits of `D` from the digits of `N`. While some remain, ...

```
≧⁺²⁵⁶θ

```

... add 256 to `N`.

```
Ｉθ

```

Output the final value of `N`.
> 3 votes

# Answer
# Stax, 8 bytes

```
πdµ∞╔▓|▒

```

Run and debug it

## Explanation

```
WcEx-!CVB+
W          loop forever
 c         copy c
  E        get digits
   x       push D
    -      set difference
     !C    if empty, break out of the loop
       VB+ else add 256

```
> 3 votes

# Answer
# , 29 24 22 bytes

```
(]256&+~0 e.e.~&":)^:_

```

Try it online!

-2 thanks to Bubbler

Call it like: `1 2 3 4 5 f 57`, which returns 313.

* `]256&+~...^:_` Keep adding 256 while...
* `0 e.e.~&":` There is a digit of the right arg that's not in the left arg.
> 2 votes

# Answer
# Haskell, ~~38~~ 34 bytes

* -4 bytes thanks to xnor, for using `until`.

```
f d=until(all(`elem`d).show)(+256)

```

Try it online!

Takes `d` as a list of `Chars` (i.e. a `String`) and `c` as an integer.
> 2 votes

# Answer
# Retina, 36 bytes

```
"$<%'"~L$`.+$
/[^$&]/+`.+¶$$.($*257*

```

Try it online! Takes `N` and `D` on separate lines but test suite splits on `,` for convenience. Explanation:

```
"$<%'"~`

```

Evaluate the following generated Retina program passing in only `N` as input.

```
L$`.+$

```

Use `D` to generate the Retina program.

```
/[^$&]/+`

```

The generated program repeats while `N` contains a digit not in `D`.

```
.+¶$$.($*257*

```

Each loop of the generated program adds `256` to `N`. This is a little unclear due to the quoting. The generated program looks like this:

```
/[^12468]/+`.+
$.(*_[256 more `_`s]

```

The `*_` converts `N` to unary. The 256 `_`s then effectively adds 256, after which the `$.(` converts the sum to decimal.
> 1 votes

# Answer
# Python 3, 45 bytes

```
f=lambda d,c:f(d,c+256)if{*str(c)}-{*d}else c

```

Try it online!

My first attempt at golfing in Python (or, for that matter, in an imperative language). Suggestions are welcome! Especially about conditionals, I don't really know all those `and` and `or` tricks, but I almost never see `if`-`else` used in Python codegolfing, so I guess I'm doing something wrong :).

Also, I had to increase the default recursion limit for some testcases, I hope that's ok.
> 1 votes

# Answer
# Python 3, 70 bytes

```
d,n=set(input()),ord(input())
while not set(str(n))<=d:n+=256
print(n)

```

Try it online! Simple brute-force solution.
> 1 votes

# Answer
# Python 3, 82 bytes

```
f=lambda d,c,k=0:(all(_ in d for _ in str(k))and chr(k%256)==c)and k or f(d,c,k+1)

```

Try it online!

Plain brute force, takes `D` as a string of the numbers and `c` as a character.
> 0 votes

# Answer
# , 68 bytes

```
f=function(D,C)"if"(all((utf8ToInt(paste(C))-48)%in%D),C,f(D,C+256))

```

Try it online!

Fails in TIO for larger test-cases.

---

**without recursion:**

### , 75 bytes

```
function(D,C){while(T%%256-C|any(!(utf8ToInt(paste(+T))-48)%in%D))T=T+1;+T}

```

Try it online!
> 0 votes

---
Tags: code-golf, math, number-theory
---


title: Road golf through the mountains

text:
# Question
Title: Road golf through the mountains
You have a bunch of cities on a grid which you wish to link up. Roads can be placed on any tile that doesn't contain a city, and connect to all roads or cities adjacent to them, vertically, horizontally or diagonally.

Roads can link up via cities, for example

```
C
 \
  C-C

```

is fully linked up.

However, there are some mountains in your way. Roads can't pass through mountains, and have to go around them. In my examples/testcases, these will be be marked as M.

With

```
  M
C M C
  M

```

Something like

```
  ^
 /M\
C M C
  M

```

Will have to be done.

Roads can go through mountain passes diagonally, for example

```
C M
 \M
MM\
   C

```

is valid.

# Your challenge

Given an arrangement of cities and mountains, output the minimum number of roads needed to connect them all.

# Rules

Input can be taken however you like, as ascii-art, a matrix, the positions of the cities and mountains, etc.

You may assume that no adjacent cities (like `CC`) will ever be inputted.

# Testcases

Note: These are formatted as ASCII-art.

```
C C
=> 1

C C

  C
=> 1 (in the centre)

C M C
=> 3

MMC
  M
C M
=> 1

MMMMMMMMM
MCMCM   M
M M M M M
M M   M M
M MMMMM M
M       M
MMMMMMMMM
=> 15

C   C
  C

  C
C   C
=> 5

MMM
CMC
MMM
=> 5

     C
MMMMMMMMMM
C        C
=> 11

```

# Answer
# Jelly, 29 bytes

```
;_þ`²§<3æ*L$Ȧ
FṀ‘Żṗ2ḟẎŒPçƇḢḢL

```

Try it online!

Uses ovs' method, be sure to give them an upvote!

Takes the input as a pair `[a, b]` where `a` is a list of 1 indexed co-ordinates of cities and `b` a list of 1 indexed co-ordinates of mountains

This is *stupidly* slow. For an \\$n \times m\\$ matrix with \\$x\\$ spaces, this has a lower bound of \\$O(2^{\max(n,m)^2-x})\\$, and that doesn't factor in the speed of Jelly's matrix power, which isn't fast. This doesn't finish on TIO for any valid input

# Jelly, 36 bytes

```
;’_þ`²§<3æ*L$Ȧ
Ż€ZUƊ4¡µœẹ0ŒPçƇœẹ1$ḢL

```

Try it online!

Also *incredibly* slow. For an input of size \\$n\times m\\$ with \\$x\\$ spaces, this has an absolute lower bound of \\$O(2^{2(n+m)+x})\\$, and that doesn't factor in the speed of Jelly's matrix power, or the fact that it has to calculate \\$2^{2(n+m)+x}\\$ Cartesian products with the number of cities in the input.

There are various optimisations you can do if you know the input before hand. For example, this is a much faster version that works for inputs that can be constructed as going over the "top" of the mountains.

# Jelly, 34 bytes

```
;’_þ`²§<3æ*L$Ȧ
Ż€ZUƊ4¡µœẹ0ŒPçƇŒṪḢL

```

Try it online!

Exactly the same as the 36 byte version, but takes input as a matrix where `0` is a space, `1` is a city and `[]` is a mountain. For example, `C M C` is `[[1, 0, [], 0, 1]]`

## How they work

```
;_þ`²§<3æ*L$Ȧ - Helper link. Takes S (indices of spaces) and C (indices of cities)
;             - Concatenate
 _þ`          - Create a subtraction table
    ²         - Square each
     §        - Sums of each
      <3      - Less than 3?
           $  - To this square matrix M:
          L   -   Get its length
        æ*    -   Raise it to that power
            Ȧ - Are all elements of the matrix non-zero?

FṀ‘Żṗ2ḟẎŒPçƇḢḢL - Main link. Takes [a, b] on the left
F               - Flatten
 Ṁ              - Maximum
  ‘             - Increment
   Ż            - Range from zero
    ṗ2          - Cartesian square
                   This gets all possible coordinates, including an outer border
       Ẏ        - Flatten the argument into a list of coords
      ḟ         - Remove the mountain + city coords from the list
        ŒP      - Powerset
            Ḣ   - Extract the list of city coords
          çƇ    - Keep the powerset elements that are truthy under the helper link
             ḢL - Take the shortest one and return its length

```

```
;’_þ`²§<3æ*L$Ȧ - Helper link. Takes S (indices of spaces) and C (indices of cities)
;              - Concatenate
 ’             - Decrement to zero index
  _þ`          - Create a subtraction table
     ²         - Square each
      §        - Sums of each
       <3      - Less than 3?
            $  - To this square matrix M:
           L   -   Get its length
         æ*    -   Raise it to that power
             Ȧ - Are all elements of the matrix non-zero?

Ż€ZUƊ4¡µœẹ0ŒPçƇœẹ1$ḢL - Main link. Takes matrix M on the left
    Ɗ4¡               - Do the following 4 times:
Ż€                    -   Prepend a zero to each row
  Z                   -   Transpose
   U                  -   Reverse
       µ              - Begin a new link with this bordered matrix M' as the argument
        œẹ0           - Get the indices of zeros
           ŒP         - Powerset
                  $   - To M':
               œẹ1    -   Get the indices of ones
             çƇ       - Keep the powerset elements that are truthy under the helper link
                   ḢL - Take the shortest one and return its length

```

The third one takes advantage of the fact `[]` is both falsey and non-zero, and replaces `œẹ1$` with `ŒṪ` which gets the indices of all truthy elements in `M'`
> 5 votes

# Answer
# 05AB1E, ~~63~~ ~~54~~ 52 bytes

Quite slow, but after some optimisation, this can now run some testcases!

```
2Føðδ.ø}©˜„ CSδQƶø0δK<®øg‰`Uæé.ΔX«Dδ-nO3‹DvDδ*O}ßĀ}g

```

Try it online!

The algorithm used has complexity \\$\mathcal{O}\left(2^{(n+2)^2} (n+2)^6\right)\\$ (for a grid of size \\$n \times n\\$) and uses matrix multiplication (`øδ*O`), which is often incredibly slow in 05AB1E.

### How?

A slightly different interpretation of the tasks helps explaining the approach: Instead of placing roads, we can also place additional cities into the grid until all cities are connected.
The program tries all combinations of new cities in increasing order of new cities until it finds a valid solution.

To validate a given attempt we consider a graph where the vertices are cities and two cities are connected with an edge if they are vertically, horizontally or diagonally adjacent. Two cities are adjacent, iff their squared Euclidean distance is less than \\$3\\$.
This property can be used to calculate an adjacency matrix from a list of city coordinates. An undirected graph of \\$n\\$ vertices with adjacency matrix \\$A\\$ is connected, iff \\$A^n\\$ has no zeros. Example:

```
map
 C
C C

city coordinates
[0,1], [1,0], [1,2]

pairwise squared Euclidean distances
0 2 2
2 0 4
2 4 0

adjacency matrix A
1 1 1
1 1 0
1 0 1

A^3
7 5 5
5 4 3
5 3 4

min(A^3) = 3 > 0 => connected

```

Try your own example!

**Commented Code**:

```
                         # pad with spaces
2F     }                 # execute two times:
  ø                      #   transpose the grid
   ðδ.ø                  #   and surround every row with spaces

                         # get coordinates of cities and spaces
©                        # store the padded grid in the register
 ˜                       # flatten the grid
  „ CS                   # push [" ", "C"]
      δQ                 # equality table (== [[char==" ", char=="C"] for char in flat_grid])
        ƶ                # multiply each pair by its 1-based index
         ø               # tranpose
          0δK            # remove all zeros
             <           # decrement by 1
                         # Now we have a two list of coordinates of spaces and cities in the flattened grid
              ®          # get the grid from the register
               øg        # get the height (length of the tranpose)
                 ‰       # divmod each flat index with this
                         # this results into the 2d-indices
                  `      # push cities and spaces seperately on the stack
                   U     # store coordinates of cities in variable X
                         # coordinates of spaces are now on top of the stack

                         # try subsets of the spaces until we get a connected graph
æ                        # push the powerset (all subsets) of space coordinates
 é                       # sort by length
  .Δ                  }  # find the first value for which the following is truthy
    X«                   # append the existing cities to the current subset of spaces
      D                  # duplicate
       δ-                # subtraction table
         n               # square each difference
          O              # sum each pair of squared differences
           3‹            # for each number: is it less than 3?
                         # this is the adjacency matrix A
             D           # make a copy of the matrix
              v    }     # for each row in A:
               D         # duplicate current matrix
                δ*O      # matrix multiplication (for symmetric matrices)
                    ßĀ   # is the minimum not 0?

g                        # take the length of the result

```

---

# 05AB1E, 31 bytes

Takes input as lists of 1-indexed coordinates of cities and mountains. Even less efficient if the input is not square.

```
«Z>ÝãsKæé.Δ¹«Dδ-nO3‹DvDδ*O}ßĀ}g

```

Try it online!

```
«        # concatenate cities and mountains
 Z>      # maximum integer in the list + 1 (0 and +1 for padding)
   Ý     # push range from 0 to this value
    ã    # cartesian square: all 2d coordinates with values in that range
     sK  # remove all cities and mountains, this leaves the coordinates of spaces
 ...     # same as above

```
> 9 votes

# Answer
# Kotlin with JGraphT, ~~3009~~ 2984 (thanks to ophact) bytes (plus header/footer)

```
import org.jgrapht.Graph
import org.jgrapht.GraphPath
import org.jgrapht.alg.connectivity.ConnectivityInspector
import org.jgrapht.alg.shortestpath.AllDirectedPaths
import org.jgrapht.alg.shortestpath.DijkstraManyToManyShortestPaths
import org.jgrapht.graph.DefaultDirectedGraph
import org.jgrapht.graph.DefaultEdge
import org.jgrapht.graph.DefaultUndirectedGraph
import org.jgrapht.graph.builder.GraphBuilder
import kotlin.streams.asStream

sealed class P
object C:P()
object M:P()
object E:P()
object R:P()
typealias D=Pair<Int,Int>
typealias L<T> =List<T>
typealias A<T> =Array<T>
typealias F=DefaultEdge
typealias G=BooleanArray
object H:ThreadLocal<G>(){override fun initialValue()=G(1 shl(B*2)){false}}
const val B=4
fun GraphPath<D,F>.v():A<D>{val r=arrayOfNulls<D>(edgeList.size+1)
r[0]=graph.getEdgeSource(edgeList.first())
edgeList.forEachIndexed{i,e->r[i+1]=graph.getEdgeTarget(e)}
return r as A<D>}
fun A<GraphPath<D,F>>.d()=sumOf{val table=if(B<=3){G(1 shl(B*2)){false}}else{H.get().also{for(i in it.indices){it[i]=false}}}
it.v().sumOf{val hash=(it.first+1)or(it.second+1).shl(B)
if(table[hash]){0}else{table[hash]=true
1}.toInt()}}
fun j(b:GraphBuilder<D,*,*>,x:Int,y:Int){val others=(x-1..x+1).flatMap{z->(y-1..y+1).map{z to it}}
others.forEach{b.addEdge(x to y,it)}}
fun g(g:L<L<P>>):Pair<Set<D>,Graph<D,F>>{val b=DefaultDirectedGraph.createBuilder<D,F>(::DefaultEdge)
val c=mutableSetOf<D>()
g.forEachIndexed{y,r->r.forEachIndexed{x,p->when(p){C->{c+=x to y
j(b,x,y)}
E->j(b,x,y)
R->error("")}}}
val width=g[0].size
g.indices.forEach{y->if (g[y][0]==M)j(b,-1,y)
if (g[y].last()==M)j(b,width,y)}
(0 until width).forEach{x->if (g[0][x]==M)j(b,x,-1)
if (g.last()[x]==M)j(b,x,g.size)}
return c to b.buildAsUnmodifiable()}
fun t(c: Set<D>, g:Graph<D,F>):Set<D>{val d=DijkstraManyToManyShortestPaths(g).getManyToManyPaths(c,c)
val h=c.flatMap{o->c.map{o to it}}.filter{if(it.first.first==it.second.first)it.first.second>it.second.second else it.first.first>it.second.first}.associateWith{d.getPath(it.first,it.second)}.map{it.key to AllDirectedPaths(g).getAllPaths(it.key.first,it.key.second,true,it.value.length)}
val j=h.map{it.first}
val k=h.map{it.second}
val l=k.s{val m=DefaultUndirectedGraph.createBuilder<D,F>(::DefaultEdge)
m.addVertices(*c.toTypedArray())
it.mapIndexed{i,b->if(b)j[i]else null}.filterNotNull().forEach{m.addEdge(it.first,it.second)}
ConnectivityInspector(m.buildAsUnmodifiable()).isConnected}
return HashSet(l.asStream().parallel().map{it to it.d()}.min{n,o->n.second-o.second}.get().first.flatMap{it.v().asList()})}
fun a(a:String)=a.lines().map{it.map{when(it){'M'->M
'.',' '->E
'C'->C
'R'->R
else->null}}.filterNotNull()}.filter{it.isNotEmpty()}
fun l(data:L<L<P>>, route:Set<D>)=route.sumOf{if(it.second<0||it.second>data.lastIndex)return@sumOf 1
val row=data[it.second]
if(it.first<0||it.first>row.lastIndex)return@sumOf 1
if(row[it.first]==E)1.toInt()else 0}
inline fun<reified T>L<L<T>>.s(noinline test:(A<Boolean>)->Boolean)=List(size){listOf(false,true)}.c().filter(test).let{sequence{for(selection in it){yieldAll(filterIndexed { i, _->selection[i]}.c())}}}
inline fun <reified T>L<L<T>>.c()=sequence{if(isEmpty())return@sequence
val j=map{it.iterator()}.toTypedArray()
val v=j.map{it.next()}.toTypedArray()
yield(v.clone())
while(true){var i=0
while(!j[i].hasNext()){j[i]=get(i).iterator()
v[i]=j[i].next()
if(++i>lastIndex)return@sequence}
v[i]=j[i].next()
yield(v.clone())}}

fun main() {
    val art = System.`in`.bufferedReader().readText()
    val data = a(art)
    val (cities, graph) = g(data)
    val route = t(cities, graph)
    println("Length: ${l(data, route)}")
}

```

Here is the original, prior to golfing:

```
import org.jgrapht.Graph
import org.jgrapht.GraphPath
import org.jgrapht.alg.connectivity.ConnectivityInspector
import org.jgrapht.alg.shortestpath.AllDirectedPaths
import org.jgrapht.alg.shortestpath.DijkstraManyToManyShortestPaths
import org.jgrapht.graph.DefaultDirectedGraph
import org.jgrapht.graph.DefaultEdge
import org.jgrapht.graph.DefaultUndirectedGraph
import org.jgrapht.graph.builder.GraphBuilder
import java.util.concurrent.atomic.AtomicLong
import kotlin.concurrent.thread
import kotlin.streams.asStream

sealed class Place
object City : Place()
object Mountain : Place()
object Empty : Place()
object Road : Place()

typealias Coord = Pair<Int, Int>

operator fun Coord.compareTo(other: Coord): Int {
    return first.compareTo(other.first).let {
        if (it == 0)
            second.compareTo(other.second)
        else
            it
    }
}

fun <T> Collection<T>.toHashSet() = HashSet(this)

object HashTable : ThreadLocal<BooleanArray>() {
    override fun initialValue(): BooleanArray {
        return BooleanArray(1 shl (MAX_DIMEN_BITS * 2)) { false }
    }
}

const val MAX_DIMEN_BITS = 4

inline fun <reified V, E> GraphPath<V, E>.getVertexListFast(): Array<V> {
    val ret = Array<V?>(edgeList.size + 1) { null }
    ret[0] = graph.getEdgeSource(edgeList.first())
    edgeList.forEachIndexed { i, edge ->
        ret[i + 1] = graph.getEdgeTarget(edge)
    }
    @Suppress("UNCHECKED_CAST")
    return ret as Array<V>
}

fun Array<GraphPath<Coord, DefaultEdge>>.distinctSize() = sumOf { path ->
    val table = if (MAX_DIMEN_BITS <= 3) {
        BooleanArray(1 shl (MAX_DIMEN_BITS * 2)) { false }
    } else {
        HashTable.get().also {
            for (i in it.indices) {
                it[i] = false
            }
        }
    }
    path.getVertexListFast().sumOf {
        val hash = (it.first + 1) or (it.second + 1).shl(MAX_DIMEN_BITS)
        if (table[hash]) {
            0
        } else {
            table[hash] = true
            1
        }.toInt() /* stupid overload resolution */
    }
}

fun joinUp(builder: GraphBuilder<Coord, *, *>, x: Int, y: Int) {
    val others = (x - 1 .. x + 1).flatMap { otherX -> (y - 1 .. y + 1).map { otherY -> otherX to otherY } }
    others.forEach {
        builder.addEdge(x to y, it)
    }
}

fun createGraph(grid: List<List<Place>>): Pair<Set<Coord>, Graph<Coord, DefaultEdge>> {
    val builder = DefaultDirectedGraph.createBuilder<Coord, DefaultEdge> { DefaultEdge() }
    val cities = mutableSetOf<Coord>()
    grid.forEachIndexed { y, row ->
        row.forEachIndexed { x, place ->
            when (place) {
                City -> {
                    cities += x to y
                    joinUp(builder, x, y)
                }
                Mountain -> {
                }
                Empty -> joinUp(builder, x, y)
                Road -> error("Cannot pre-supply Roads")
            }
        }
    }
    val width = grid.first().size
    grid.indices.forEach { y ->
        if (grid[y].first() == Mountain)
            joinUp(builder, -1, y)
        if (grid[y].last() == Mountain)
            joinUp(builder, width, y)
    }
    (0 until width).forEach { x ->
        if (grid.first()[x] == Mountain)
            joinUp(builder, x, -1)
        if (grid.last()[x] == Mountain)
            joinUp(builder, x, grid.size)
    }
    return cities to builder.buildAsUnmodifiable()
}

fun joinCities(cities: Set<Coord>, graph: Graph<Coord, DefaultEdge>): Set<Coord> {
    val allPathsAlgo = AllDirectedPaths(graph)
    val dijkstraAlgo = DijkstraManyToManyShortestPaths(graph)
    val shortestPaths = dijkstraAlgo.getManyToManyPaths(cities, cities)
    val sourceTargets = cities.flatMap { outer -> cities.map { outer to it } }.filter { it.first > it.second }
    val shortestLengths = sourceTargets.associateWith {
        shortestPaths.getPath(it.first, it.second)
    }
    val allShortestPathsWithKey = shortestLengths.map {
        it.key to allPathsAlgo.getAllPaths(it.key.first, it.key.second, true, it.value.length)
    }
    val allShortestPathsKeys = allShortestPathsWithKey.map { it.first }
    val allShortestPaths = allShortestPathsWithKey.map { it.second }
    val i = AtomicLong()
    val (total, allPathsProduct) = allShortestPaths.selectiveCartesianProduct { selection ->
        val builder = DefaultUndirectedGraph.createBuilder<Coord, DefaultEdge> { DefaultEdge() }
        builder.addVertices(*cities.toTypedArray())
        selection.mapIndexed { i, bool -> if (bool) allShortestPathsKeys[i] else null }.filterNotNull().forEach { builder.addEdge(it.first, it.second) }
        val selectionGraph = builder.buildAsUnmodifiable()
        ConnectivityInspector(selectionGraph).isConnected
    }
    val startTime = System.currentTimeMillis()
    val counterThread = thread(true) {
        try {
            while (true) {
                Thread.sleep(1000)
                val progress = i.getOpaque()
                val percent = (progress.toDouble() / total.toDouble()) * 100f
                print("Progress: $progress\t/ $total\t($percent%)\t(${System.currentTimeMillis() - startTime} ms)\r")
            }
        } catch (e: InterruptedException) {
            println()
        }
    }
    val ret = allPathsProduct
        .asStream()
        .parallel()
        .map { (it to it.distinctSize()).also { i.incrementAndGet() } }
        .min { left, right -> left.second - right.second }.get().first.flatMap { it.getVertexListFast().asIterable() }.toHashSet()
    counterThread.interrupt()
    counterThread.join()
    return ret
}

fun artToData(art: String) = art.lines().map {
    it.map { char ->
        when (char) {
            'M' -> Mountain
            '.', ' ' -> Empty
            'C' -> City
            'R' -> Road
            else -> null
        }
    }.filterNotNull()
}.filter { it.isNotEmpty() }

fun plotRoute(data: List<List<Place>>, route: Set<Coord>): List<List<Place>> {
    val width = data[0].size
    val emptyLine = List<Place>(width + 2) { Empty }
    val newData = mutableListOf(emptyLine.toMutableList(), *data.map { mutableListOf(Empty, *it.toTypedArray(), Empty) }.toTypedArray(), emptyLine.toMutableList())
    for (point in route) {
        if (newData[point.second + 1][point.first + 1] == Empty) {
            newData[point.second + 1][point.first + 1] = Road
        }
    }
    return newData
}

fun routeLength(data: List<List<Place>>, route: Set<Coord>): Int = route.sumOf { point ->
    if (point.second < 0 || point.second > data.lastIndex) return@sumOf 1
    val row = data[point.second]
    if (point.first < 0 || point.first > row.lastIndex) return@sumOf 1
    if (row[point.first] == Empty) 1.toInt() /* needed due to overload ambiguity */ else 0
}

fun dataToArt(data: List<List<Place>>) = buildString {
    data.forEach { row ->
        row.forEach { place ->
            append(
                when (place) {
                    City -> 'C'
                    Empty -> '.'
                    Mountain -> 'M'
                    Road -> 'R'
                }
            )
        }
        append('\n')
    }
}

inline fun <reified T> List<Collection<T>>.selectiveCartesianProduct(noinline test: (Array<Boolean>) -> Boolean): Pair<Long, Sequence<Array<T>>> {
    val selections = List(size) { listOf(false, true) }.cartesianProduct().filter(test)
    val total = selections.sumOf { selection ->
        val selected = filterIndexed { i, _ -> selection[i] }
        if (selected.isEmpty()) 0 else selected.fold(1L) { acc, value -> acc * value.size }
    }
    return total to sequence {
        for (selection in selections) {
            yieldAll(filterIndexed { i, _ -> selection[i] }.cartesianProduct())
        }
    }
}

inline fun <reified T> List<Iterable<T>>.cartesianProduct() = sequence {
    if (isEmpty()) return@sequence
    val iterators = map { it.iterator() }.toTypedArray()
    val values = iterators.map { it.next() }.toTypedArray()
    yield(values.clone())

    while (true) {
        var i = 0
        while (!iterators[i].hasNext()) {
            // reset current iterator, move on to check next one
            iterators[i] = get(i).iterator()
            values[i] = iterators[i].next()
            if (++i > lastIndex)
                return@sequence
        }
        values[i] = iterators[i].next()
        yield(values.clone())
    }
}

fun main() {
    val art = System.`in`.bufferedReader().readText()
    val data = artToData(art)
    val (cities, graph) = createGraph(data)
    val route = joinCities(cities, graph)
    println("Length: ${routeLength(data, route)}")
    val newData = plotRoute(data, route)
    println(dataToArt(newData))
}

```

The algorithm is very intractable: with the sample with 6 cities, it takes ~300 minutes of CPU time on my high-end desktop

Note that if your input data is longer than 14 on any dimension, you have to increase MAX\_DIMEN\_BITS.

Input is sent to stdin followed by EOF (^D) as ASCII art.
> 7 votes

# Answer
# Python 3 \+ numpy, 325 bytes

A (slightly faster) port of my 05AB1E solution. The computational complexity is still the same, but especially the matrix operations are faster.

```
from itertools import*
from numpy import*
def f(G):
 E=enumerate;k=[' '];p,c,*s=[k*len(G[0])],[]
 for y,r in E([k+r+k for r in p+G+p]):
  for x,v in E(r):[s,p,p,c][ord(v)%4]+=[y,x],
 for i in count():
  for N in combinations(s,i):
   v=array(c+[*N]);A=sum((v-v[:,None])**2,axis=2)<3
   for _ in v:A=A@A
   if A.min():return i

```

Try it online!

Ungolfed full program:

```
import itertools, sys
import numpy as np

grid = [list(line) for line in sys.stdin.read().splitlines()]
print(grid)
width = len(grid[0])

# pad with spaces on all sides
padding = [[' '] * width]
grid = [[' ', *row, ' '] for row in padding + grid + padding]

# get the coordinates of cities and empty spaces
cities = [[y, x] for y, row in enumerate(grid) for x, v in enumerate(row) if 'C' == v]
spaces = [[y, x] for y, row in enumerate(grid) for x, v in enumerate(row) if ' ' == v]

for i in range(len(spaces)):
  # Iterate over all combinations of i new cities
  for new_cities in itertools.combinations(spaces, i):
    vertices = np.array([*cities, *new_cities])
    adjacency = (np.sum((vertices - vertices[:, None])**2, axis=-1)<3)
    if (np.linalg.matrix_power(adjacency, adjacency.shape[0]) > 0).all():
      print(i)
      exit()

```

Try it online!
> 3 votes

---
Tags: code-golf, grid, path-finding, connected-figure
---


title: Find the HTTP status code

text:
# Question
Title: Find the HTTP status code
Given the name of an HTTP status code, such as `OK` or `Continue`, output or return the corresponding number. Your code is limited to **200 bytes**, and the winner is the answer that correctly finds the number for the most status codes.

For this challenge, the status codes your program should handle are:

```
100 Continue
101 Switching Protocols
200 OK
201 Created
202 Accepted
203 Non-Authoritative Information
204 No Content
205 Reset Content
206 Partial Content
300 Multiple Choices
301 Moved Permanently
302 Found
303 See Other
304 Not Modified
305 Use Proxy
307 Temporary Redirect
400 Bad Request
401 Unauthorized
402 Payment Required
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable
407 Proxy Authentication Required
408 Request Timeout
409 Conflict
410 Gone
411 Length Required
412 Precondition Failed
413 Request Entity Too Large
414 Request-URI Too Long
415 Unsupported Media Type
416 Requested Range Not Satisfiable
417 Expectation Failed
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
505 HTTP Version Not Supported

```

Test cases:

```
Continue        -> 100
OK              -> 200
No Content      -> 204
Not Found       -> 404

```

For invalid status codes or ones not supported by your program, any behavior is fine. Input and output can be in any reasonable format. If there is a tie, the shortest program that can support that many status codes wins.

# Answer
# Node.js, <sup> ~~135 126 125~~ </sup> 123 bytes, score 40

*Saved 2 bytes by using unprintable characters, as suggested by @dingledooper*

```
s=>Buffer('~>/6%sH~~d4~\\~i~~,~~~~~.~~~~n)W*~~~~;~CR@M"~1E~$~ _Z9~')[parseInt(s[0]+s[4]+s[19],34)*57%65]*209%523

```

Try it online!

### Decoding example

Let's consider the input string `"Internal Server Error"`.

We extract the characters at indices \\$0\\$, \\$4\\$ and \\$19\\$ and concatenate them together:

```
**I**nte**r**nal Server Err**o**r
^   ^              ^
```

This gives `"Iro"`.

We parse this string as a base-34 value, leading to \\$\color{blue}{21750}\\$.

**Note:** For many shorter entries, some characters are undefined. This leads to strings such as `"Piundefined"` and much higher integers.

We apply the hash formula:

$$(\color{blue}{21750}\times57)\bmod65=5$$

We extract the corresponding character from the lookup string (which is a `"s"`) and take its ASCII code, leading to \\$\color{blue}{115}\\$.

We apply another black magic formula to turn this into the final HTTP status code:

$$(\color{blue}{115}\times209)\bmod 523=500$$

Given an HTTP status code \\$c\\$, the ASCII code \\$k\\$ of the encoding character is given by the following reverse formula:

$$k = \lfloor c / 100\rfloor \times 23 - (c \bmod 100) \times 5$$

Try it online!

---

# Node.js, 84 bytes, score 40

With a built-in.

```
s=>Object.keys(c=require('http').STATUS_CODES).find(k=>c[k]==s)||413+(~s.length/6&3)

```

Try it online!

### How?

There are 3 strings that do not match the values stored in `STATUS_CODES` for codes **413**, **414** and **416**. For these ones, we use the length of the input to figure out the correct answer.

```
 string                            | len | ~len/6  | &3 | +413
-----------------------------------+-----+---------+----+------
 "Request Entity Too Large"        |  24 | -4.1667 |  0 |  413
 "Request-URI Too Long"            |  20 | -3.5000 |  1 |  414
 "Requested Range Not Satisfiable" |  31 | -5.3333 |  3 |  416

```
> 35 votes

# Answer
# Python 3, 68 bytes, score: 40

A cheap builtin answer.

```
lambda s:+http.HTTPStatus[re.sub('\W','_',s.upper())]
import http,re

```

Try it online!

# Python 2, ~~131~~ ~~119~~ ~~115~~ 104 bytes, score: 40

A nicer method with the same score, using a magic formula. @Arnuald's answer had a really nice way of calculating the status code, which saves me *a ton* of bytes.

```
lambda s:ord('?".\, ;?Zd?s>M?C6/W4?)??*??H1@R???i_??n$?9E?%'[hash(s)%762%517%233%56])*209%523

```

Try it online!
> 17 votes

# Answer
# Jelly, score 40, tiebreak score 61 bytes

```
ȷ;€ȷḥ€ɠḋ“^,fḷɱ⁹⁴ƒẈ®ẒỤĖṅ}PG¬Ƭṙ⁴&©ẉ}Ḳḍƙḋ¥ȤẊḌÐẈ’b123¤%127b28ḅ³+³

```

Try it online!

# Jelly, score 40, tiebreak score 58 bytes, in collaboration with @Arnauld and @ChartZ Belatedly

```
ȷ;€ȷḥ€ɠḋ“Rḳk_ṇṙƤĊ⁻ƒƓḍ¹⁹¡Ɱṫ°ė÷Ḣ4[⁶æȥ.’b41¤ị“£¬®Ø©‘Ḷ+"J×³ƊF¤

```

Try it online!

## Discussion

I found an almost asymptotically optimal algorithm for solving this sort of problem (mapping a set of given inputs into specific numbers, not caring about other inputs) a while ago. The algorithm takes a few bytes to express in Jelly, but the savings in not having any wasted bytes actually describe the outputs are worthwhile, making this the currently shortest non-builtin-based solution. (As a side note, it may well be worth adding the algorithm in question as a Jelly builtin, which would save 11-13 bytes from this program depending on how it was implemented; it seems likely to come up in the future.)

The algorithm basically generates programs that work by running a large number of hash functions on the input to produce a vector of hashes, then taking the dot product of that vector with a hardcoded vector over a finite field. (When implementing this in Jelly, we use a finite field of prime order, because it doesn't have builtins for dealing with other sorts of finite field.) It turns out that the minimum length of a hardcoded vector that solves this problem is almost always equal to the number of input/output pairs, and the maximum size of the vector elements is the order of the finite field, so the amount of storage used by this is equal to the amount of storage needed to store the possible outputs (thus asymptotically optimal). Adding a new HTTP status code to this program would typically cost less than a byte on average per code, unless it was outside the range of the existing codes (e.g. here's how to add "I'm a teapot" to the original program at the cost of only one more byte).

I've since automated a program generator that generates Jelly programs to solve these programs. So this codegolf submission was pretty much entirely automatically generated. This is the generation program I used (configured to generate a solution to this problem). The Sage program it generates, when run, generates this Jelly program which generates the program written above.

The reason I've described the algorithm as "almost asymptotically optimal" is that it has two failure modes. One is mathematical; the algorithm involves solving a set of simultaneous equations, which can almost always be solved using a vector whose length is equal to the number of input/output pairs, but rarely and randomly have no solution (the odds of this become smaller as the size of the codomain becomes larger, and when it happens you can "reroll" by adding an arbitrary extra input/output pair, leading to a slightly larger program). The other is a deficiency of Jelly; the shortest way in Jelly to describe a list of integers drawn from a uniform random distribution is to use a large constant integer and base-convert it, but this mechanism is incapable of expressing lists with a leading 0 (the program generator I've written above doesn't attempt to fix this problem itself, but the odds of it happening are again just 1 in the size of the output domain).

## Explanation (original version)

Here's how this program is implemented in Jelly:

```
ȷ;€ȷḥ€ɠḋ“…’b123¤%127b28ḅ³+³
    ḥ                        Hash
      ɠ                        a line taken from standard input
                             using
     €                         each of the following hash configurations:
ȷ €                              each number from 1 to 1000 (the salt)
 ;                               concatenated with
   ȷ                             1000 (the codomain of the hash function);
       ḋ                     take the dot product of the resulting hashes and
               ¤               a constant calculated by
        “…’                      converting a large constant integer
           b123                  to a list of base 123 digits;
                %127         take the resulting dot product modulo 127,
                    b28      convert to a list of base 28 digits,
                       ḅ³    interpret as base 100 digits,
                         +³  and add 100

```

Everything up to the %127 is just the implementation of our general-purpose input→output mapper. The `b28ḅ³+³` after that implements the inverse of a function that maps HTTP status codes from 100…505 onto integers in the range 0…117; producing a smaller codomain allows for a smaller hardcoded vector. (The basic idea is to note that the last two digits of the status code are never greater than 27, so the double base conversion "closes some of the gaps" in the range of possible outputs.)

As it happens, our hardcoded vector didn't contain any of the values 123, 124, 125, or 126, so it was possible to use 123 as the base for that base conversion. (The gain from this is minimal; if Jelly had a builtin for this algorithm, you'd hardcode that the "123" and "127" were the same number.)

There's no particular algorithmic reason for the codomain of the hash function to be 1…1000 (any sufficiently large codomain would do), and calculating 1000 hashes is likewise not algorithmically useful because we only use the first 40 of them. This is just a tiny byte saving: 1000 has a 1-byte representation, whereas most other numbers can't be written in a single byte.

Incidentally, the reason we take input from standard input is that 100 (the lowest HTTP status code) can be represented in 1 byte in Jelly if the program has no command-line arguments, but takes 3 bytes if there are any command-line arguments. There wasn't a byte cost to doing anything because I needed to take explicit input anyway (attempting to take implicit input would run into a parse ambiguity that would need a byte to fix, so the extra byte for explicit input doesn't cost).

## Explanation (improved version)

@Arnauld suggested, instead of the base-28 calculation used in the previous version, to generate a list of the 41 possible (return values + 306) (trying to omit 306 from the list would cost more bytes than simply just adding it; and including it also gives us a prime number of possible outputs, which we need to be able to do finite field operations over the range of outputs in Jelly).

We can generate a list of the values like this:

```
“£¬®Ø©‘Ḷ+"J×³ƊF
“£¬®Ø©‘          [2,7,8,18,6]
       Ḷ         range from 0 to n-1, i.e. [[0,1],[0,1,…,6],…]
             Ɗ   group the three preceding bultins together
        +        add
           ×³      100 times
          J        the index of
         "         each sublist to every element of the sublist
              F  flatten

```

In other words, we're adding 1 to each element of the first list, 2 to each element of the second list, etc., 100 times, thus effectively adding \[100,200,300,400,500\] to each element of the corresponding sublist of \[\[0,1\],\[0,1,…,6\],…\] to produce \[\[100,101\],\[200,201,…,206\],…\], which can be flattened to produce the list of status codes we want.

I originally generated the list using slightly different code (doing the addition 100 times rather than adding 100 times the index), and connected the list to the original program using a newline and `ị¢`;  is wrapping indexing into a list (thus contains an implicit "modulo 41"; 41 is the size of the finite field we're using in this version and also the number of status codes in the list), and `¢` tells Jelly to look at the previous line to find the list to index into. However, @ChartZ Belatedly realised that rearranging the list generation like this, although it still takes the number of bytes, makes the list generation into a nilad followed by a sequence of monads. This makes it possible to treat the entire list generation like a literal constant by using a single `¤` byte, which is a less general method of specifying the grouping than the a newline and `¢` were, but worth it as it's a byte shorter overall.

This approach, where almost all the outputs are used, costs several bytes for the more complex post-processing, but makes the hardcoded vector require substantially less storage because the numbers in it now only go up to 40 rather than 122, so it saves more bytes than it costs.
> 10 votes

# Answer
# Ruby `-n -l -rnet/http/status`, 31 bytes, score: 37

```
p Net::HTTP::STATUS_CODES.key$_

```

Try it online!

Another cheap builtin answer. Not a perfect score because the reason phrases in the library are taken from RFC 7231 instead of the older RFC 2616 (as used in the question).

---

# Ruby `-n -l -rnet/http/status`, 47 bytes, score: 40

```
p Net::HTTP::STATUS_CODES.key($_)||416-~/$//7%4

```

Try it online!

Uses the length of the input to return the correct code for the three reason phrases not stored in the builtin hash. Credit to @Arnauld for the idea.
> 6 votes

# Answer
# Python 3, ~~200~~ ~~190~~ 188 bytes Score:40

Thanks to pxeger for -8 bytes, ChartZ Belatedly for -4 bytes!

At least I didn't use a builtin :P this was an editor nightmare, couldn't copy and paste my encoded data correctly. I stopped working on this when it came out to exactly 200 bytes. I don't know what kind of black magic created dingledooper's solution and I'm afraid to ask.

```
lambda i:sum(e[1:(e.index(sum(i)&4095)+2):2])
e=[*map(ord,"ͅdޕšcʸ̙୧θӾ׈ت^ڪǼ̿ѲͯܕА]Ԃؿ΍͍ښԵୣװ̲Ɖ׃ݓࣣ܈࡫஗۩߾SׅϹݕיॽ")]

```

Try it online!

The encoded data goes like this:

```
[Sum of description bytes & 0xfff,Numeric change in HTTP Code,Sum of ...

```

e.g.

```
[837, 100, 1941, 1, 154, 99, 696, 1, 793, 1, 2919, 1, 952, 1, 1278, 1, 1480, 1, 1578, 94, 1706, 1, 508, 1, 831, 1, 1138, 1, 879, 1, 1813, 2, 1040, 93, 1282, 1, 1599, 1, 909, 1, 845, 1, 1690, 1, 1333, 1, 2915, 1, 1520, 1, 818, 1, 393, 1, 1475, 1, 1875, 1, 2275, 1, 1800, 1, 2155, 1, 2967, 1, 1769, 1, 2046, 83, 1477, 1, 1017, 1, 1877, 1, 1497, 1, 2429, 1]

```

Here's the code I used to generate it (plus some useless vestigial code...):

```
dat = b"""100 Continue
101 Switching Protocols
200 OK
201 Created
202 Accepted
203 Non-Authoritative Information
204 No Content
205 Reset Content
206 Partial Content
300 Multiple Choices
301 Moved Permanently
302 Found
303 See Other
304 Not Modified
305 Use Proxy
307 Temporary Redirect
400 Bad Request
401 Unauthorized
402 Payment Required
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable
407 Proxy Authentication Required
408 Request Timeout
409 Conflict
410 Gone
411 Length Required
412 Precondition Failed
413 Request Entity Too Large
414 Request-URI Too Long
415 Unsupported Media Type
416 Requested Range Not Satisfiable
417 Expectation Failed
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
505 HTTP Version Not Supported"""
data = ([(x[4:],x[:3]) for x in dat.split(b"\n")])
def e(d) : return sum(d)&0xfff
d2 = ([(x[1],e(x[0])) for x in data])
print(d2)
ol=[]
px = 0
for x in d2:
	ol.append(x[1])
	ol.append(int(x[0])-px)
	px = int(x[0])
de="".join([chr(x) for x in ol])
with open("de","w") as fh:
	fh.write(de)

ind=b"Non-Authoritative Information"
print(len(bytes(de,'utf-8')))
ct=f"""\
d="{de}"
e=list(map(ord,d))
c=lambda i:(sum(e[1:(e.index(sum(i)&0xfff)+2):2]))\
"""

with open("decoder.py","w") as fh:
	fh.write(ct)

from decoder import *
res = [(c(bytes(i[0])),i[1]) for i in data]
re = [x[0]==int(x[1]) for x in res]
print(sum(re))
print(len(data))
for i,v in enumerate(re):
	if not v:
		print(res[i])

print(ct)

```

Try it online!
> 5 votes

# Answer
# YaBASIC, 195 bytes, score:40

```
h=0
for i=1 to len(c$)
h=h+asc(mid$(c$,i,1))
next
x=instr(")64rRz!\"VEjX(#3I	2nBAsfm=tC_TuUhid",chr$(mod(xor(h,1329),127)))
b=99
if x>2 b=197
if x>9 b=290
if x>17 b=382
if x>35 b=464
?b+x;

```

Try it online!

Well this bit of voodoo was probably the hardest challenge I've completed on Code-Golf! But here it is - a complete, self contained routine that recognizes all 40 codes, in 195 bytes, in good old-fashioned BASIC.

As genius as @Arnauld's answer was, I really wanted to come up with my own solution, not blindly copy his formula, nor just pull codes off the net.

An early attempt with 2 bytes per status code, based on a Pearson hash, bottom out at 238 bytes, and it became obvious I needed a hash table with a single byte per code. Worse, due to the vagaries of UTF-8 coding, attempting to use all 256 ASCII codes gave garbage out, so I was stuck with the basic 127...

I based my answer on the fact that the sum of the ASCII values for each code was unique, and I just needed to find a way to get a unique byte from each one. I ended up writing a seperate utility to generate hash tables, XOR them, test for collisions, and increment the XOR until each hash was unique. 1329 was the "magic number" I got. *Of course*, the result had to include a " so I lost a byte with the \ needed to add it to a string, plus an extra X to deal with that sneaky jump from 305 to 307.

I really feel I levelled up as a programmer on this one, and I hope you like it!
> 4 votes

# Answer
# APL (Dyalog Unicode),

# 186 bytes, Score : 40 ~~41~~

```
S←18 22 53 56 38 91 76 83 98 11 31 86 90 62 40 47 25 80 72 5 10 99 85 24 2 68 52 96 77 19 9 65 4 87 33 36 57 16 49 28 41
C←{(∊⍳¨⍵)+⍵\100×1+⍳5}2 7 8 18 6
f←{C[⍸S=∊⍎2↑⌽⍕8-⍨|-/∊⎕UCS¨33⍴⍵]}

```

I made a very sketchy "hash function", that is so hobbled together it will only work for these messages.

```
{⍎2↑⌽⍕8-⍨|-/∊⎕UCS¨33⍴⍵} 'Foo Bar'

33⍴⍵   ⍝ 'Foo BarFoo BarFoo BarFoo BarFoo B'
∊⎕UCS¨ ⍝ convert to UTF8 numerical array 70 111 111 32...
|-/    ⍝ |70-111+111-32...|=104
8-⍨    ⍝ 96
⍎2↑⌽⍕  ⍝ 69

```

Rehydrating the Status Codes

```
{(∊⍳¨⍵)+⍵\100×1+⍳5}2 7 8 18 6

100×1+⍳5 ⍝ 100 200 300 400 500
⍵\       ⍝ 100 100 200 200 200 200 200 200 200 300...
∊⍳¨⍵     ⍝ 0 1 0 1 2 3 4 5 6 0 1 2 3...
+        ⍝ 100 101 200 201 202 203 204...

```

Lookup Status Code

```
C[⍸S=∊Calculated_Hash]

```

Try it online!
> 4 votes

# Answer
# Java EE, 111 bytes, score: 40

```
s->javax.servlet.http.HttpServletResponse.class.getField("SC_"+s.toUpperCase().replaceAll(" |-","_")).get(null)

```

`HttpServletResponse` has public fields for all the statuses prefixed with `"SC_"`. The names, however, are all uppercase and spaces or dashes are replaced with underscores. The values of these fields can be obtained dynamically using reflection.

Demo
> 3 votes

# Answer
# APL (Dyalog Extended), 123 bytes

```
⎕FIX'file:///opt/mdyalog/17.1/64/unicode/Library/Conga/HttpUtils.dyalog'
f←{⊃s⌿⍨(⊂⍵)≡⍥(⌈~∘'-')¨⊣/⌽s←HttpUtils.HttpStatuses}

```

No builtins that do this exactly (as far as I can tell) but luckily the statuses are stored in Dyalog's HTTP utilities.

Try it online!
> 3 votes

# Answer
# c# 9, 101 bytes.

```
System.Console.WriteLine(args.Length>0?(int)System.Enum.Parse<System.Net.HttpStatusCode>(args[0]):0);

```
> 3 votes

# Answer
# PowerShell, 41 bytes

```
+[net.httpstatuscode]($args-replace" |-")

```

Try it online!

Cheap builitins, again

-7 bytes for @ZaelinGoodman
> 2 votes

# Answer
# Zsh, <sup>~~197~~</sup> 187 bytes, score 40

```
>`sum`
F()for a {let n++;ls|grep -q $[32#$a]$&&<<<$n&&bye}
for b (5SOO E3HOIOTU3P5PJL 1K82FFFCPFC5JIQF 3AIQ9M13UPUUQ0PR9RBUIAHSNOF8M32QLT2H C2Q1BISP3DKE)n=$[m++]99 F `fold -2<<<$b`
<<<201

```

Try it online!

Can probably be a fair bit shorter, but I'm not really with it right now.
> 2 votes

# Answer
# JavaScript (Node.js), 133 bytes, score 40

```
f=(t,i,c,s=require('http').STATUS_CODES[i])=>s==t?i:i>999?0:(g=_=>s&&s.slice(--j)==t.slice(j)?g():j)(j=0)>=c?f(t,-~i,c):f(t,-~i,j)||i

```

Try it online!

I have no idea why it is so complex. But it at least works within 200 bytes.

---

# JavaScript (Node.js), 54 bytes, score 37

```
f=(t,i)=>require('http').STATUS_CODES[i]==t?i:f(t,-~i)

```

Try it online!
> 1 votes

# Answer
# JavaScript, 63 bytes (Node.js), score 36 for some reason

```
n=>Object.keys(a=require('http').STATUS_CODES).find(e=>a[e]==n)

```

Works with ES6 and above.
> 1 votes

# Answer
# Java, 32 bytes

```
n -> HttpStatus.valueOf(n).value()

```

Using Spring. Plus a couple of megs of libs!
> 1 votes

# Answer
# Julia 1.0, <sup>~~143~~</sup> 135 bytes, score 40

```
x->Int["Ƙ...Ĭ..ƙ.ƞıƕƐƛ.ǵƚ.ÎĮįƜĳǷÊƒdĭƠÌƖǶơÍƔǸÈƑǴƗƓǹƟËÉe....Ɲ.İ"...][sum(Int[x...])%217%159%117%54]

```

Try it online!

it could probably be more golfed but good enough for now
> 1 votes

# Answer
# , ~~131~~ 128 bytes, score 40

```
`-`=utf8ToInt
c(408:417,0:7+100*1:5%x%!!1:8)[-"+41i@N!>Q      -bTE6 ;?J85 M0IP)F/^]3G*  "==sum(-readLines())%%217%%124]

```

Try it online!

Unlike many other answers, this one isn't really based on some "magic formula". Here we use modulo hashing simply to convert the byte sum of the input to a unique checksum and then to make it fit within ASCII in order to avoid multi-byte characters (albeit with some unprintables). The lookup string is then just a catalog of these checksums.

Finally, we return a value from the vector of status codes at the position where the checksum matches. The status codes themselves are completely unencoded: Initially, I just used a literal concatenation of relevant ranges `c(100:101,200:206,...)`, but then managed to squeeze off a few extra bytes by declaring a "structured" range encompassing the values `x00:x07` for each hundred. However, the savings are rather modest, as we now also have to fill the lookup string with dummy values (whitespace) for missing codes.
> 1 votes

# Answer
# 05AB1E \+ Plug, ~~30~~ 29 bytes, score 40

```
l„ -'_º‡…ƒË :”§¬.¡¤n.‡‚.”rJ.E

```

Beats all other answers. No TIO link because the module (`Plug.Conn.Status`) used here is not on TIO.

```
l„ -'_º‡…...”...”rJ.E  # trimmed program
l                      # push...
                       # implicit input...
l                      # in lowercase...
       ‡               # with each character in...
 „ -                   # literal...
       ‡               # replaced with corresponding character in...
    '_                 # literal...
      º                # concatenated with...
    '_                 # literal...
      º                # reversed
        …...           # push "code :"
            ”...”      # push "Plug. Conn. Status."
                       # in title case
                 r     # reverse stack
                   .E  # evaluate...
                  J    # joined stack...
                   .E  # as Elixir code

====================

Plug. Conn. Status.code  # full program
Plug. Conn. Status.code  # return HTTP status code with given name

```
> 1 votes

---
Tags: string, code-challenge
---


title: New order #4: World

text:
# Question
Title: New order #4: World
## Introduction *(may be ignored)*

Putting all positive numbers in its regular order (1, 2, 3, ...) is a bit boring, isn't it? So here is a series of challenges around permutations (reshuffelings) of all positive numbers. This is the fourth challenge in this series (links to the first, second and third challenge).

In this challenge, we will explore not *one* permutation of the natural numbers, but an entire world of permutations!

In 2000, Clark Kimberling posed a problem in the 26th issue of *Crux Mathematicorum*, a scientific journal of mathematics published by the Canadian Mathematical Society. The problem was:

> \\$\text{Sequence }a = \begin{cases} a\_1 = 1\\ a\_n = \lfloor \frac{a\_{n-1}}{2} \rfloor\text{ if }\lfloor \frac{a\_{n-1}}{2} \rfloor \notin \\{0, a\_1, ... , a\_{n-1}\\}\\ a\_n = 3 a\_{n-1}\text{ otherwise} \end{cases}\\$
>
> ***Does every positive integer occur exactly once in this sequence?***

In 2004, Mateusz Kwasnicki provided positive proof in the same journal and in 2008, he published a more formal and (compared to the original question) a more general proof. He formulated the sequence with parameters \\$p\\$ and \\$q\\$:

\\$\begin{cases} a\_1 = 1\\ a\_n = \lfloor \frac{a\_{n-1}}{q} \rfloor\text{ if }\lfloor \frac{a\_{n-1}}{q} \rfloor \notin \\{0, a\_1, ... , a\_{n-1}\\}\\ a\_n = p a\_{n-1}\text{ otherwise} \end{cases}\\$

He proved that for any \\$p, q\>1\\$ such that \\$log\_p(q)\\$ is irrational, the sequence is a permutation of the natural numbers. Since there are an infinite number of \\$p\\$ and \\$q\\$ values for which this is true, this is truly an entire world of permutations of the natural numbers. We will stick with the original \\$(p, q)=(3, 2)\\$, and for these paramters, the sequence can be found as A050000 in the OEIS. Its first 20 elements are:

```
1, 3, 9, 4, 2, 6, 18, 54, 27, 13, 39, 19, 57, 28, 14, 7, 21, 10, 5, 15

```

Since this is a "pure sequence" challenge, the task is to output \\$a(n)\\$ for a given \\$n\\$ as input, where \\$a(n)\\$ is A050000.

## Task

Given an integer input \\$n\\$, output \\$a(n)\\$ in integer format, where:

\\$\begin{cases} a(1) = 1\\ a(n) = \lfloor \frac{a(n-1)}{2} \rfloor\text{ if }\lfloor \frac{a(n-1)}{2} \rfloor \notin \\{0, a\_1, ... , a(n-1)\\}\\ a(n) = 3 a(n-1)\text{ otherwise} \end{cases}\\$

*Note: 1-based indexing is assumed here; you may use 0-based indexing, so \\$a(0) = 1; a(1) = 3\\$, etc. Please mention this in your answer if you choose to use this.*

## Test cases

```
Input | Output
---------------
1     |  1
5     |  2
20    |  15
50    |  165
78    |  207
123   |  94
1234  |  3537
3000  |  2245
9999  |  4065
29890 |  149853

```

## Rules

* Input and output are integers (your program should at least support input and output in the range of 1 up to 32767)
* Invalid input (0, floats, strings, negative values, etc.) may lead to unpredicted output, errors or (un)defined behaviour.
* Default I/O rules apply.
* Default loopholes are forbidden.
* This is , so the shortest answers in bytes wins

# Answer
> 3 votes
# Japt, ~~15~~ 14 bytes

1-indexed.

```
@[X*3Xz]kZ Ì}g

```

Try it

```
@[X*3Xz]kZ Ì}g     :Implicit input of integer U
             g     :Starting with the array [0,1] do the following U times, pushing the result to the array each time
@                  :  Pass the last element X in the array Z through the following function
 [                 :    Build an array containing
  X*3              :      X multiplied by 3
     Xz            :      X floor divided by 2
       ]           :    Close array
        kZ         :    Remove all elements contained in Z
           Ì       :    Get the last element
            }      :  End function
                   :Implicit output of the last element in the array

```

# Answer
> 7 votes
# JavaScript (ES6),  ~~55 51~~  50 bytes

*Saved 1 byte thanks to @EmbodimentofIgnorance*
*Saved 1 byte thanks to @tsh*

```
n=>eval("for(o=[p=2];n--;)o[p=o[q=p>>1]?3*p:q]=p")

```

Try it online!

# Answer
> 5 votes
# Jelly, 15 bytes

```
µ×3żHḞḢḟȯ1Ṫ;µ¡Ḣ

```

A full program accepting the integer, `n` (1-based), from STDIN which prints the result.

**Try it online!**

### How?

```
µ×3żHḞḢḟȯ1Ṫ;µ¡Ḣ - Main Link: no arguments (implicit left argument = 0)
µ           µ¡  - repeat this monadic chain STDIN times (starting with x=0)
                -                   e.g. x = ...  0      [1,0]            [9,3,1,0]
 ×3             -   multiply by 3                 0      [3,0]            [27,9,3,0]
    H           -   halve                         0      [1.5,0]          [4.5,1.5,0.5,0]
   ż            -   zip together                  [0,0]  [[3,1.5],[0,0]]  [[27,4.5],[9,1.5],[3,0.5],[0,0]]
     Ḟ          -   floor                         [0,0]  [[3,1],[0,0]]    [[27,4],[9,1],[3,0],[0,0]]
      Ḣ         -   head                          0      [3,1]            [27,4]
       ḟ        -   filter discard if in x        []     [3]              [27,4]
        ȯ1      -   logical OR with 1             1      [3]              [27,4]
          Ṫ     -   tail                          1      3                4
           ;    -   concatenate with x            [1,0]  [3,1,0]          [4,9,3,1,0]
              Ḣ - head                            1      3                4
                - implicit print

```

# Answer
> 4 votes
# Perl 6, 49 bytes

*-2 bytes thanks to nwellnof*

```
{(1,3,{(3*@_[*-1]Xdiv 6,1).max(*∉@_)}...*)[$_]}

```

Try it online!

Returns the 0-indexed element in the sequence. You can change this to 1-indexed by changing the starting elements to `0,1` instead of `1,3`

### Explanation:

```
{                                             }  # Anonymous code block
 (                                   ...*)[$_]   # Index into the infinite sequence
  1,3                                            # That starts with 1,3
     ,{                             }            # And each element is
       (                 ).max(    )             # The first of
          @_[*-1]X                               # The previous element
        3*        div 6                          # Halved and floored
        3*        div  ,1                        # Or tripled
                               *∉@_             # That hasn't appeared in the sequence yet

```

# Answer
> 4 votes
# 05AB1E, ~~16~~ 15 bytes

Saved 1 byte thanks to *Kevin Cruijssen*.
0-indexed.

```
¾ˆ$FDˆx3*‚;ï¯Kн

```

Try it online!

**Explanation**

Using `n=1` as example

```
¾ˆ                 # initialize global array as [0]
  $                # initialize stack with 1, input
   F               # input times do:
    Dˆ             # duplicate current item (initially 1) and add one copy to global array
                   # STACK: 1, GLOBAL_ARRAY: [0, 1]
      x            # push Top_of_stack*2
                   # STACK: 1, 2, GLOBAL_ARRAY: [0, 1]
       3*          # multiply by 3
                   # STACK: 1, 6, GLOBAL_ARRAY: [0, 1]
         ‚;ï       # pair and integer divide both by 2
                   # STACK: [0, 3], GLOBAL_ARRAY: [0, 1]
            ¯K     # remove any numbers already in the global array
                   # STACK: [3], GLOBAL_ARRAY: [0, 1]
              н    # and take the head
                   # STACK: 3

```

# Answer
> 3 votes
# , ~~47~~ 40 bytes

```
[:{:0 1(],<.@-:@{:@](e.{[,3*{:@])])^:[~]

```

Try it online!

## ungolfed

```
[: {: 0 1 (] , <.@-:@{:@] (e. { [ , 3 * {:@]) ])^:[~ ]

```

Direct translation of the definition into J. It builds bottom up by using `^:` to iterate from the starting value the required number of times.

# Answer
> 3 votes
# Haskell, ~~67~~ 65 bytes

```
(h[1,0]!!)
h l@(a:o)|elem(div a 2)o=a:h(3*a:l)|1>0=a:h(div a 2:l)

```

Try it online!

Uses 0-based indexing.

EDIT: saved 2 bytes by using `elem` instead of `notElem` and switching conditions

# Answer
> 3 votes
# Java 10, ~~120~~ 99 bytes

```
n->{var L=" 1 0 ";int r=1,t;for(;n-->0;L+=r+" ")if(L.contains(" "+(r=(t=r)/2)+" "))r=t*3;return r;}

```

Try it online.

**Explanation:**

```
n->{                              // Method with integer as both parameter and return-type
  var L=" 1 0 ";                  //  Create a String that acts as 'List', starting at [1,0]
  int r=1,                        //  Result-integer, starting at 1
      t;                          //  Temp-integer, uninitialized
  for(;n-->0;                     //  Loop the input amount of times:
      L+=r+" "))                  //    After every iteration: add the result to the 'List'
                          t=r     //   Create a copy of the result in `t`
                       r=(...)/2  //   Then integer-divide the result by 2
    if(L.contains(" "+(...)+" ")) //   If the 'List' contains this result//2:
      r=t*3;                      //    Set the result to `t` multiplied by 3 instead
  return r;}                      //  Return the result

```

# Answer
> 2 votes
# Jelly, 21 bytes

```
Ø.;0ị×3$:2$:2eɗ?Ɗ$⁸¡Ṫ

```

Try it online!

A monadic link that takes zero-indexed \\$n\\$ as the argument and returns \\$a(n)\\$.

# Answer
> 2 votes
# C++ (gcc), ~~189~~ 180 bytes

-9 bytes to small golfing

```
#import<vector>
#import<algorithm>
int a(int n){std::vector<int>s={1};for(int i=0;i<n;++i)s.push_back(i&&std::find(s.begin(),s.end(),s[i]/2)==s.end()?s[i]/2:3*s[i]);return s[n-1];}

```

Try it online!

Computes the sequence up to `n`, then returns the desired element. Slow for larger indices.

# Answer
> 2 votes
# Ruby, ~~54~~ ~~52~~ 48 bytes

```
->n{*s=0;j=2;n.times{s<<j=s==s-[j/2]?j/2:j*3};j}

```

Try it online!

# Answer
> 2 votes
# Python 2, 66 bytes

```
l=lambda n,p=1,s=[0]:p*(n<len(s))or l(n,3*p*(p/2in s)or p/2,[p]+s)

```

Try it online!

Uses zero-based indexing. The lambda does little more than recursively building up the sequence and returning as soon as the required index is reached.

# Answer
> 2 votes
# Stax, 14 bytes

```
üÑα↕○Ü1∟¡f↑ô┬♥

```

Run and debug it

Zero-indexed.

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

```
(L=Last)@Nest[{##,If[FreeQ[#,x=⌊L@#/2⌋],x,3L@#]}&,{0,1},#]&

```

Try it online!

This is 0-indexed
(In TIO I added -1 in every test case)

# Answer
> 1 votes
# Haskell, 55 bytes

```
(1%[0]!!)
a%o|b<-div a 2=a:last(b:[3*a|elem b o])%(a:o)

```

Try it online!

Golfing user1472751's slick list-generation method.

Same length:

```
(1%[0]!!)
a%o=a:[x|x<-[div a 2,a*3],all(/=x)o]!!0%(a:o)

```

Try it online!

# Answer
> 1 votes
# Python 3, ~~105~~ ~~103~~ ~~100~~ ~~95~~ 83 bytes

*-2 bytes thanks to agtoever*
*-12 bytes thanks to ArBo*

```
def f(n):
 s=0,1
 while len(s)<=n:t=s[-1]//2;s+=(t in s)*3*s[-1]or t,
 return s[-1]

```

Try it online!

# Answer
> 1 votes
# Gaia, ~~22~~ 20 bytes

```
2…@⟨:):3×¤ḥ⌋,;D)+⟩ₓ)

```

Try it online!

0-based index.

Credit to Shaggy for the approach

```
2…			| push [0 1]
  @⟨		 ⟩ₓ	| do the following n times:
    :):			| dup the list L, take the last element e, and dup that
       3×¤ḥ⌋,		| push [3*e floor(e/2)]
	     ;D		| take the asymmetric set difference [3*e floor(e/2)] - L
	       )+	| take the last element of the difference and add it to the end of L (end of loop)
		   )	| finally, take the last element and output it

```

`;D`

# Answer
> 1 votes
# Python 2, 62 bytes

```
a=lambda n:n<1or a(n-1)*6**(a(n-1)//2in[0]+map(a,range(n)))//2

```

Try it online!

Returns `True` for `a(0)`. 0-indexed.

# Answer
> 1 votes
# Husk, 18 bytes

```
!t¡(→S-o§e*3÷2→)ŀ2

```

Try it online!

Not sure why I'm unable to compose the iteration function, but I was only able to get it working with parentheses.

+1 byte after fixing the list.

# Answer
> 0 votes
# Lua, 78 bytes

```
x,y=1,3 u={}for _=2,...do
u[x]=0
x,y=y,y//2
if u[y]then y=3*x end
end
print(x)

```

Try it online!

# Answer
> 0 votes
# Vyxal, 22 bytes

```
0⅛3?(:½⌊¾$ḟu=[½⌊|3*]:⅛

```

Try it Online!

1-indexed.

```
0⅛                     # Push 0 to glob. arr.
  3                    # Push 3
   ?(                  # Iteration times
             [     ]   # If...
     :½⌊               # Top of stack, halved and floored
        ¾$ḟu=          # Is in global array?
              ½⌊       # Halved and floored
                |      # Else
                 3*    # Tripled
                    :⅛ # And pushed to glob. arr.

```

---
Tags: code-golf, sequence
---


title: Stack Overflowing

text:
# Question
Title: Stack Overflowing
(Inspired by this question)

# Objective

Your task is to write a program or function to print an ASCII version of the Stack Overflow logo to STDOUT

```
 \|/
(-)
(-)
(-)
(-)

```

Your program should take two inputs, referred to here as H and N. The height of the stack "container" (the parentheses) is determined by H. The number of items in the stack is determined by N. If N\>H, the stack will "overflow".

# Input/Output

H will determine the height of the containers

For example:

H=1:

```
( )

```

H=2:

```
( )
( )

```

H=3:

```
( )
( )
( )

```

H will always be at least 1

N will determine how many items are in the stack. The following examples are all H = 2:

N=0

```
( )
( )

```

N=1

```
( )
(-)

```

N=2

```
(-)
(-)

```

N=3

```
 \
(-)
(-)

```

N=4

```
 \|
(-)
(-)

```

N=5

```
 \|/
(-)
(-)

```

N=6

```
 \|/
(-)-
(-)

```

N=7

```
 \|/
(-)-
(-)-

```

N will never be more than `2H+3` (In other words, the stack will never go through the ground).

# Rules

* No Standard Loopholes.
* Your program must not produce any errors.
* All test cases must pass.
* You can input H and N any way you want.
* I seriously doubt that your language has a built-in for this.
* Each line may optionally have an extra space at the end. A blank line above a stack where N \<= H is optional, as is a trailing newline.
* This is , so shortest code in bytes wins!

# Test Cases

In addition to all of the H=2 test cases from the Input/Output section, all of the following test cases must pass:

H=1, N=1

```
(-)

```

H=1, N=5

```
 \|/
(-)-

```

H=4, N=7

```
 \|/
(-)
(-)
(-)
(-)

```

H=5, N=0

```
( )
( )
( )
( )
( )

```

## Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
var QUESTION_ID=81167,OVERRIDE_USER=41505;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# Pyth, ~~43~~ ~~41~~ 40 bytes

```
<" \|/"g#0hK-QJEVJs[\(?<N_Kd\-\)*<N-K3\-

```

Try it online. Test suite.

First pass, quick and dirty. Input to STDIN as `N\nH`.

### Explanation

1. Save the second input (height) to `J` (`JE`), and subtract it from the first input (the number of items). (`-QJE`)
2. Save the difference (number of overflowing items) to `K`. (`K-QJE`)
3. Add 1 to the number. (`hK-QJE`)
4. Take `max(0, previous)`. This is required as negative numbers would break the next step. (`g#0hK-QJE`)
5. Take at most that many letters from the string `" \|/"` to get the first line and print. (`<" \|/"g#0hK-QJE`)
6. Loop `N` over `range(0, J)`. (`VJ`) For each `N` print the concatenation of the following: (`s[`)
    * `"("` (`\(`)
    * `" "` if there are at least `N+1` free spaces in the stack (`<N_K`), `"-"` otherwise. (`?<N_Kd\-`)
    * `")"` (`\)`)
    * `"-"` if there are at least `N+4` overflowing pieces in the stack (`<N-K3`), `""` otherwise. (`*<N-K3\-`)
> 15 votes

# Answer
## JavaScript (ES6), ~~105~~ 102 bytes

@Edit: Saved 3 bytes thanks to @PatrickRoberts.

```
f=
(n,h)=>` \\|/`.substr(0,n+1-h)+[...Array(h)].map((_,i)=>`
(${i+n<h?` `:`-`})${i+h+3<n?`-`:``}`).join``
;
```

```
<div oninput=o.textContent=f(+n.value,+h.value)>n<input id=n type=number min=0 value=0>h<input id=h type=number min=0 value=0><pre id=o>
```
> 13 votes

# Answer
# JavaScript (ES6), ~~126~~ ~~122~~ 112 bytes

```
h=>n=>' \\|/'.substr(0,(o=n-h)+1)+`
( )`[r='repeat'](0>-o?0:-o)+`
(-)-`[r](o=0>o-3?0:o-3)+`
(-)`[r](n<h-o?n:h-o)

```

## Test

```
f=h=>n=>' \\|/'.substr(0,(o=n-h)+1)+`
( )`[r='repeat'](0>-o?0:-o)+`
(-)-`[r](o=0>o-3?0:o-3)+`
(-)`[r](n<h-o?n:h-o)
document.write(`<pre>${[[2,0],[2,1],[2,2],[2,3],[2,4],[2,5],[2,6],[2,7],[1,1],[1,5],[4,7],[5,0]].map(a=>f(a.shift())(a.shift())).join`

`}</pre>`)
```

## Alternate Test (if your browser does not support ES6)

See the test on Babeljs.io and check "evaluate".

## Interesting alternate approach at 136 bytes

```
h=>n=>' \\|/'.substr(0,(o=n-h)+1)+`
( )${0>-o?0:-o}
(-)-${o=0>o-3?0:o-3}
(-)${n<h-o?n:h-o}`.replace(/(\n.*)(\d+)/g,(_,s,r)=>s.repeat(r))

```

This moves the repeat amounts into the template string and uses a regexp and replace to inject the repeating groups. Unfortunately the signature for `.replace()` is just too long.
> 12 votes

# Answer
## C++14 (lambda function), 196

Saved 1 byte thanks to Quentin.

Saved 2 bytes thanks to Adam Martin.

```
#include<iostream>
using namespace std;[](int h,int n){auto s=" \\|/( ) (-) (-)-"s;int t=max(min(n-h,3),0);n-=t;cout<<s.substr(0,t+1)+'\n';for(;h;h--)n-=t=n>h?2:h<=n,cout<<s.substr(4+4*t,4)+'\n';}

```

The function itself takes 157 bytes.

See it in action here.

Ungolfed version:

```
[](int h, int n) {
    auto s = " \\|/( ) (-) (-)-"s;
    int t = max(min(n - h, 3), 0);
    n -= t;
    cout << s.substr(0, t + 1) + '\n';
    for(; h; h--) {
        if (n > h) t = 2;
        else if (h > n) t = 0;
        else t = 1;
        n -= t;
        cout << s.substr(4 + 4 * t, 4) + '\n';
    }
};

```
> 10 votes

# Answer
## CJam, 57 bytes

```
Sri:X'(*+X),W%X)X')*+X),X))f+]zN*X5*,X'-*_"\|/"\++ri<S+er

```

Test it here.

Could definitely use some improvement. The idea is to build a grid where the `-\|/-` cells are replaced with consecutive integers, e.g.

```
 345
(2)6
(1)7
(0)8

```

And then to replace them with the correct characters (potentially spaces) at the end.
> 9 votes

# Answer
# Python 2, ~~101~~ ~~100~~ 98 bytes

```
def f(h,n):
 print" \|/"[:max(0,n-h+1)]
 for i in range(h):print("(-)","( )")[h-i>n]+"-"*(n>i+h+3)

```
> 6 votes

# Answer
# JavaScript (ES6), ~~87~~ 80 bytes

```
F=(h,n)=>h?F(h-1,n-1)+`
(${n>0?'-':' '})${n>2*h+2?'-':''}`:' \\|/'.substr(0,n+1)

```

Uses recursion to create the output string from the bottom up.

**EDIT**: Thanks to @Neil for shaving 7 bytes off from 87 bytes

## Original

```
(h,n)=>(E=s=>h--?E(`
(${n>0?'-':' '})${--n>2*h+3?'-':''}`+s):` \\|/`.substr(0,n+1)+s)``

```

## Test snippet:

```
F=(h,n)=>h?F(h-1,n-1)+`
(${n>0?'-':' '})${n>2*h+2?'-':''}`:' \\|/'.substr(0,n+1)

h.oninput = n.oninput = () => output.innerHTML = F(+h.value, +n.value);
```

```
<label>h <input type="number" min="0" value="0" id="h" /></label>
<label>n <input type="number" min="0" value="0" id="n" /></label>
<hr />
<pre id="output"></pre>
```
> 4 votes

# Answer
# JavaScript (ES6), ~~149~~ ~~139~~ 137 bytes

```
h=>n=>` ${[(g=(j,m=1)=>` -\\|/`[(j<n)*m])(h,2),g(h+1,3),g(h+2,4)].join``}${[...Array(h)].map((_,i)=>`
(${g(h-i-1)})${g(h+i+3)}`).join``}`

```

I liked @MartinEnder's idea about indexing the `-\|/` characters and I wanted to see how it would fare in ES6. Apparently I didn't do so well. Trying to figure out if this could be improved using `for...of`.

### Edits

* I managed to remove regexp and the call to `.replace`, moving the indexing directly into `g()` instead.
* I accidentally counted `f=` in the second byte count

## Test

```
f=h=>n=>` ${[(g=(j,m=1)=>` -\\|/`[(j<n)*m])(h,2),g(h+1,3),g(h+2,4)].join``}${[...Array(h)].map((_,i)=>`
(${g(h-i-1)})${g(h+i+3)}`).join``}`
document.write(`<pre>${[[2,0],[2,1],[2,2],[2,3],[2,4],[2,5],[2,6],[2,7],[1,1],[1,5],[4,7],[5,0]].map(a=>f(a.shift())(a.shift())).join`

`}</pre>`)
```
> 3 votes

# Answer
# Java, 186 177 bytes

```
void f(int h,int n){for(int i=0;i<h+1;i++)System.out.print((i>0?"(":" ")+(i>0?n>h-i-2?"-":" ":n>h+0?"\\":" ")+(i>0?")":n>h+1?"|":" ")+(i>0?n>h+2+i?"-":" ":n>h+2?"/":" ")+"\n");}

```

**Ungolfed** try online

```
String f(int h, int n)
{
    String s=" ";
    s+=n>h+0?"\\":" ";
    s+=n>h+1? "|":" ";
    s+=n>h+2? "/":" ";
    s+="\n";

    for(int i=0; i<h; i++)
    {
        s+="(";
        s+=n>h-i-1?"-":" ";
        s+=")";
        s+=n>h+3+i?"-":" ";
        s+="\n";
    }

    return s;
}

```
> 3 votes

# Answer
# Excel, 131 bytes

Input taken as a tuple, Height `H` in `A1`, `N` in `B1`. Cell containing formula needs to have Text Wrapping turned on. Suggest using a Mono-spaced font.

```
=LEFT(" \|/",MAX(0,B1-A1+1))&"
"&REPT("(-)-
",MAX(0,B1-A1-3))&REPT("( )
",MAX(0,A1-B1))&REPT("(-)
",A1-MAX(0,B1-A1-3)-MAX(0,A1-B1))
```
> 3 votes

# Answer
# C++11, ~~155~~ ~~148~~ 145 bytes

```
void f(int h,int n){cout<<string{" \\|/",max(min(3,n-h),0)+1}<<'\n';for(int i=0;i<h;++i)cout<<(h-i<=n?"(-)":"( )")<<(i<max(n-h-3,0)?"-\n":"\n");}

```

**Ungolfed**:

```
void f(int h,int n)
{
  cout << string{" \\|/", max(min(3, n-h), 0) + 1} << '\n';
  for(int i=0; i<h; ++i)
    cout << (h-i <= n ? "(-)" : "( )") << (i < max(n-h-3,0) ? "-\n" : "\n");
}

```

**Usage**:

```
#include <iostream>
#include <string>
using namespace std;

void f(int h,int n){cout<<string{" \\|/",max(min(3,n-h),0)+1}<<'\n';for(int i=0;i<h;++i)cout<<(h-i<=n?"(-)":"( )")<<(i<max(n-h-3,0)?"-\n":"\n");}

int main()
{
  int h,n;
  cin >> h >> n;
  f(h, n);
}

```
> 2 votes

# Answer
# Vyxal, 34 bytes

```
ð₴-0∴`\|/`Ẏ,(\(₴¹n->\)-2↳3¹+n+⁰<-,

```

Try it Online!

```
ð₴                                 # Output a space
  -                                # Difference
   0∴                              # or 0 if diff. is negative
     `\|/`                         # String literal
          Ẏ,                       # First (max(N - H, 0)) letters
            (                      # Height times do...
             \(₴                   # Output a (
                ¹n-                # The difference of (iteration number) and (height)
                   >               # Is greater than (N)
                    \)-            # That many -s before a )
                       2↳          # Justified to the right, so space if not empty
                         3¹+       # 3 + (Height)
                            n+     # Plus iteration number
                              ⁰<   # Is less than (N)
                                -  # That many -s appended to the previous string
                                 , # Output with trailing newline.

```
> 2 votes

# Answer
# Python 3, ~~134~~ ~~121~~ ~~118~~ 111 bytes

```
def f(h,n):print('\|/'[:max(0,n-h)]+'\n'+'\n'.join('(-)-'if h<n-x-3else('(-)','( )')[x+n<h] for x in range(h)))

```

Test it here: https://repl.it/CYL1/0

Un-golfed:

```
def f(h,n):
  top=['\|/'[:max(0,n-h)]]
  stack=['( )'if x+n<h else'(-)'for x in range(h)]
  overflow=top+stack
  v=n-3
  while v>h:
      overflow[h-v]+='-' #add side overflow
      v-=1

  print('\n'.join(overflow))

```

~~I'd like to have added the side overflow to the list comprehension, but I couldn't squeeze it in, so I had to go with the while loop.~~ Saved 13 bytes!
> 1 votes

# Answer
# Perl 5, 91 bytes

```
say((' \|/'=~/./g)[0..-($a=<>)+($b=<>)]);say$b<=$a-$_?'( )':'(-)'.'-'x($b-2>$a+$_)for 1..$a

```

Try it online!
> 1 votes

# Answer
# Pip, 50 bytes

```
Ps.(0Xa."\|/")@<bDC0Fi,aP"()"WV"- "@[b<a-ib<a+4+i]

```

Try it online!

Ugh, this is too long... don't know how to shorten it any more, though. Cyclical indexing, which is usually helpful, cost extra bytes this time.
> 1 votes

# Answer
# PowerShell, ~~109~~ ~~108~~ 104 bytes

```
param($n,$h)-join" \|/"[0..(($d=$n-$h),0)[$d-lt0]]
1..$h|%{("( )","(-)")[$h-$_-lt$n]+"-"*($h+$_+2-lt$n)}

```

Try it online!

Lost a lot on expensive indexing but still decent-ish. I'm not sure my index math is optimal however. Stole some logic from the other answers to save a byte. Also remembered precedence to pop some parens for -4 bytes.
> 1 votes

# Answer
# 05AB1E, 45 bytes

```
-U…( )¸¹иε²N›ið'-:]RεX4-N@i'-«]" \|/"XdX*>£š»

```

Can definitely be golfed.. Not too happy about it in its current form tbh.

Try it online or verify all test cases.

**Explanation:**

```
-                # Subtract the 2nd (implicit) input `n` from the 1st (implicit) input `h`
                 #  i.e. `h`=3, `n`=8 → 5
 U               # Pop and store it in variable `X`
…( )             # Push string "( )"
    ¸            # Wrap it into a list: ["( )"]
     ¹и          # Repeat it the first input (`h`) amount of times
                 #  i.e. 3 → ["( )","( )","( )"]
ε                # Map each to:
 ²N›i            #  If the second input `n` is larger than the map-index N:
                 #    i.e. `n`=8 >= N=0 → 1 (truthy)
     ð'-:       '#   Replace the space with a "-"
                 #    i.e. "( )" → "(-)"
]                # Close both the if and map
 R               # Reverse the list
ε                # Map each to:
 X4-N@i          #  If `X` minus 4 is larger than or equal to the map-index N:
                 #     i.e. `X`=5 and N=0 → 5-4 >= 0 → 1 (truthy)
                 #     i.e. `X`=5 and N=2 → 5-4 >= 2 → 0 (falsey)
       '-«      '#   Append a "-"
]                # Close both the if and map
 " \|/"          # Push String " \|/"
       Xd        # Check if `X` is 0 or positive (0 if negative, 1 if 0 or positive)
                 #  i.e. `X`=5 → 1 (truthy)
         X*      # Multiply it by `X`
                 #  i.e. 1 * 5 → 5
           >     # Increase it by 1
                 #  i.e. 5 → 6
            £    # Take that many character of the string " \|/"
                 #  i.e. 6 → " \|/"
             š   # Prepend it to the list
                 #  i.e. ["(-)-","(-)-","(-)"] and " \|/" → [" \|/","(-)-","(-)-","(-)"]
              »  # Join the list by newlines (and output implicitly)
                 #  i.e. [" \|/","(-)-","(-)-","(-)"] → " \|/\n(-)-\n(-)-\n(-)"

```
> 0 votes

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


title: Grow a Treemote!

text:
# Question
Title: Grow a Treemote!
This is my friend Thomas. He is half tree, half emoticon.

```
|    |
| :D |
|    |

```

He is lonely. Let's make him some friends!

---

Given a text-based emoticon as input (e.g. `ಠ_ಠ`, `:P`, `>_>`, not , , or ), output the corresponding treemote.

A treemote's length is how many characters it is lon (basically most builtin length functions for strings). So `ಠ_ಠ` has length 3.

The syntax for a treemote of length `n` is as follows:

```
|< 2+n spaces>| * ceil(n/2)
| <emote> | (note the spaces)
|< 2+n spaces>| * ceil(n/2)

```

So any treemote of length 3 would look like:

```
|     |
|     |
| ಠ_ಠ |
|     |
|     |

```

He has `ceil(n/2)` newline separated trunk segments on either side, each with `2 + n` spaces inside.

### Challenge: Given the text-based emoticon, output the corresponding treemote.

---

Other rules:

* This is , which means I want you to write short code.
* Standard loopholes disallowed.
* You must support non-ascii characters unless your language can't handle them.

## Test Cases:

```
^_^

|     |
|     |
| ^_^ |
|     |
|     |

\o/

|     |
|     |
| \o/ |
|     |
|     |

(✿◠‿◠)

|        |
|        |
|        |
| (✿◠‿◠) |
|        |
|        |
|        |

D:

|    |
| D: |
|    |

( ͡° ͜ʖ ͡°)

|             |
|             |
|             |
|             |
|             |
|             |
| ( ͡° ͜ʖ ͡°) |
|             |
|             |
|             |
|             |
|             |
|             |

```

# Answer
# 05AB1E, ~~27~~ 25 bytes

Code:

```
g©Ìð×"|ÿ|
"®;î×©„| Â¹s¶®J

```

Explanation:

```
g                  # Push the length of the input string.
 ©                 # Copy that to the register.
  Ì                # Increment by 2.
   ð×              # Multiply by spaces.
     "|ÿ|\n"       # ÿ is used for interpolation and push the string "|spaces|\n".
                   #
 ®                 # Retrieve the value from the register.
  ;î               # Divide by 2 and round up.
    ×              # Multiply that by "|spaces|".
     ©             # Copy this into the register.
      „|           # Push the string "| ".
         Â         # Bifurcate, pushing the string and the string reversed.
          ¹s       # Push input and swap.
            ¶      # Push a newline character.
             ®J    # Retrieve the value from the register and join everything in the stack.
                   # Implicitly output this.

```

Uses **CP-1252** encoding. Try it online!.
> 4 votes

# Answer
# Python 3.5, ~~76~~ ~~75~~ 73 bytes:

(*Thanks to Blue for a tip which saved 2 bytes!*)

```
def i(n):q=len(n);z=('|'+' '*(2+q)+'|\n')*-(-q//2);print(z+'| '+n+' |\n'+z)

```

Try It Online! (Ideone)

Also, here is a **noncompeting Python 2.7.5** version since it is much longer at **87 bytes**.

```
def i(n):q=len(n.decode('utf-8'));z=('|'+' '*(2+q)+'|\n')*-(-q/2);print z+'| '+n+' |\n'+z

```

This is because Python 2's default encoding is `ascii`, and therefore, characters such as  outside the 128 unicode point range count as more than 1 byte (`list('ಠ')` yields `['\xe0', '\xb2', '\xa0']`). The only workaround I could think of for this was to first decode the input using `utf-8`, and then move on with this `utf-8` decoded string.

Try This Python 2 Version Online! (Ideone)
> 4 votes

# Answer
# Dyalog APL, ~~37~~ ~~34~~ 33 bytes

```
{↑'|'{⍺⍵⍺}¨b,(⊂⍵),b←' '/⍨⌈0.5×≢⍵}

```

Chrome users: See footnote\*

### Test cases

```
      f←{↑'|'{⍺⍵⍺}¨b,(⊂⍵),b←' '/⍨⌈0.5×≢⍵}

      f,'☺' ⍝ the , is necessary to create a 1 char string instead of a character scalar
|   |
| ☺ |
|   |
      f':D'
|    |
| :D |
|    |
      f'^_^'
|     |
|     |
| ^_^ |
|     |
|     |

```

---

*<sup>Chrome misdisplays the two characters `≢⍵` (U+2262,U+2375) as `≢⍵` (U+2261,U+0338,U+2375) instead of as `̸≡⍵` (U+0338,U+2262,U+2375), so here is a display version for Chrome: `{↑'|'{⍺⍵⍺}¨b,(⊂⍵),b←' '/⍨⌈0.5×̸̸≡⍵}`</sup>
> 3 votes

# Answer
# Vitsy, 43 bytes

```
IV2m3mz4m2m
3mV\D4m
V1+2/\[1m]
' || '
}}ZaO
```

Explanation:

```
IV2m3mz4m2m

I            Grab the length of the input string.
 V           Save that value to a global final variable.
  2m         Call the method at line index 2.
    3m       Call the method at line index 3.
      z      Push the entire input to the stack.
       4m    Call the method at line index 4.
         2m  Call the method at line index 2.

3mV\D4m

3m           Call the method at line index 3.
  V          Push the global variable to the stack.
   \D        Duplicate the top item on the stack that many times.
     4m      Call the method at line index 4.

V1+2/\[1m]

V            Push the global variable to the stack.
 1+          Add one to the top value.
             REASONING: We want ceil(V/2), and since repeat commands follow the floor value of repeats, we want ceil(V/2)+.5, so we add one to make this work right.
   2/        Divide by two.
     \[1m]   Call method 1 that top value of the stack times.

' || '

' || '       Push ' || ', the string, to the stack.

}}ZaO

}}           Push the bottom item of the stack to the top twice.
  Z          Output everything in the stack.
   aO        Output a newline.

```

Try it online!

~~Note that, due to a bug in TIO, input with unicode characters will not work. You'll have to use the local version instead for those.~~ Thanks, @Dennis!
> 2 votes

# Answer
# V, ~~60~~ 57 bytes

```
I| A |ByWo=ceil(len(""")/2.0)
 dF.d0kwviWr Yu@-pH@-P

```

Unfortunately, V has next to nothing in terms of mathematical operations. The divide and ceil functions *drastically* inflated the byte count.

Since this contains a bunch of nasty unprintables, here is a reversible hexdump:

```
00000000: 497c 201b 4120 7c1b 4279 576f 123d 6365  I| .A |.ByWo.=ce
00000010: 696c 286c 656e 2822 1222 2229 2f32 2e30  il(len("."")/2.0
00000020: 290d 201b 6446 2e64 306b 7776 6957 7220  ). .dF.d0kwviWr
00000030: 5975 402d 7048 402d 50                   Yu@-pH@-P

```

Explanation:

```
I| A |                                #Add surrounding bars
      B                               #Move back
       yW                             #Yank a word
         o                            #Open a new line
          <C-r>=                      #Evaluate

          <C-r>"                      #Insert the yanked text into our evaluation
ceil(len("      ")/2.0)<cr>           #Evaluate ceil(len(text)/2) and insert it

 dF.                                  #Append a space and delete backward to a (.)
                                      #By default, this will be in register "-
    d0                                #Delete this number into register a
      kw                              #Move up, and forward a word
        viWr                          #Replace the emoticon with spaces
             Yu                       #Yank this line, and undo
                                      #(so we can get the emoticon back)
               @-p                    #Paste this text "- times.
                  H                   #Move to the beginning
                   @-P                #Paste this text "- times behind the cursor.

```
> 2 votes

# Answer
# Vyxal `j`, 22 bytes

```
Lð*w?L½⌈ẋfpømƛ‛| p‛ |+

```

Try it Online!

```
Lð*                    # Length spaces
   w    ẋf             # Repeated
    ?L½⌈               # Ceiling of input length/2
          p            # Append input
           øm          # Mirror
             ƛ‛| p‛ |+ # Foreach, prepend '| ' and append ' |'

```
> 2 votes

# Answer
# JavaScript ES6, ~~83~~ 78 bytes

```
e=>(a=`| ${" ".repeat(n=e.length)} |
`.repeat(Math.ceil(n/2)))+`| ${e} |
${a}`

```
> 1 votes

# Answer
## Pyke, 31 bytes

```
"||
"1dQlO*:Ql_2f_*iO"|  |"2Q:i

```

Try it here!

Thanks @R.Kap for saving a byte with the floor divide trick
> 1 votes

# Answer
# Ruby, 57 bytes

Uses integer division tricks and takes advantages of the quirks in Ruby's `puts` function.

```
->e{s=e.size+1;puts k=[?|+' '*-~s+?|]*(s/2),"| #{e} |",k}

```
> 1 votes

# Answer
# Pyth, 30 bytes

I'm surprised that such an easy task isn't implemented in Pyth.

```
Ls[K\|dbdK)j++J*/hlQ2]sym;QyQJ

```

Try it online!
> 1 votes

# Answer
# TSQL, ~~96~~ 88 bytes

```
DECLARE @ varchar(100)='^_^'

PRINT STUFF(REPLICATE('|'+SPACE(2+LEN(@))+'|
',LEN(@)*2-1),LEN(@)*(LEN(@)+5)-3,LEN(@),@)

```

Try online!
> 1 votes

# Answer
# \>\<\>, 103 bytes

```
i:0(?\
}$&1[\~rl:::2%+*:2,
1-:?!\" "$
]{\  \~
?!\$}1-:
~&\
?!\l$:@-[l2)
~]\
}}\" || "
?!\ol
8.>]l?!;ao2

```

Try it online!

This solution is based on the observation that each line consists of `| <x> |`, where `<x>` is the pattern in the middle line, and the same number of spaces in the other lines.

After reading the input (length `n`) from STDIN, the program pushes `n*(n+(n%2))` spaces. The stack is then rolled half as many times. Next, all but `n` characters are pulled to a new stack, leaving a stack of stacks consisting of either `n` spaces or the pattern itself (in the middle stack only). In the output step, the contents of the current stack are printed, surrounded by `|`  and  `|`.
> 1 votes

# Answer
## C, 89 bytes

```
f;main(int c,char**a){for(c=strlen(*++a)+1;f<(c|1);)printf("|%*s |\n",c,f++==c/2?*a:"");}

```

Not sure if it will handle non-ascii emoticon though....
> 1 votes

# Answer
## PowerShell v3+, 72 bytes

```
param($a)$b=("| "+(" "*($l=$a.length))+" |`n")*($l+1-shr1);"$b| $a |";$b

```

Takes input string `$a`. Constructs `$b` as (the empty pipe-ended string (with `$a.length` spaces in the middle) and a trailing newline) repeated (length+1 shifted right one bit, i.e., divided by two and ceiling'd) times. Then outputs the copies of `$b`, the input string with its own pipes, and finally the copies of `$b` again.

Requires v3+ for the bit-shift `-shr` operator.

### Examples

```
PS C:\Tools\Scripts\golfing> .\grow-a-treemote.ps1 '>:-|'
|      |
|      |
| >:-| |
|      |
|      |

PS C:\Tools\Scripts\golfing> .\grow-a-treemote.ps1 '>:`-('
|       |
|       |
|       |
| >:`-( |
|       |
|       |
|       |

```
> 1 votes

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