title: Follow the Path, but is it valid?

text:
# Question
Title: Follow the Path, but is it valid?
# Follow the Path

I got directions to my friend's house, but it looks like his map might have some mistakes. He's expecting me soon, so I need some short code to figure out if I can get there.

# The Challenge

The code should, when given an ASCII representation of a path as input, traverse from the start to the end, and output depending on whether there is a valid path.

# Input

Input is an ASCII representation of a map. It will use only the following symbols:

```
Character = Meaning
(space) = Blocked area
| = Vertical Path
- = Horizontal Path
+ = Intersection
^ or v = Horizontal Bridge
< or > = Vertical Bridge
$ = Start Location
# = End Location

```

# Traversal Rules

* Execution always starts on `$` and will end when all paths are blocked, an infinite loop, or the pointer hits `#`. It is guaranteed that input will have exactly 1 of each.
* The pointer starts moving to the right and down.
* Vertical paths will only connect to vertical paths, vertical bridges, or intersections.
* Horizontal paths will only connect to horizontal paths, horizontal bridges, or intersections.
* If a vertical and horizontal path meet at a non-bridge, it is considered blocked at that point.
* Bridges function according to the following:

```
 |      |
-^- OR -v- = Horizontal path going over a vertical path
 |      |

 |      |
-<- OR ->- = Vertical path going over a horizontal path
 |      |

```
* When the pointer hits an intersection, movement precedence is in the clockwise direction (up, right, down, left). The pointer will not go back the way it came.
* The program must detect/calculate infinite loops and branching paths from `+`.

# Output

The length of the path, or `-1`, according to the following conditions:

* If the program reaches `#`, output the path length.
* If the program detects only blocked paths, return `-1`.
* If the program detects an infinite loop, return `-1`.

# Scoring

This is , so the shortest code in bytes wins! Standard loopholes are forbidden.

# Test Cases

```
   $
   |
 +-|
#+-+
= 6 (going north at `#+-` will lead to a blocked path, but going to the west is a valid path)

#-+-+
  | |
$-^-+
  +-+
= -1 (Will infinitely loop)

$#
= 1

#^^^^+
     >
$----^-+
     > +
     +-+
= 20

$------+
|-----+|
 --#--+|
+--+---+
+------+
= 23

$ #
= -1 (Blocked by the space)

$|#
= -1 (Can't go onto a vertical path from the sides)

$
-
#
= -1 (Can't go onto a horizontal path from the top or bottom)

$|#
|--|
++++
= -1 (No valid paths exist)

```

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

Takes input as a list of lists of characters.

```
a=>((g=(X,Y,D,n=o=0)=>!(a+0)[n++]|a.some((r,y)=>r.some((c,x)=>D=='975'[i='-| #+$'.indexOf(c),x-X+1]-'450'[y-Y+1]?i-3?i-2?i>3?[3,0,7,4].some(d=>D^d^4&&g(x,y,d,n)):~i&&i^D&1?0:g(x,y,D,n):0:o=-n:X+1|i<5?0:g(x,y,2))))(),~o)

```

Try it online!

### How?

Because they need to be tried in a specific order, the way the directions are handled in this code is a bit unusual.

Given a direction \\$D\\$ and the source coordinates \\$(X,Y)\\$, we want to figure out which target coordinates \\$(x,y)\\$ correspond to a move by one square along \\$D\\$.

We use the following test for each candidate pair \\$(x,y)\\$:

```
D == '975'[x - X + 1] - '450'[y - Y + 1]

```

This test always fails if \\$|x-X|\>1\\$ or \\$|y-Y|\>1\\$ because we get an undefined value from at least one of the 2 lookup strings.

Otherwise, we have the following table:

$$\begin{array}{r|c|ccc} &x-X&-1&0&+1\\ \hline y-Y&&9&7&5\\ \hline -1&-4&5&3&1\\ 0&-5&4&2&0\\ +1&-0&9&7&5 \end{array}$$

Because diagonal moves are not used, our final compass looks as follows:

$$\begin{array}{cccc} &&3\\ &&↑\\ 4&←&2&→&0\\ &&↓\\ &&7 \end{array}$$

The lookup values were chosen in such a way that we end up with some handy properties:

* Opposite directions can be detected by testing if \\$d\operatorname{xor}d'=4\\$. Hence the code to try all directions in clockwise order except the one that would make us going back the way we came:

```
  [3, 0, 7, 4].some(d => D ^ d ^ 4 && g(x, y, d, n))

```
* Vertical moves are connected to odd values.
* Horizontal moves are connected to even values (except direction \\$2\\$, for no move at all, which is only used at the beginning of the process when the starting point has been identified).

# Answer
> 2 votes
# Python3, 934 bytes:

```
E=enumerate
V=lambda b,X,Y:0<=X<len(b)and 0<=Y<len(b[0])and b[X][Y]!=' '
def U(D,x,X):D[x]=D.get(x,[])+[X];D[X]=D.get(X,[])+[x]
def f(b):
 m,W=[[0,1,'-^'],[1,0,'|>'],[0,-1,'-^'],[-1,0,'|>']],{'^':'-','>':'|'}
 x,y=[[x,y]for x,r in E(b)for y,t in E(r)if'$'==t][0]
 q,D=[(x,y,0,not V(b,x,y+1))],{}
 while q:
  x,y,p,l=q.pop(0)
  if'#'==b[x][y]:return p
  if b[x][y]in'>^':
   for j,k,I in[(X,Y,i)for i,(X,Y,u)in E(m)if b[x][y]in u]+[(m[l][0],m[l][1],l)]:
    if(x+j,y+k)not in D.get((x,y),[])and(b[x+j][y+k]in'>#^+'or b[x+j][y+k]==W[b[x][y]]):U(D,(x,y),(x+j,y+k));q+=[(x+j,y+k,p+1,I)];break
  elif'+'==b[x][y]:
   T,O=[0,1,2,3],[]
   for i in T[l:]+T[:l]:
    if V(b,X:=x+m[i][0],Y:=y+m[i][1])and(X,Y)not in D.get((x,y),[]):
     if'#'==b[X][Y]:return p+1
     O+=[((X,Y),i)]
   if O:U(D,(x,y),O[0][0]);q+=[(*O[0][0],p+1,O[0][1])]
  elif V(b,X:=x+m[l][0],Y:=y+m[l][1])and b[X][Y]in(m[l][2]+'#+'):U(D,(x,y),(X,Y));q+=[(X,Y,p+1,l)]

```

Try it online!

---
Tags: code-golf, ascii-art, decision-problem, path-finding
---


title: Lowest-Base Palindrome

text:
# Question
Title: Lowest-Base Palindrome
Given a number \\$n\\$, write a program that finds the smallest base \\$b ≥ 2\\$ such that \\$n\\$ is a palindrome in base \\$b\\$. For example, an input of \\$28\\$ should return the base \\$3\\$ since \\$28\_{10} = 1001\_3\\$. Although \\$93\\$ is a palindrome in both base \\$2\\$ and base \\$5\\$, the output should be \\$2\\$ since \\$2\<5\\$.

## Input

A positive integer \\$n \< 2^{31}\\$.

## Output

Return the smallest base \\$b ≥ 2\\$ such that the base \\$b\\$ representation of \\$n\\$ is a palindrome. Do not assume any leading zeros.

Samples (input =\> output):

> \\$11 \to 10\\$
>
> \\$32 \to 7\\$
>
> \\$59 \to 4\\$
>
> \\$111 \to 6\\$

## Rules

The shortest code wins.

# Answer
> 3 votes
# CJam, 19 bytes / GolfScript, 23 bytes

```
q~:N;1{)_N\b_W%=!}g

```

or

```
~:N;1{).N\base.-1%=!}do

```

Try it online:

### Examples

```
$ cjam base.cjam <<< 11; echo
10
$ cjam base.cjam <<< 111; echo
6
$ golfscript base.gs <<< 11
10
$ golfscript base.gs <<< 111
6

```

### How it works

```
q~:N;   # Read the entire input, interpret it and save the result in “N”.
1       # Push 1 (“b”).
{       #
  )     # Increment “b”.
  _N\   # Duplicate “b”, push “N” and swap.
  b     # Push the array of digits of “N” in base “b”.
  _W%   # Duplicate the array and reverse it.
  =!    # Compare the arrays.
}g      # If they're not equal, repeat the loop.

```

For GolfScript, `q~` is `~`, `_` is `.`, `b` is `base`, `W` is `-1` and `g` is `do`.

# Answer
> 5 votes
### GolfScript, 20 characters

```
~:x,2>{x\base.-1%=}?

```

A different approach with GolfScript other than Dennis'. It avoids the costly explicit loop in favour of a *find* operator. Try online.

```
~:x        # interpret and save input to variable x
,2>        # make a candidate list 2 ... x-1 (note x-1 is the maximum possible base)
{          # {}? find the item on which the code block yields true
  x\       # push x under the item under investigation
  base     # perform a base conversion
  .-1%     # make a copy and reverse it
  =        # compare reversed copy and original array
}?

```

# Answer
> 4 votes
## Mathematica, ~~67~~ 66 bytes

```
g[n_]:=For[i=1,1>0,If[(d=n~IntegerDigits~++i)==Reverse@d,Break@i]]

```

Can't really compete with GolfScript here in terms of code size, but the result for 232 is basically returned instantly.

# Answer
> 4 votes
# Japt, ~~12~~ 9 bytes

Unless I've missed a trick (it's late!), this should work for all numbers up to and including at least `2**53-1`.

In my (admittedly limited and entirely random) testing, I've gotten results up to base ~~`11601`~~ `310,515`(!) so far. Not too shabby when you consider JavaScript only natively supports bases `2` to `36`.

```
@ìX êê}a2

```

Try it

* Thanks to ETH for pointing out something new to me that saved 3 bytes and increased the efficiency considerably.

---

## Explanation

Implicit input of integer `U`.

```
@     }a2

```

Starting with `2`, return the first number that returns true when passed through the following function, with `X` being the current number

```
ìX

```

Convert `U` to an array of base `X` digits.

```
êê

```

Test if that array is a palindrome.

# Answer
> 2 votes
## JavaScript, 88 bytes

```
f=function(n){for(a=b='+1';a^a.split('').reverse().join('');a=n.toString(++b));return+b}

```

**Ungolfed:**

```
f = function(n) {
    for(a = b = '+1'; // This is not palindrome, but equals 1 so we have at least one iteration
        a ^ a.split('').reverse().join(''); // test a is palindrome
        a = n.toString(++b));
    return+b
}

```

# Answer
> 2 votes
# J - 28 char

```
#.inv~(-.@-:|.@)(1+]^:)^:_&2

```

Explained:

* `#.inv~` \- Expand left argument to the base in the right argument.
* `(-.@-:|.@)` \- Return 0 if the expansion is palindromic, and 1 otherwise.
* `(1+]^:)` \- Increment the right argument by one if we returned 1, else take no action.
* `^:_` \- Repeat the above incrementing until it takes no action.
* `&2` \- Prepare the right argument as 2, making this a function of one argument.

Examples:

```
   #.inv~(-.@-:|.@)(1+]^:)^:_&2 (28)
3
   #.inv~(-.@-:|.@)(1+]^:)^:_&2 every 93 11 32 59 111  NB. perform on every item
2 10 7 4 6
   #.inv~(-.@-:|.@)(1+]^:)^:_&2 every 1234 2345 3456 4567 5678 6789
22 16 11 21 31 92

```

# Answer
> 1 votes
# Python 2, 79 bytes

```
def f(n,b=2):
 l=[];m=n
 while m:l+=m%b,;m/=b
 return(l==l[::-1])*b or f(n,b+1)

```

Try it online!

*-1 bytes thanks to 97.100.97.109*

I'm not sure what input/output format the question wanted. I wrote a function. The code uses an optional input `b` to track the current base it's testing. The `while` loops converts the number to a list of digits in base `b`.

The last line returns `b` if `l` is a palindrome, and recursively tries the next `b` otherwise. The index-by-Boolean trick doesn't work here because it would cause both options to be evaluated regardless of the Boolean, and the recursion would never bottom out.

# Answer
> 1 votes
# Javascript, 105 bytes

```
function f(n){for(var b=2,c,d;d=[];++b){for(c=n;c;c=c/b^0)d.push(c%b);if(d.join()==d.reverse())return b}}

```

**JSFiddle:** http://jsfiddle.net/wR4Wf/1/

Note that this implementation also works correctly for large bases. For example, `f(10014)` returns 1668 (10014 is 66 in base 1668).

# Answer
> 1 votes
## R, ~~122~~ 95 bytes

```
function(n)(2:n)[sapply(2:n,function(x){r={};while(n){r=c(n%%x,r);n=n%/%x};all(r==rev(r))})][1]

```

**Three-year old solution at 122 bytes:**

```
f=function(n)(2:n)[sapply(sapply(2:n,function(x){r=NULL;while(n){r=c(n%%x,r);n=n%/%x};r}),function(x)all(x==rev(x)))][1]

```

With some explanations:

```
f=function(n)(2:n)[sapply(
                    sapply(2:n,function(x){ #Return the decomposition of n in bases 2 to n
                                 r=NULL
                                 while(n){
                                     r=c(n%%x,r)
                                     n=n%/%x}
                                     r
                                     }
                           ),
                    function(x)all(x==rev(x))) #Check if palindrome
                   ][1] #Return the first (i. e. smallest) for which it is

```

# Answer
> 1 votes
# Bash + coreutils, 100 bytes

```
for((b=1;b++<=$1;)){
p=`dc<<<${b}o$1p`
c=tac
((b<17))&&c=rev
[ "$p" = "`$c<<<$p`" ]&&echo $b&&exit
}

```

Uses `dc` to do base formatting. The tricky thing is `dc`'s format is different for n \> 16.

Testcases:

```
$ ./lowestbasepalindrome.sh 11
10
$ ./lowestbasepalindrome.sh 32
7
$ ./lowestbasepalindrome.sh 59
4
$ ./lowestbasepalindrome.sh 111
6
$

```

# Answer
> 1 votes
# Husk, ~~11~~ 9 bytes

```
ḟoS=↔`B⁰2

```

Thanks @Zgarb for -2!

Try it online!

### Explanation

```
ḟ(      )2  -- find least number ≥ 2 that satisfies:
     `B⁰    --   convert input to base (` flips arguments)
  S=↔       --   is palindrome (x == ↔x)

```

# Answer
> 0 votes
### Note: Pyth is newer than this question, so this answer is not eligible to win.

# Pyth, 10 bytes

```
fq_jQTjQT2

```

Try it here.

# Answer
> 0 votes
# Scala, 83 bytes

```
def s(n:Int)=(for(b<-2 to n;x=Integer.toString(n,b);if(x==x.reverse))yield(b)).min

```

# Answer
> 0 votes
# 05AB1E, 8 bytes

```
¼[¼¾вÂQ#

```

Try it online!

# Answer
> 0 votes
# Perl 5, 84 + 1 (-p) = 85 bytes

```
$\=1;{++$\;my@r;$n=$_;do{push@r,$n%$\}while$n=int$n/$\;@t=@r;map$_-pop@t&&redo,@r}}{

```

Try it online!

# Answer
> 0 votes
# JavaScript 72 bytes

```
F=(n,b=2)=>eval(`for(t=n,a=c="";t;t=t/b|0)a=t%b+a,c+=t%b`)^a?F(n,b+1):b

console.log(F(11) == 10)

console.log(F(32) == 7)

console.log(F(59) == 4)

console.log(F(111) == 6)
```

# Answer
> 0 votes
# Mathematica 42 bytes

A variation of Martin Ender's entry. Makes use of `IntegerReverse` (made available in version 10.3) which dispenses with `IntegerDigits`.

```
(i=2;While[#~IntegerReverse~i !=#,i++];i)&

```

# Answer
> 0 votes
# Java 8, 103 bytes

```
n->{int b=1,l;for(String s;!(s=n.toString(n,++b)).equals(new StringBuffer(s).reverse()+""););return b;}

```

**Explanation:**

Try it here.

```
n->{                          // Method with integer as both parameter and return-type
  int b=1,                    //  Base-integer, starting at 1
      l;                      //  Length temp integer
  for(String s;               //  Temp String
      !(s=n.toString(n,++b))  //   Set the String to `n` in base `b+1`
                              //   (by first increase `b` by 1 using `++b`)
       .equals(new StringBuffer(s).reverse()+"");
                              //   And continue looping as long as it's not a palindrome
  );                          //  End of loop
  return b;                   //  Return the resulting base integer
}                             // End of method

```

# Answer
> 0 votes
# Jelly, 8 bytes

```
2b@ŒḂ¥1#

```

Try it online!

## How it works

```
2b@ŒḂ¥1# - Main link. Takes an integer n on the left
     ¥   - Group the previous 2 links into a dyad f(b, n):
 b@      -   Convert n to base b
   ŒḂ    -   Is palindrome?
2     1# - Count up b = 2, 3, 4, ... returning the first b that's true under f(b, n)

```

# Answer
> 0 votes
# Ruby, 43 bytes

-1 byte thanks to Steffan

```
->n{(2..).find{d=n.digits _1
d==d.reverse}}

```

Attempt This Online!

---
Tags: code-golf, palindrome, base-conversion
---


title: Play Caesar's Cipher with Letters only

text:
# Question
Title: Play Caesar's Cipher with Letters only
# Description

The Caesar cipher is a cipher, where every letter in the alphabet will be rotated by a secret number.
If the rotation is \\$7\\$, then `a` -\> `h`, `g` -\> `n`, `v` -\> `c` and `z` -\> `g`.

Today, we're playing Caesar's Cipher with ASCII chars, (0-127 inclusive). So, with rotation \\$7\\$, `b` -\> `i`, `Z` -\> `a`, `x` -\> `DEL (127)`,

But, even if the encoder shifted the chars around the ASCII table, you know, that the original string consisted of only the lowercase, uppercase alphabet, and space.

# Task

You're given a string of ASCII code points, your task is to print all of the possible original strings if the encoder only used the lowercase and the upper case alphabet (plus space) in the original string.

# Rules

* The program must take the ASCII char codes of the encoded string as the input
* The encoded string is not constricted on lowercase, uppercase, and space, it can (because it's ASCII shifted) include ASCII chars
* The output must be all possible original strings (as a list, separated by newlines, etc.)
* Default loopholes apply
* Lowercase, uppercase, and space: `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`
* This is , so the shortest answer wins!

---

# Examples

```
[In]: [91, 111, 112, 122, 39, 112, 122, 39, 104, 39, 123, 108, 122, 123, 39, 116, 108, 122, 122, 104, 110, 108]
[Out]: This is a test message

[In]: [43, 35, 49, 49, 31, 37, 35]
MESSAGE
NFTTBHF
OGUUCIG
PHVVDJH
QIWWEKI
RJXXFLJ
SKYYGMK
TLZZHNL
message
nfttbhf
oguucig
phvvdjh
qiwweki
rjxxflj
skyygmk
tlzzhnl

[In]: [103, 123, 120, 51, 97, 124, 1, 120, 7, 120, 120, 1, 7, 123, 51, 85, 12, 7, 120]
[Out]: The Nineteenth Byte
[In]: [78, 82, 78, 78]
[Out]:
NRNN
OSOO
PTPP
QUQQ
RVRR
SWSS
TXTT
UYUU
VZVV
aeaa
bfbb
cgcc
dhdd
eiee
fjff
gkgg
hlhh
imii
jnjj
kokk
lpll
mqmm
nrnn
osoo
ptpp
quqq
rvrr
swss
txtt
uyuu
vzvv
AEAA
BFBB
CGCC
DHDD
EIEE
FJFF
GKGG
HLHH
IMII
JNJJ
KOKK
LPLL
MQMM

```

# Answer
> 4 votes
# Jelly, 16 bytes

```
+ⱮØ⁷%Ø⁷ỌfƑƇØẠ;⁶¤

```

A monadic Link that accepts a list of code-points and yields a list of lists of characters.

**Try it online!**

### How?

```
+ⱮØ⁷%Ø⁷ỌfƑƇØẠ;⁶¤ - Link: list of code-points C
  Ø⁷             - 128
 Ɱ               - map (across v in [1..128]) with:
+                -   C add v (vectorises)
    %Ø⁷          - modulo 128
       Ọ         - convert to characters (list of potentials, P)
               ¤ - nilad followed by link(s) as a nilad:
           ØẠ    -   alphabetic characters
              ⁶  -   space character
             ;   -   concatenate (list of characters "A..Za..z ", A)
          Ƈ      - filter keep those p in P for which:
         Ƒ       -   is invariant under:
        f        -     p filter keep only those in A

```

# Answer
> 4 votes
# , 82 bytes

```
\(s)for(i in 0:127)if(all((x=(s+i)%%128)%in%c(32,97:122,65:90)))show(intToUtf8(x))
```

Attempt This Online!

---

With the use of `grepl` instead of filtering char codes:

### , 84 bytes

```
\(s)for(i in 0:127)if(!grepl("[^ a-z]",v<-intToUtf8(x<-(s+i)%%128),T)&all(x))show(v)
```

Attempt This Online!

`intToUtf8` has some weird behaviour with the input of `0` (it omits that char altogether) - the workaround here is using `all` to filter that out.

# Answer
> 3 votes
# Perl 5 `-na`, 45 bytes

```
y//\1-\x7f\0/c,/[^\pL ]/||say for(pack'C*',@F)x128

```

Try it online!

The program works as is, but replace `\0`, `\1` and `\x7f` with their literal equivalents for the claimed score.

Very simple approach. 128 times, translate `\0-\x7f` to `\1-\x7f\0`, thus shifting each char by one, and check whether it meets the criteria.

# Answer
> 3 votes
**Based on ophact's answer.** (Sadly I don't have the reputation to comment this instead of duplicating it like this)

# Python 3.8+, 97 bytes

```
lambda l:[b for i in range(128)if(b:=bytes(i+c&127for c in l))*all(c==32or 64<c&95<91for c in b)]

```

Try it online!

Since both A-Z and a-z are permitted, we can ignore the "case bit" `0x20` (`c | 0x20` or `c & 0x5f`) to get a single range for the letters. There's no need to worry about the out of bounds `0x80`.
As we can write `0x5b` (`b'Z'[0]+1`) as `91`, while `0x7b` (`b'z'[0]+1`) could only be as short as `123` (and `0x20==32` is as expensive as `0x5f==95`), we'll choose the uppercase letters' range.
`bytes([1,2,3])` is, for all purposes I can think of "just read-only `[1,2,3]`" while already being something string-like we can return.

# Python 3.8+, 105 bytes

If it **has to** output `str` instead for some reason, we need to add a `.decode()`:

```
lambda l:[w.decode()for i in range(128)if(w:=bytes(c+i&127for c in l))*all(64<c&95<91or c==32for c in w)]

```

Try it online!

~~Is it required to be a `lambda`? Just the business part would be 86 bytes.~~

~~```
b for i in range(128)if(b:=bytes(i+c&127for c in l))*all(c==32or 64<c&95<91for c in b)

```
You would get the same output by giving the input in the variable `l` and writing something like
~~

~~`sys.stdout.buffer.write(b'\n'.join(`
-paste here-
`))`~~

# Answer
> 2 votes
# 05AB1E, ~~18~~ 16 bytes

```
₅ÝIδ+žy%êçʒðKDáQ

```

Outputs as a list of list of characters.

Try it online or verify all test cases.

**Explanation:**

```
₅Ý        # Push a list in the range [0,255]
          # (255 is the lowest single-byte value above 127)
   δ      # Map over this list of integers:
  I +     #  Add the integer to each value in the input-list
     žy%  # Modulo-128
        ê # Sorted uniquify this list of lists
ç         # Convert each inner-most integer to a character with this codepoint
 ʒ        # Filter this list of lists of characters by:
  ðK      #  Remove all spaces
    D     #  Duplicate it
     á    #  Only keep all ASCII letters
      Q   #  Check if both lists are the same
          # (after which the filtered list is output implicitly)

```

# Answer
> 2 votes
# JavaScript (Node.js), 85 bytes

```
a=>[...Array(128)].flatMap(_=>/[^a-z ]/i.test(s=Buffer(a=a.map(c=>c+1&127))+'')?[]:s)

```

Try it online!

# Answer
> 2 votes
# Vyxal, ~~17~~ 15 bytes

```
₇ƛ⁰+₇%C;U'kBṄ↔⁼

```

Try it Online!

-2 thanks to @lyxal

Explanation is for my old code:

```
₇ƛ⁰+₇%Cṅ;U'ðkB+↔= # This comment line needs some love
₇                 # 128, implicitly cast to `0..128`
 ƛ      ;         # Map to...
  ⁰+              # The input plus the offset
    ₇%            # Modulo 128
      Cṅ          # Converted into a string
         U        # Remove duplicates
          '       # Filter by...
                = # Is the original string equal to...
               ↔  # The string with the following chars removed
           ðkB+   # " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

```

# Answer
> 2 votes
## PHP 4 (123 chars)

The function **f** is accepting an encoded string.

```
function f($s){for($i=128;$i-=print chop($s,'A..Za..z ')?'':"$s\n";)for($j=strlen($s);$j--;)$s[$j]=chr(1+ord($s[$j])%128);}

```

# Answer
> 1 votes
# BQN, 39 bytesSBCS

Returns a matrix with one possible original per row.

```
128⊸|{@++⌜˜(∊/⊣)˝-˜⌜32∾⥊65‿97+⌜↕26}

```

Run online!

This computes the possible shifts for each character, takes the intersection, and shifts the input by all remaining numbers.
Generating all shifts and then only keeping alphabetic ones is 2 bytes longer:

```
@+·(∧´˘∊⟜(32∾⥊65‿97+⌜↕26))⊸/128|(↕128)+⌜⊢

```

Run online!

# Answer
> 1 votes
# Python 3.8 (pre-release), 117 bytes

```
lambda l:[''.join(map(chr,w))for i in range(128)if(w:=[c+i&127for c in l])*all(64<c<91or 96<c<123or c==32for c in w)]

```

Try it online!

Yep... that long.

Nothing much to say here; simply loops through the numbers from 0-127 and keeps the word found by shifting by that many units if all characters in such a word are part of the required alphabet.

# Answer
> 1 votes
# JavaScript (Node.js), 78 bytes

```
x=>Buffer(128).map(_=>/[^ a-z]/i.test(x=x.map(y=>y+1&127))||console.log(''+x))

```

Try it online!

# JavaScript (Node.js), 83 bytes

```
a=>[...Array(128)].flatMap(_=>/[^a-z ]/i.test(a=Buffer(a.map(c=>c+1&127)))?[]:a+'')

```

Try it online!

Handleing part already near Arnauld enough, so I place it here

# Answer
> 1 votes
# Charcoal, 24 bytes

```
ΦＥ¹²⁸⭆θ℅﹪⁺ιλ¹²⁸⬤ι№⁺⁺αβ λ

```

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

```
  ¹²⁸                       Literal integer `128`
 Ｅ                          Map over implicit range
      θ                     Input array
     ⭆                      Map over elements and join
          ι                 Outer value
         ⁺                  Plus
           λ                Inner value
        ﹪                   Modulo
            ¹²⁸             Literal integer `128`
       ℅                    Convert from ASCII code
Φ                           Filtered where
                ι           Current string
               ⬤            All characters satisfy
                 №          (Non-zero) Count of
                       λ    Current character in
                    α       Uppercase letters
                   ⁺        Concatenated with
                     β      Lowercase letters
                  ⁺         Concatenated with space
                            Implicitly print each solution on its own line

```

# Answer
> 1 votes
# C (gcc), ~~159~~ 136 bytes

* -23 bytes thanks to ceilingcat

As `NUL` is a valid character, also takes the counted string length. The function first iterates through each shifted string to verify that all the decoded characters are valid (and bails early if not), then prints the shifted string if it is still valid.

```
#define v;for(r=0;a&&r<l;r++
a,h,r,c;f(s,l)char*s;{for(h=128;a=h--;a&&puts("")){v)a=isalpha(c=s[r]+h&127)|c==32 v)putchar(s[r]+h&127);}}

```

Try it online!

# Answer
> 1 votes
# Perl 5, 63 bytes

```
sub{grep!/[^a-z ]/i,map{//;join'',map chr($_+$'&127),@_}0..127}

```

Try it online!

# Answer
> 1 votes
# Behaviour, 78 bytes

```
u=&(127*&(f=a;s=c*&(f+a)%127~(s<~&[a==32(a>64a<91)(a>96a<123)])@s*ascii>&a+b))

```

test with:

```
@u:c={43 35 49 49 31 37 35}
@u:c={91 111 112 122 39 112 122 39 104 39 123 108 122 123 39 116 108 122 122 104 110 108}

```

ungolfed and commented:

```
uncypher = &(
  127*&(  // do the following sequence 127 times
    off = a  // get offset from iterator
    s = c*&(off+a)%128  // rotate each character from /c by the offset
    ~(s<~&[  // stop sequence if the previous result has any invalid character
      (a==32)
      (a>64 a<91)
      (a>96 a<123)
    ])
    @(s*ascii)>&a+b // convert ascii num to char, reduce to string and print
  )
)

```

# Answer
> 1 votes
# Factor, 84 bytes

```
[ 128 iota [ '[ _ + 128 mod ] ""map-as ] with [ R/ [a-z ]+/i matches? ] map-filter ]

```

Try it online!

# Answer
> 1 votes
# APL+WIN, 74 bytes

Prompts for code points

```
⎕av[((⍴n)=+/m∊(i,53)⍴32,∊(⊂65 97)+¨⍳26)⌿m←i|((i,⍴n)⍴n)+⍉((⍴n←⎕),i)⍴⍳i←128]

```

Unfortunately Dyalog APL Classic's atomic vector does not line up with ASCII code points whereas APL+WIN does so I cannot demonstrate via TIO as I would do normally.

# Answer
> 1 votes
# Ruby, 66 bytes

```
->a{(1..127).map{|n|a.map{((_1+n)%128).chr}*""}.grep /^[a-z ]+$/i}

```

Attempt This Online!

---
Tags: code-golf, string, puzzle-solver, cipher
---


# Question
Title: Convert a string of ASCII characters to base-3 equivalents
Task similar to this one. Take a string of ASCII characters and convert it to base-3 equivalents separated by a space.

For example:

```
Hello, world!

```

Should be converted to

```
02200 10202 11000 11000 11010 01122 01012 11102 11010 11020 11000 10201 01020

```

The output should only contain numbers with the same number of digits. Which separator to use is up to you.

This is a code-golf challenge so the shortest solution wins.

# Answer
> 9 votes
# MATL, 3 bytes

```
3YA

```

Uses newline as separator. **Try it online!**

### Explanation (by @Sundar R)

`YA` is a single function, corresponding to Matlab's `dec2base` (convert from decimal to some base). By default it takes two arguments: an array with the numbers to convert and the base to convert to. Since only the second argument (`3`) is specified here, the input is implicitly used as the first argument.

The cool part is that this is automatically applied to the whole input (which is a char array), the results collected into a char matrix, and when things don't line up, `0`'s are automatically prepended to make them have the same width.

# Answer
> 5 votes
# Python 3,  ~~70 66~~  62? 66 bytes

```
for c in input():print(*[ord(c)//d%3for d in b'Q    '],sep='')

```

(Code contains unprintable bytes inside the `b'...'`)

A full program accepting input from STDIN that prints the result using a newline separator (with a trailing newline).

**Try it online!**

---

...but 66 if we need to handle multi-line strings (since `input()` only reads one line:

```
lambda s:[print(*[ord(c)//d%3for d in b'Q   '],sep='')for c in s]

```

An unnamed function that prints the answer.

Try it online!

# Answer
> 4 votes
# Jelly, 9 bytes

All-ASCII jelly code to boot...

```
Ob3Uz0ZUK

```

A full program accepting a string that prints the result.

**Try it online!**

### How?

```
Ob3Uz0ZUK - Main Link: list of characters
O         - ordinals
 b3       - to base three
   U      - upend (reverse each)
    z0    - transpose with filler of zero
      Z   - transpose
       U  - upend (reverse each)
        K - join with spaces
          - implicit, smashing print

```

# Answer
> 3 votes
# Python 3, 71 bytes

```
import numpy
for i in input():print(numpy.base_repr(ord(i),3).zfill(5))

```

Try it online!

-30 thanks to Jonathan Allan, I'm lazy to golf another code

Prints numbers separated by newlines

If you really need space as a separator then here is the code:

# Python 3, 176 bytes

```
import numpy
m=input()
y=m[:-1]
u=lambda x:"0"*(5-len(x))+x
for i in y:print(u(str(numpy.base_repr(ord(i),base=3))),end = " ")
print(u(str(numpy.base_repr(ord(m[-1]),base=3))))

```

Try it online!

# Answer
> 3 votes
# Charcoal, 14 bytes

```
⪫ＥＳ⭆◧⍘℅ι³¦⁵Σλ

```

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

```
  Ｓ             Input string
 Ｅ              Map over characters
       ι        Current character
      ℅         ASCII code
     ⍘  ³       Convert to base 3
    ◧     ⁵     Left pad to length 5
   ⭆            Map over characters and join
            λ   Inner character
           Σ    Numeric value if any
⪫               Join with spaces
                Implicitly print

```

12 bytes to print as a list:

```
ＵＢ0←Ｅ⮌Ｓ⮌⍘℅ι³

```

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

```
ＵＢ0

```

Set output to zero fill.

```
←Ｅ⮌Ｓ⮌

```

Output the strings upside-down and reversed (which right-justifies them) given by...

```
⍘℅ι³

```

... converting the ASCII codes to base 3.

# Answer
> 3 votes
# Javascript (Node.js), ~~62~~ 59 bytes

```
f=

x=>[...x].map(t=>(t.charCodeAt()+243).toString(3).slice(1))

console.log((f+'').length);
console.log(f("Hello World!")+'');
```

Try it online!

-3 thanks to @tsh

# Answer
> 3 votes
# , ~~63~~ 59 bytes

```
function(s)write(rep(utf8ToInt(s),e=5)%/%3^(4:0)%%3,1,,,"")

```

Try it online!

~~Nothing clever, but a straightforward implementation in R is shorter than anything else that I can think of so far...~~
To avoid the penalty of defining a base-conversion `function` to use on each character, we repeat each character value 5 times, and then use vectorized integer division (`%/%`) and modulo (`%%`) to calculate all the base-3 digits. Then, by lucky co-incidence, the `write` function splits its output data into a column width of 5 by default.

# Answer
> 3 votes
# Vyxal, 9 bytes

```
C3τvṅ5∆Z⁋

```

Uses newline as the separator.

```
C3τvṅ5∆Z⁋
C            Convert to ASCII codepoint
 3τ          Convert each character to base 3
   vṅ        Join by nothing, because to-base returns a list of digits
     5∆Z     Pad with 5 zeros (because that's the max length of an ASCII char)
        ⁋    Join by newlines

```

Try it Online!

It will probably get 9 bytes soon, because of a bug (to-base doesn't support vectorization)
Lyxal epic speed bug fix done

Actually, 8 bytes with flag, but `j` is very buggy

# Answer
> 3 votes
# Factor, ~~38~~ 34 bytes

```
[ [ 3 >base "%05s "printf ] each ]

```

Try it online!

* `[ ... ] each` For each code point in the input string,
* `3 >base` convert it to base 3
* `"%05s "printf` and print it with leading zeros to a length of five, followed by a space.

# Answer
> 2 votes
# GeoGebra, ~~74~~ 50 bytes

```
Zip(Take(ToBase(a,3),2,6),a,TextToUnicode("")+243)

```

Insert string input between the `""`. (I guess this is allowed) Output is a list of strings padded to 5 digits. (This is also allowed by OP)

Uses the " add \\$3^5\\$ " idea from @DLosc's answer.

Try It On GeoGebra!

# Answer
> 2 votes
# BQN, 20 bytes

```
{'0'+3|⌊÷3⋆⌽↕5}¨-⟜@

```

Anonymous function that takes a string and returns a list of strings. Run it online!

If a list of lists of digits is an acceptable output format, then it's 16 bytes:

```
{3|⌊÷3⋆⌽↕5}¨-⟜@

```

### Explanation

```
{'0'+3|⌊÷3⋆⌽↕5}¨-⟜@
                  -⟜@  Subtract '\0' from each character, converting to list of charcodes
{               }¨      Map this function to each charcode:
              ↕5          Range(5)
            ⌽            Reverse
          3⋆              3 to the power of each
        ÷                Divide the argument by each
       ⌊                  Floor
     3|                   Mod 3
 '0'+                     Convert digits to characters by adding '0'

```

# Answer
> 1 votes
# Burlesque, 14 bytes

```
)**m{3B!5'0P[}

```

Try it online!

```
)**     # Map ord
m{      # Map
 3B!    # To base 3
 5'0P[  # Pad to length 5 using "0"s
}

```

# Answer
> 1 votes
# APL+WIN, 22 bytes

Prompts for ASCII string. Index origin = 0

```
(⍕¨(⊂5⍴3)⊤¨⎕av⍳⎕)~¨' '

```

Most of the bytes are taken by formatting the output.

# Answer
> 1 votes
# Husk, 11 bytes

```
m(↑_5ṁsΘB3c

```

Try it online!

5 bytes (`m(B3c`) to calculate the base-3 representation of each ASCII character, but then 6 more bytes to format the output: prepend a zero (`Θ`), get string representation of digits (`s`), flatten together (), and take the last 5 elements (`↑_5`).

If it's acceptable for the base-3 digits to be space-separated (and the groups to be newline-separated), then we could do it in 10 bytes: `m(w↑_5ΘB3c`.
If we insist on space-separating the non-separated base-3 digits (exactly as in the example), it'll cost 12 bytes: `wm(↑_5ṁsΘB3c`.

# Answer
> 1 votes
# Haskell, ~~72 64~~ 62 bytes

```
unwords.map(\c->show.(`mod`3).div(fromEnum c)=<<[81,27,9,3,1])

```

Try it online!

* Saved 8+2 Bytes thanks to @ovs suggestions.

Couldn't find any golfy way for the list of powers of 3: tried (3^)\<$\>\[4,3..0\] with no gains.

# Answer
> 1 votes
# C (gcc), 72 bytes

```
i;f(char*s){for(;*s;++s,putchar(32))for(i=243;i/=3;)putchar(48+*s/i%3);}

```

Try it online!

# Answer
> 0 votes
# Pip, 15 bytes

```
S3E5+A_TB3MaJ:s

```

Attempt This Online!

Or, using the `-s` flag to do the output formatting, **12 bytes**:

```
S3E5+A_TB3Ma

```

Attempt This Online!

### Explanation

Pip doesn't have any padding builtins as of this writing, so we do the following instead: Add \\$3^5\\$ to each codepoint; convert to base 3, resulting in a 6-digit number that always has a leading 1; and slice off the first digit.

```
S3E5+A_TB3MaJ:s
           a     ; First command-line argument
          M      ; Map this function to each of its characters:
     A_          ;   ASCII code of the character
 3E5+            ;   Add 3 to the 5th power
       TB3       ;   Convert to base 3
S                ;   Suffix containing all but the first character
            J:   ; Join the resulting list on
              s  ; Space

```

# Answer
> 0 votes
# 05AB1E (legacy), 9 bytes

```
Ç3Bí0ζøí»

```

Output is newline delimited.

Try it online.

**Explanation:**

Uses the legacy version of 05AB1E because it can zip/transpose on list of strings, whereas the new 05AB1E version requires a matrix of characters. This would be 10 bytes in the new version by replacing `B` with `в` and adding a `J` (join) before the `»`. If any amount of leading 0s is valid, this could be 9 bytes as well in the new version of 05AB1E with `Ç3BZ°+€¦»` or `Ç3BZj»ð0:`.

```
Ç          # Convert the (implicit) input-string to a list of codepoint integers
 3B        # Convert each integer to a base-3 string
   í       # Reverse each string
     ζ     # Zip/transpose; swapping rows/columns,
    0      # using a 0 as trailing filler for unequal length rows
      ø    # Zip/transpose back
       í   # Reverse each string back
        »  # Join the strings with newline delimiter
           # (after which the result is output implicitly)

```

# Answer
> 0 votes
# Java (JDK), 80 bytes

```
s->s.chars().forEach(c->System.out.printf("%05d ",new Long(Long.toString(c,3))))

```

Try it online!

# Answer
> 0 votes
# APL, 21 Chars, 39 Bytes

```
{∊6↑¨,⌿⍕¨(5⍴3)⊤⎕UCS⍵}

```

`(5⍴3)⊤⎕UCS⍵` converts input to base 3 ASCII code in five digits.

`,⌿⍕¨` converts the digits to characters and joins them together.

`6↑¨` pads space in between (also results in a trailing space) and  builds the final output.

Try it online!

# Answer
> 0 votes
# Ruby, 35 bytes

```
->s{s.bytes.map{"%05d"%_1.to_s(3)}}

```

Attempt This Online!

# Answer
> 0 votes
# J-uby, 30 bytes

```
:bytes|:*&(~:to_s&3|:%&"%05d")

```

Attempt This Online!

## Explanation

```
:bytes |        # Get bytes, then
:* & (          # map with...
  ~:to_s & 3 |  #   convert to base 3
  :% & "%05d"   #   format to 5 digits
)

```

---
Tags: code-golf, string, base-conversion
---


# Question
Title: Capture the longest leading whitespace substring from lines
### The Challenge

Given a multiline string, return the longest substring of leading whitespace present in every line, ignoring empty lines or lines composed only of whitespace. If input is empty or whitespace, return nullish or the empty string--up to you.

Update: Per Meta consensus, the input may also be treated as an array of strings. My examples below could be shortened by excluding the `.split()` calls.

---

I wrote a quick script for my iPhone that comments or uncomments JavaScript code (since I can't use `ctrl`+`/`).

I want the `//`  placed the furthest right that it can, given that each `//`  is aligned with the other lines. If a line is only whitespace (or empty), I want to skip adding a comment.

To do this, I must determine the longest leading whitespace substring that exists in every line. So, given the input string

```
  const x = () =>
    y.split()
      .map(s =>
        s.length
      )
      .join()

  console.log(x)

```

the result of the algorithm would be 2 spaces. (Note: Line 7 has 4 leading spaces, but the browser may or may not remove them. It does not appear to remove them in the example solutions below.) If the input was only lines 3-7, the result would be 6 spaces.

A simple JS solution to achieve this would be

```
const solution = text => {
  const lines = text.split('\n').filter(l => !!l.trim())

  let result = ''
  while (lines.every(l => l.startsWith(result + ' '))) {
    result += ' '
  }

  return result
}

// test

const text =
`  const x = () =>
    y.split()
      .map(s =>
        s.length
      )
      .join()

  console.log(x)`

let result = solution(text);
console.log(`|${result}| ${result.length} spaces`)

const lines3Through7 = text.split('\n').slice(2, 7).join('\n')

result = solution(lines3Through7)
console.log(`|${result}| ${result.length} spaces`)

result = solution(
`abc
  def`)
console.log(`|${result}| ${result.length} spaces`)
```

I'm sure you can do better than this.

Another would be

```
const solution = text =>
  ' '.repeat(
    text.split('\n')
      .filter(l => !!l.trim())
      .map(l => l.length - l.trimStart().length)
      .reduce((m, v) => Math.min(m, v))
  )

// test

const text =
`  const x = () =>
    y.split()
      .map(s =>
        s.length
      )
      .join()

  console.log(x)`

let result = solution(text);
console.log(`|${result}| ${result.length} spaces`)

const lines3Through7 = text.split('\n').slice(2, 7).join('\n')

result = solution(lines3Through7)
console.log(`|${result}| ${result.length} spaces`)

result = solution(
`abc
  def`)
console.log(`|${result}| ${result.length} spaces`)
```

---

Assume all whitespaces are space characters (i.e. not `\t`). For input that has no non-whitespace characters, it should return nullish or 0 spaces, up to you.

You can use any language~~, but I'd also like *someone* to present an answer in JavaScript~~ ✅.

Shortest answer wins. Include your answer, a prettified version of your answer for readability, and for esoteric languages, an explanation of how your script works.

# Answer
# Jelly, ~~9~~ 8 bytes

```
=⁶Pi0’⁶ẋ

```

Try it online!

-1 thanks to Jonathan Allan reminding me of meta consensus on being able to take a list of lines.

```
=⁶          For each character on each line, is it a space?
  P         Take the product along each column,
   i0       and find the first 1-index of 0 (or 0 if not found).
     ’      Decrement
      ⁶ẋ    and yield a space repeated that many times (or none if not positive).

```

`n⁶SÄ¬S⁶ẋ` works similarly, but does not ignore all-whitespace lines if there's nothing else.

If we can assume the input contains no codepoints under 32 other than newlines, this *almost* works:

# Jelly, ~~7~~ ~~6~~ 5 bytes

```
Ṁ»\f⁶

```

Try it online!

-1 because I tried replacing `»/` with  just in case that would work, and after further consideration, of course it would work--the lexicographically greatest line is precisely some line with the fewest leading spaces that has something else after them (under the assumption stated above).

-1 thanks to Jonathan Allan reminding me of meta consensus on being able to take a list of lines.

Fails to ignore all-whitespace lines if there's nothing else. A fix in fewer than 3 bytes seems unlikely (though `Ṁ»\ḟȧfɗ⁶` in 3 bytes seems worth mentioning).

```
Ỵ         Split on newlines.
 Ṁ        Take the lexicographically greatest row,
  »\      find the largest character in each of its prefixes,
    f⁶    and remove any that aren't spaces.

```
> 7 votes

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

-1 by using the default ruling that Submissions may use list of strings instead of multi-line strings.

```
n⁶T€FṂ’⁶ẋ

```

A monadic Link accepting a list of lines (lists of characters) that yields a list of characters.

**Try it online!**

### How?

```
n⁶T€FṂ’⁶ẋ - Link: list lists of characters, Lines
 ⁶        - space character
n         - not equals? (vectorises across all the characters in Lines)
   €      - for each:
  T       -   truthy indices (1-indexed)
    F     - flatten
     Ṃ    - minimum (minimum of the empty list is 0)
      ’   - decrement -> number of "common" leading spaces, N
       ⁶  - space character
        ẋ - repeat N times (repeating -1 or 0 times gives an empty list)

```
> 5 votes

# Answer
# 05AB1E (legacy), 9 bytes

```
εDðKk}ßð×

```

Input as a list of character-lists.

Try it online (footer is added to pretty-print the string of spaces) or verify all test cases.

**Explanation:**

```
ε      # Map over each inner character-list of the (implicit) input-list:
 D     #  Duplicate the current character-list
  ðK   #  Remove all spaces from the copy
    k  #  Get the first 0-based index of each of these characters in the list
}ß     # After the map: pop and push the flattened minimum
  ð×   # Convert it to a string with that many spaces
       # (after which the result is output implicitly)

```
> 4 votes

# Answer
# Vyxal, 10 bytes

```
↵ƛðv≠TgI;g

```

Try it Online!

A port of the jelly answer. 8 bytes with the `g` flag.

## Explained

```
↵ƛðv≠TgI;g
↵ƛ          # For each item n in the input split on newlines:
  ðv≠       #   Is each character not a space?
     Tg     #   Smallest index where ^ is truthy. Returns an empty list if all spaces.
       I    #   Push that many spaces or two empty lists if it's all spaces.
        ;g  #   Return the smallest item of that.

```
> 3 votes

# Answer
# JavaScript (ES6), 43 bytes

```
s=>(s.match(/^ *(?=\S)/gm)||[""]).sort()[0]

```

Try it online!

Or **40 bytes** by using optional chaining, as suggested by the OP:

```
s=>s.match(/^ *(?=\S)/gm)?.sort()[0]||''

```

(doesn't work on TIO)
> 3 votes

# Answer
# Retina 0.8.2, 16 bytes

```
G`\S
O^`.+
!`^ +

```

Try it online! Explanation:

```
G`\S

```

Discard lines that only consist of whitespace.

```
O^`.+

```

Sort them in reverse order, so the line with the least space sorts first.

```
!`^ +

```

Output the leading spaces.

If just the count of leading spaces suffices, then for 14 bytes:

```
G`\S
O^`.+
\G

```

Try it online! Explanation: The last stage `\G`  counts consecutive spaces at the start of the buffer.
> 3 votes

# Answer
# Python, 39 bytes

```
lambda l:max(l)[:-len(max(l).lstrip())]
```

Attempt This Online!

Takes input as a list of lines, per default I/O rules.

Uses Unrelated String's observation that the lexicographically greatest line will be the one with the least leading whitespace. This means the input must not contain unprintables other than newline.
> 3 votes

# Answer
# , ~~50~~ ~~62~~ ~~60~~ 57 bytes

*Edit: -2 bytes thanks to pajonk*

```
sub("^( *).*","\\1",sort(sub(" *$","",readLines()),T)[1])

```

Try it online!
> 3 votes

# Answer
# Husk, ~~9~~ ~~11~~ ~~10~~ 9 bytes

*Thanks to Jonathan Allan for bug-spotting (both versions)*

```
←T↑o¬wTfw

```

Try it online!

Takes a list of lines, removes all-space lines (`fw`), transposes (`T`), keeps longest prefix of all spaces (`↑o¬w`), transposes back again (`T`), and output first element ().

---

# Husk, ~~7~~ ~~9~~ 8 bytes

```
↑=' →Ofw

```

Try it online!

Uses Unrelated string's lexicographic sorting approach: Takes a list of lines, removes all-space lines (`fw`), sorts (`O`), keeps last element (), and keeps the longest prefix of spaces (`↑='` ).
> 3 votes

# Answer
# Haskell, ~~47~~ 46 bytes

```
fst.minimum.filter((>[]).snd).map(span(==' '))

```

Try it online!

Nothing special here, it's a very standard approach, just with less whitespace. A more presentable version:

```
main :: IO ()
main = interact (f . lines)

f :: [String] -> String
f = fst                      -- extract it from the tuple
  . minimum                  -- find the shortest leading whitespace (tuples are sorted by first element)
  . filter ((> []) . snd)   -- remove any tuples for which 'everything else' is empty
  . map (span (== ' '))      -- split each line into tuples of (leading whitespace, everything else)

```

Since `minimum` is a partial function, it will raise an exception if given input that consists only of whitespace. From my perusal of the rules, I'm under the impression that this is acceptable; but I'm fairly new here so please correct me if I'm wrong.
> 3 votes

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

```
s=>/( *)\S(.|\s+(\1|$))*$|$/.exec(s)[1]

```

Try it online!

Return `undefined` if no line

# JavaScript (Node.js), 37 bytes

```
s=>/( *)\S(.|\s+(\1|$))*$/.exec(s)[1]

```

Try it online!

Throw if no line
> 2 votes

# Answer
# Pip `-r`, 15 bytes

```
@SS Ks~Y#||_FIg

```

Takes input from stdin; prints a string of spaces (with a trailing newline) to stdout. Outputs nothing if the input contains only whitespace. Attempt This Online!

### Explanation

The `-r` flag reads all of stdin and stores it as a list of lines in `g`. Then:

```
@SS Ks~Y#||_FIg
            FIg  ; Filter g on this function:
         ||      ;   Strip whitespace from
           _     ;   each line
        #        ;   and get the length of what remains
       Y         ; Yank the result (used here just to manipulate precedence)
      ~          ; Get first match of this regex in (each line of) the above:
     s           ;   Preset variable: space
    K            ;   Kleene star (results in this regex: ` *`)
 SS              ; Sort in lexicographic order (in this case, shortest first)
@                ; Get the first element

```
> 2 votes

# Answer
# Excel, ~~48~~ 58 bytes

Revised to return *N* spaces instead of just the value of *N*.

```
=LET(t,TRIM(A:A),REPT(" ",MIN(IF(t="","",FIND(t,A:A)))-1))

```

Trim the leading and trailing white space from each line then find the position what's left in the original line, ignoring those lines that are empty once they're trimmed. Find the minimum of those positions minus 1. Return a space repeated that many times.

Screenshot shows formula returning repeated pipes instead of spaces so you can see the results.
> 2 votes

# Answer
# Charcoal, 23 bytes

```
ＷＳ⊞υι× ∨⌊ΦＥυ⌕Ｅ⪪ι ¬λ⁰⊕ι⁰

```

Try it online! Link is to verbose version of code. Takes input by default as a list of newline-terminated strings, so if you want to provide an empty string as part of the input you'll have to encode it as a JSON list instead. Explanation:

```
ＷＳ⊞υι

```

Input the string.

```
× ∨⌊ΦＥυ⌕Ｅ⪪ι ¬λ⁰⊕ι⁰

```

Split each line on spaces and find the index of the first non-space character, but filter out those lines that only have spaces, and then take the minimum number of spaces, or 0 if all lines only have spaces, and repeat a space that many times.
> 1 votes

# Answer
# Ruby, 29 bytes

```
->a{a.map{_1[/^ +/]}.sort[0]}

```

Attempt This Online!
> 1 votes

# Answer
# Burlesque, 23 bytes

```
t]:nzm{Jt[.-}saq<]qesIE

```

Try it online!

```
t]:nz  # Filter null/wspc lines
m{     # Map
 J     # Dup
 t[    # Trim left
 .-    # String Difference
}      -- Diff pre/post trim
sa     # non-destructive Length
q<]    # If non-zero length find max
qes    # Else Empty Block -> Empty string
IE     # If Else

```
> 0 votes

# Answer
# Perl 5, 38 bytes

```
print[sort map/^ +/g,grep/\S/,<>]->[0]

```

Try it online!
> 0 votes

# Answer
## Scala, 51 bytes

```
"\\n[\\s]*".r.findAllIn("\n"+y).map(_.length).min-1

```

Try it online!

**Explanation:**

```
"\\n[\\s]*".r                   // regex to find newlines and all whitespaces after
           .findAllIn(          // iterator of all matches in the given string
                      "\n"+y)   // add a newline to the front to count first line
           .map(_.length).min   // find the shortest match
           -1                   // subtract one since lengths include the newlines

```
> 0 votes

# Answer
# J-uby, 28 bytes

```
:*&(~:[]&/^ */)|:sort|:first

```

Attempt This Online!

## Explanation

```
:* & (           # Map lines with...
   ~:[] & /^ */  #   Get part that matches /^ */
) |              # then
:sort | :first   # sort, then get the first

```
> 0 votes

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


title: Construct a multiparticle quantum state

text:
# Question
Title: Construct a multiparticle quantum state
Sandboxed and made less complicated and hopefully more fun.

# Summary of the challenge

Given a number of particles, either identical bosons or identical fermions, output the total wave function of the state assuming they are all independent.

# Physics background

Don't worry, you don't need to know quantum mechanics to solve this challenge. I will explain what you need now.

**What is a wave function?**

In (non-relativistic) quantum mechanics every particle can be described with a function of the position called the *wave function*. If you have a system with more than one particle you can describe it using a wave function that will depend on the position of all the particles of the system. In this challenge we will only consider independent (i.e. non-interacting) particles. In this case the total wave function can be written as a combination of the wave function of the single particles. The way you can do this depends of the type of particles you have and the statistics they obey.

**Distinguishable particles**

Let's start from the case of *distinguishable particles* even if you will not need them for the challenge. Distinguishable particles are what you have in classical physics. Every object has is own identity. If I throw two coins I have a 25% chance of getting `TT`, 25% for `HH` and a 50% for `TH` because `TH` and `HT` are two different events.

For a system of distinguishable particles the total wave function is written as the product of the single wave functions. For a system of n particles, if we call `di` the i-th particle wave function and `xi` the i-th particle position we have a total wave function:

```
1 particle:    d1(x1)
2 particles:   d1(x1)d2(x2)
3 particles:   d1(x1)d2(x2)d3(x3)
  ...

```

**Indistinguishable Bosons**

Now onto the weird stuff. When you get to the quantum level you will discover that particles with same properties are actually identical and thus obey a different statistics than classical particles. Back to the coin toss example we find that if we assume the coins to be indistinguishable, all the three events are equally likely, that is we have a 33% for `TT`, 33% for `HH` and 33% for `HT` because now `TH` and `HT` are the same event.

The total wave function for several bosons is **not** given by simply the product of the single particle wave functions, but as a sum of all the possible combinations of wave function and positions. You will understand better with some examples, using a similar notation than before:

```
1 boson:    b1(x1)
2 bosons:   b1(x1)b2(x2) + b2(x1)b1(x2)
3 bosons:   b1(x1)b2(x2)b3(x3) + b2(x1)b1(x2)b3(x3) + b3(x1)b2(x2)b1(x3) + b1(x1)b3(x2)b2(x3) + b2(x1)b3(x2)b1(x3) + b3(x1)b1(x2)b2(x3)
  ...

```

What you have at the end is a total wave function that is *symmetric* (i.e. stays the same) for any exchange like `xi <-> xj` or `bi <-> bj`.

**Indistinguishable Fermions**

It gets even weirder! Fermions are not only indistinguishable but they also don't like being in the same state. This means that if you toss two fermion coins you are 100% guaranteed of getting `TH` since `TT` and `HH` are now prohibited.

The total fermion wave function is constructed the same way of the boson one, but instead of having all `+` signs, you have a `+` or a `-` depending on the *sign* of the permutation. For an odd number of swaps to get from the starting order to that permutation you have a `-` sign, for an even number you have a `+` sign.

```
1 fermion:    f1(x1)
2 fermions:   f1(x1)f2(x2) - f2(x1)f1(x2)
3 fermions:   f1(x1)f2(x2)f3(x3) - f2(x1)f1(x2)f3(x3) - f3(x1)f2(x2)f1(x3) - f1(x1)f3(x2)f2(x3) + f2(x1)f3(x2)f1(x3) + f3(x1)f1(x2)f2(x3)
  ...

```

The total wave function is now *antisymmetric* (i.e. changes sign) for any exchange like `xi <-> xj` or `fi <-> fj`. If you have two equal wave functions the total wave function is zero.

# Algorithmic way of building the wave function

Suppose you have `3` particles of type `p` (`p=b`for bosons and `p=f` for fermions).

* Start from `p1(x1)p2(x2)p3(x3)`
* Build each possible swap of two wave functions (or equivalently coordinates)
    + `p1(x1)p2(x2)p3(x3)`
    + `p1(x1)p3(x2)p2(x3)`
    + `p2(x1)p1(x2)p3(x3)`
    + `p2(x1)p3(x2)p1(x3)`
    + `p3(x1)p1(x2)p2(x3)`
    + `p3(x1)p2(x2)p1(x3)`
* Determine the sign of the permutation (only for fermions)
* Join everything with the correct sign: `+` for bosons or the sign of the permutation for fermions

# Input

You will get two inputs (or a list of two items). One of them is a number from 0 to 9 inclusive (that will represent the number of particles, the other defines the type of particles in the system. You can choose the order of the input and the format of the two inputs. Some examples of inputs might be:

```
[n, type]    |    Meaning
---------------------------------------------------------------
[3, "boson"] |    3 bosons
[6, 'f']     |    6 fermions
[4, True]    |    4 fermions (True = fermion, False = boson)

```

Remember to write in the answer how you are formatting your input.

# Output

You have to output the total wave function of the system that obeys the rules explained before. See the examples for an example of formatting. Bosons are represented as `bi`, fermions as `fi` and positions as `xi` where the index `i` goes from `1` to `n` (the number of particles).

Each output will have `n!` terms that contains the product of `n` terms summed together. The order inside each product or in the total sum does not matter, the important thing is the dependence of each wave function on the positions and the sign of each term.

The output must be a mathematically valid expression, so if you want to add explicit multiplication signs it is fine. You have the freedom of writing the variables and the function as you want, but there needs to be a clear distinction between fermions and bosons.

The output must be written as an explicit sum of explicit products, so no implicit summations or products, no summation signs, no product signs and no determinants of matrices.

The spaces in the example are just for clarity and you can decide not to output them.

# Scoring

This is . Shortest answer in bytes wins. Standard loopholes apply.

# Examples

```
Input  ->   Output
[0, b] ->   0 (or empty string)
[1, b] ->   b1(x1)
[2, b] ->   b1(x1)b2(x2) + b2(x1)b1(x2)
[3, b] ->   b1(x1)b2(x2)b3(x3) + b2(x1)b1(x2)b3(x3) + b3(x1)b2(x2)b1(x3) + b1(x1)b3(x2)b2(x3) + b2(x1)b3(x2)b1(x3) + b3(x1)b1(x2)b2(x3)
[1, f] ->   f1(x1)
[2, f] ->   f1(x1)f2(x2) - f2(x1)f1(x2)
[3, f] ->   f1(x1)f2(x2)f3(x3) - f2(x1)f1(x2)f3(x3) - f3(x1)f2(x2)f1(x3) - f1(x1)f3(x2)f2(x3) + f2(x1)f3(x2)f1(x3) + f3(x1)f1(x2)f2(x3)

```

# Answer
> 3 votes
# Jelly,  ~~47~~  46 bytes

*He he, what a `ṭ€€ż€`...*

```
Ṭ€z0ÆḊ×”fe⁴¤«0ị⁾-+
ṭ€”xj@€⁾()
Œ!©ṭ€€ż€⁸Ç¤®Ñ€¤ż

```

A full program which prints such that the summands are in lexicographical order once the multiplications of particle functions are all ordered by the position arguments.
i.e.:
`f1(x1)f2(x2)...fn-1(xn-1)fn(xn)` (or `b...`) will always be first, followed by
`f1(x1)f2(x2)...fn(xn-1)fn-1(xn)`, and so on up to
`fn(x1)fn-1(x2)...f2(xn-1)f1(xn)`.

**Try it online!**

### How?

```
Ṭ€z0ÆḊ×”fe⁴¤«0ị⁾-+ - Link 1: get the sign character: list, permutation of [1,N], P
Ṭ€                 - untruth €ach - that is [0,0,...,0,1] of length v for each v in P
  z0               - transpose with filler 0 (yields transpose of the permutation matrix)
    ÆḊ             - determinant (yields the parity of the permutation)
           ¤       - nilad followed by link(s) as a nilad:
       ”f          -   literal character 'f'
          ⁴        -   4th command line argument = 2nd program input = particle type, T
         e         -   exists in? (1 for "f", 0 for "b")
      ×            - multiply (force all results from +1 or -1 to 0 for T="b")
            «0     - minimum of that and 0 (force the +1s to 0s)
               ⁾-+ - literal list of characters = ['-', '+']
              ị    - index into (the -1s yield '-'  while the 0s yield '+')

ṭ€”xj@€⁾() - Link 2: construct parenthesised positions: number of particles, N
  ”x       - literal character = 'x'
ṭ€         - tack for €ach -> [['x', 1], ['x', 2], ..., ['x', N]]
       ⁾() - literal list of characters = ['(', ')']
    j@€    - join with swapped @rguments for €ach -> [['(', 'x', 1, ')'],...]

Œ!©ṭ€€ż€⁸Ç¤®Ñ€¤ż - Main link: number of particles, N; type of particle P
Œ!               - all permutations of N -> [[1,2,...,N-1,N],[1,2,...,N,N-1],...]
  ©              - copy to the register and yield
   ṭ€€           - tack T for €ach for €ach (place the type in front of every number)
          ¤      - nilad followed by link(s) as a nilad:
        ⁸        -   chain's left argument, N
         Ç       -   call last link (2) as a monad (get the "(xn)"s)
      ż€         - zip with for €ach (make all the summands)
              ¤  - nilad followed by link(s) as a nilad:
           ®     -   recall value from register (the permutations of N)
            Ñ€   -   call the next link (1) as a monad for €ach (get the signs)
               ż - zip the signs and the summands.
                 - implicit print

```

# Answer
> 1 votes
# Python3, 320 bytes:

```
R=range
def f(a,b):
 q,s=[([*R(a)],0)],{str([*R(a)]):0}
 while q:
  c,k=q.pop(0)
  for x in R(a):
   for y in R(x,a):
    C=eval(str(c));O=C[y];C[y]=C[x];C[x]=O
    if str(C)not in s:s[str(C)]=k+1;q+=[(C,k+1)]
 return''.join(['-','+'][b=='b'or s[j]%2==0]+''.join(f'{b}{eval(j)[k]+1}(x{k+1})'for k in R(a))for j in s)[1:]

```

Try it online!

---
Tags: code-golf, physics
---


title: Incomparable partitions

text:
# Question
Title: Incomparable partitions
A partition of a list \\$A\\$ is a way of splitting \\$A\\$ up into smaller parts, concretely it is list of lists that when concatenated gives back \\$A\\$.

For example `[[1],[2,3],[5,6]]` is a partition of `[1,2,3,5,6]`. The trivial partition is a partition that "splits" the list into only one piece, so `[[1,2,3,5,6]]` is also a partition of `[1,2,3,5,6]`.

One partition \\$X\\$ is finer than another partition \\$Y\\$ iff \\$X\\$ can be made by partitioning the pieces of \\$Y\\$ in place. So for example `[[1],[2],[3],[5,6]]` is finer than `[[1],[2,3],[5,6]]`. But `[[1,2],[3],[5],[6]]` is *not* finer than `[[1],[2,3],[5,6]]`, even though it splits it into more parts. Note by this definition every partition is finer than itself. For two partitions it can easily be the case that neither of them is finer than the other.

Your task is to take as input a partition \\$A\\$ of a list of positive integers and output a distinct partition \\$B\\$ of the same list, such that \\$A\\$ is not finer than \\$B\\$ and \\$B\\$ is not finer than \\$A\\$. The input will never be the trivial partition (no cuts made) or the cotrivial partition (all cuts made). That is you don't need to worry about cases where there is no valid output.

Input can be taken as a list of list, array of arrays, vector of vectors or any reasonable equivalent. Output should be given in the same format as input.

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

# Answer
# Retina 0.8.2, 7 bytes

```
T`,;`;,

```

Try it online! Takes input and output as a semicolon-delimited list of comma-delimited lists. Explanation: Simply partitions the original list only in the places that the input list didn't partition it. In particular, anywhere the input list partitions the original list, the output list does not, and therefore is not finer than the input list, but the same applies in reverse so that the input list is not finer than the output list.

13 bytes with a more standard I/O format:

```
,
},{
}},{{
,

```

Try it online! Takes output as a list of lists, each element separated by `,` and each list wrapped with `{` and `}`. Explanation: Switches between `,` and `},{` (which represents `;` above) by first wrapping each `,` to `},{` and then double-unwrapping `}},{{` to `,`.
> 8 votes

# Answer
# Haskell, 47 bytes

```
f((h:t):r)|t>[]=[h]:[id=<<t:r]|a:b<-f r=(h:a):b

```

Try it online!

Recursively pattern matching first element *`(h:t)`:r*
*t\>\[\]* : if its tail is a list, we isolate head *\[h\]* and join everything else.
Else we do the same with the rest and join first el. of result with *h* which is a singleton.
> 4 votes

# Answer
# Python, 98 bytes

```
lambda a:[(l:=[*chain(*a)])[:(i:=-~[len(x)>1for x in a].index(1))]]+[l[i:]]
from itertools import*

```

Attempt This Online!

Takes input as a list of lists, returns as a list of list. Though the code is a bit retch-inducing, the way it works is

1. Join all of the lists together.
2. Split the list at an index which is associated with a list of at least 2 elements in \\$A\\$.
> 3 votes

# Answer
# Python 2, 58 bytes (@AZTECCO)

```
lambda s:eval(`s`.replace('], [',',').replace(', ','],['))

```

Attempt This Online!

Port of @Neil's answer. This takes and returns a list of lists.

# Python, 50 bytes

```
lambda s:s.replace(',','],[').replace(']],[[',',')

```

Attempt This Online!

Port of @Neil's answer. Takes and returns strings (brackets, commas, no spaces).

### Python, 73 bytes

```
def f(s):
 *o,i=[],[],0
 for c,*r in s:o[i]+=c,;o[1]+=r;i|=r>[]
 return o

```

Attempt This Online!

Port (to no-itertools) of @97.100.97.109's answer.
> 2 votes

# Answer
# Japt `-Q`, 6 bytes

```
m¸·¸m·

```

Try it

Basically the same logic as Neil's Retina answer.

```
m¸·¸m·
m¸     # Join each part to a string with " " as a delimiter
  ·    # Join the resulting strings with "\n" as a delimiter
   ¸   # Split that string at " " characters
    m· # Split the substrings at "\n" characters

```

Input and output are "Array of arrays of strings". The same code works for input as numbers/output as strings. Input and output as numbers takes an extra 2 bytes.
> 2 votes

# Answer
# Jelly, 6 bytes

```
ẈÄṬ¬kẎ

```

Try it online!

Another port of Neil's logic--completely invert the partition--except without string operations. Takes and returns a list of lists.

```
  Ṭ       Generate an array with 1s at the indices in
 Ä        the cumulative sum of
Ẉ         the lengths of the original partitions.
    k     Partition the array
     Ẏ    concatenated
   ¬      after positions of 0s.

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), 46 bytes

```
f@{x___,{a_,b__},y___}:=Flatten/@{{x,a},{b,y}}

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 5 bytes

```
»#¶δ¡

```

Inspired by *@Neil*'s Retina answer: outputs the inverted partition of the given input.

I/O as a list of lists of strings.

Try it online or verify some more test cases.

**Explanation:**

```
»      # Join each inner list by spaces, and then each string by newlines
 #     # Split this multiline string by spaces
   δ   # Map over each substring:
  ¶ ¡  #  Split it by newlines
       # (after which the result is output implicitly)

```
> 1 votes

# Answer
# Python, 72 bytes

```
def f(a):
 a+=[z:=[]]
 for x in a:z+=[x.pop()]
 while[]in a:a.remove([])

```

Attempt This Online!

Port of AZTECCO's solution
> 0 votes

---
Tags: code-golf, open-ended-function, set-partitions
---


title: Snakes all around

text:
# Question
Title: Snakes all around
## Challenge

The challenge is simple: **print a snake**.
You will get the length of the snake as input.
A snake of length 2 looks like this:

```
==(:)-

```

A snake of length 7 looks like this:

```
=======(:)-

```

In other words, *the length of a snake is how many equal signs are before the head*.

## Usage

Let's say I made a C++ implementation and compiled it to `./getsnake`.
I could run it like so:

```
$ ./getsnake 10
==========(:)-

```

## Clarifications

* Standard loopholes are disallowed.
* You can get input and output in any acceptable way.
* You can assume all inputs given are positive integers.
* You may write a function instead of a regular program.

# Answer
# Hexagony, 33 bytes

Not gonna win, but still cool. Might be able to get golfed more.

Try it online!

Golfed:

```
61}?.$)@$j;(3<./;.}l/.400;5\j;.'\

```

Formatted:

```
    6 1 } ?
   . $ ) @ $
  j ; ( 3 < .
 / ; . } l / .
  4 0 0 ; 5 \
   j ; . ' \
    . . . .

```

Colored (Made using Timwi's Hexagony Colorer)

Explanation:

Loop, print out "=" until the counter reaches 0.

```
    6 1 } ?
   . $ . . $
  . . ( . . .
 / . . } . . .
  . . . ; . .
   . . . ' .
    . . . .

```

Print "("

```
    . . . .
   . . . . .
  . . . . . .
 / ; . . . . .
  4 . . . . .
   j . . . .
    . . . .

```

Print ":"

```
    . . . .
   . . . . .
  . ; ( 3 < .
 . . . } l / .
  . . . . . .
   . . . . .
    . . . .

```

Print ")"

```
    . . . .
   . . . . .
  j . . . . .
 . . . . . . .
  . . . ; 5 \
   . . . . \
    . . . .

```

The above values were generated using a simple python script. However, I kind of ran out of room for the "-". So, I had to resort to more advanced tricks.

When the program prints out ")", the value of the cell isn't 41, it's 1065. Hexagony just mods the value when printing. As it turns out, (1065\*1000+4)%256=44, just one away from 45, the ascii value for "-". Then, I just increment, print, and insert a @ somewhere after printing.

```
    . . . .
   . $ ) @ $
  j . . 3 . .
 / . . } . . .
  4 0 0 . 5 \
   . ; . . \
    . . . .

```
> 19 votes

# Answer
# Cinnamon Gum, 7 bytes

```
0000000: 7043 dc95 6d4f ce                        pC..mO.

```

Try it online.

Would have been 6 bytes with the old `p` syntax :/

# Explanation

Decompresses to `p~=~(:)-`, the `p` stage then simply reads input and repeats the `=` n times.
> 12 votes

# Answer
## Brian & Chuck, 31 bytes

```
,{-?>}-):(=?
#}<<.{?_<.<.<.<.<.

```

Input in the form of a byte value, so e.g. input `!` gives a snake of length 33.

Try it online!

It's been a while...

### Explanation

A quick Brian & Chuck primer:

* The first line of the program is Brian, the second is Chuck.
* Brian and Chuck are two Brainfuck-like instances. The main catch is that Chuck's program is Brian's tape and vice versa. The tape heads/instruction pointers start on the first cell of each tape and execution starts on Brian.
* As for the commands, there are a few differences. Only Brian can use `,` (input) and only Chuck can use `.` (output). In addition to `<` and `>` there are `{` and `}` which move the tape head up to the next zero cell (or in the case of `{` to the left end of the tape if there is no zero cell on the way). Instead of `[...]`, the only control flow is `?` which switches control to the other instance if the current cell is non-zero. The first executed instruction on the other cell is the one after the condition. And finally, `_` is just an alias for null-bytes, for convenience.

Now the code. Brian starts with this:

```
,{-?

```

This reads the input into Chuck's first cell, then moves the tape head to the left with `{` (does nothing right now) and decrements the input with `-` before switching control for Chuck if the value is still non-zero. This begins the main loop. Chuck then runs this bit:

```
}<<.{?

```

This moves the tape head on Brian to the very end, moves two cells left onto the `=` and prints it before the tape head all the way to the left and switching control back to Brian. This is how loops generally work in B&C.

Once the input has been reduced to zero, the `?` on Brian's tape will do nothing. Then Brian executes this part:

```
>}-):(=?

```

The `):(=` are no-ops, so the actual code is just `>}-?`. We move off the zero cell with `>`, move up to `_` with `}`, decrement it to make it non-zero and switch to Chuck with `?`. Then the last bit on Chuck is run:

```
<.<.<.<.<.

```

This simply prints the five characters in front of Chuck, i.e. `=(:)-`. Note that we need to print another `=` since the main loop is only executed `N-1` times for input `N`.
> 12 votes

# Answer
# , 8 bytes

```
Àé=A(:)-

```

Try it online!

V uses the "Latin1" encoding.

Explanation:

```
À        "Arg1 times:
 é=      "Insert an '='
   A(:)- "Append the head

```
> 10 votes

# Answer
# Retina, 10 bytes

```
.+
$*=(:)-

```

Try it online!

This is a simple regex substitution.

It matches `.+` which matches the whole input, and then substitutes it with `$*=(;)-`.

The `$*` is a feature unique in Retina: it is the character-repetition special operator.

For example, `5$*x` would become `xxxxx`.

In the case that the previous argument is absent, the whole match is used as the default argument.
> 6 votes

# Answer
# Python, 21 bytes

```
lambda n:"="*n+"(:)-"

```

Ideone it!
> 5 votes

# Answer
# Java 8, 52 bytes

```
n->new String(new char[n]).replace("\0","=")+"(:)-";

```

Test suite. (Compile \> Execute)

Credits.

### teh traditional way, ~~61~~ ~~54~~ 53 bytes

**7 bytes thanks to Kevin Cruijssen.**

**1 byte thanks to Dom Hastings.**

```
n->{String s="";for(;n-->0;)s+="=";return s+"(:)-";};

```
> 5 votes

# Answer
# Haskell, 25 bytes

```
f n=('='<$[1..n])++"(:)-"

```

`'='<$[1..n]` is equivalent to `replicate n '='`.
> 5 votes

# Answer
# Jelly, 9 bytes

```
”=x;“(:)-

```

Try it online!

```
”=x;“(:)-
”=          '='
  x         repeat (argument) that many times
   ;        append
    “(:)-   "(:)-"

```
> 4 votes

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

```
'=×"ÿ(:)-

```

**Explanation**

```
'=         # push equal-sign
  ×        # repeat input nr of times
   "ÿ(:)-  # interpolate snake body with head as a string
           # implicitly display

```

Try it online

1 byte saved thanks to Adnan.
> 4 votes

# Answer
# C, 38

```
f(n){for(;n--;printf(n?"=":"=(:)-"));}

```

Try it on ideone.
> 4 votes

# Answer
# Javascript, 23 bytes

```
n=>"=".repeat(n)+"(:)-"

```
> 4 votes

# Answer
## C#, 28 bytes

```
n=>new string('=',n)+"(:)-";

```
> 4 votes

# Answer
# Python, 24 bytes.

```
print"="*input()+"(:)-"

```

`input()` gets input from user

`*`, when used on strings and an integer, creates a new string, which is made of joined copies of the original. For example: `"hello "*3` outputs `hello hello hello`.

By multiplying `=` and `input()`, you get a string of `=` the length that the user specifies.

Using `+` joins two strings, in this case, our body `"=…="` with our head, `"(:)-"` to make the snake.

`print` outputs the result.
> 4 votes

# Answer
# GolfScript, ~~11~~ 10 bytes

```
~"="*"(:)-"

```

Multiplies "=" by input, and adds head.

*-1 thanks to Leaky Nun*
> 3 votes

# Answer
# Mathematica, ~~21~~ 20 bytes

```
"="~Table~#<>"(:)-"&

```

Anonymous function. Takes a number *n* as input, and returns a snake of length *n* as output. `"="~Table~#` generates a list `{"=", "=", ..., "="}` of length *n*, and `<>"(:)-"` concatenates the list's elements and appends `"(:)-"` to the resulting string.
> 3 votes

# Answer
## Batch, 68 bytes

```
@set h=(:)-
@for /l %%i in (1,1,%1)do @call set h==%%h%%
@echo %h%

```
> 3 votes

# Answer
# R, ~~32~~ 27 bytes

This solution is pretty straightforward, `rep` function repeats the first element (`"="`) `scan()` times, which is in fact the user's input.

~~```
a=scan();cat(rep("=",a),"(:)-")

```~~

*EDIT*:

```
cat(rep("=",scan()),"(:)-")

```

Slighly shorter answer, using `scan()` directly.

Alternatively,

```
cat(rep("=",scan()),"(:)-",sep="")

```

for a non-chopped snake (**34 bytes**)
> 3 votes

# Answer
# C, ~~46~~ ~~45~~ ~~43~~ bytes

*saved 2 bytes thanks to owacoder!* *saved 3 bytes thanks to rici!*

```
f(n){while(4-printf("=\0(:)-"+2*!n--));}

```

Try it on Ideone!
> 2 votes

# Answer
# CJam, ~~13~~ 11 bytes

```
qi'=*"(:)-"

```

Test it here.

*-2 bytes thanks to quartata*
> 2 votes

# Answer
# JAISBaL, 9 bytes

```
t=*Qb(:)-

```

Verbose:

```
# \# enable verbose parsing #\
push1 =        \# push = onto the stack #\
mul            \# multiply the top two values of the stack #\
popout         \# pop the top value of a stack and print it #\
print4 (:)-    \# print (:)- #\

```

Tested with JAISBaL-0.0.7 (The compiled .jar was just pushed, but the source has been up on git for a while)
> 2 votes

# Answer
# Perl 6,  ~~16 15~~  12 bytes

```
~~{"{'='x$_}(:)-"}
{'='x$_~'(:)-'}~~
'='x*~'(:)-'
```

### Explanation:

```
'=' x * # ｢=｣ string repeated by the only parameter ｢*｣
~        # concatenated with
'(:)-'   # the head

```

### Usage:

```
# store it in the lexical namespace
my &snake = '='x*~'(:)-';

put snake 10;

# put ^5 .map: &snake;
put ^5 .map: '='x*~'(:)-';

```

```
==========(:)-
(:)- =(:)- ==(:)- ===(:)- ====(:)- =====(:)-

```
> 2 votes

# Answer
## PowerShell v2+, 19 bytes

```
'='*$args[0]+'(:)-'

```

Full program. Takes input `$args[0]`, uses string multiplication to construct the body, then string concatenation to tack on the head.

```
PS C:\Tools\Scripts\golfing> .\snakes-all-around.ps1 7
=======(:)-

PS C:\Tools\Scripts\golfing> .\snakes-all-around.ps1 77
=============================================================================(:)-

```
> 2 votes

# Answer
# Cheddar, 15 bytes (noncompeting)

```
n->'='*n+'(:)-'

```

A straightforward answer.
> 2 votes

# Answer
# Sesos, 11 bytes

Hexdump:

```
0000000: aaaa5e a0f7b4 ed4cee 5d3b                         ..^....L.];

```

Try it online!

Assembler:

```
set numin
add 61
fwd 1
get
jmp,sub 1,rwd 1,put,fwd 1,jnz
add 40,put
rwd 1,sub 3,put
fwd 1,add 1,put
add 4,put

```
> 1 votes

# Answer
## K, 17 Bytes

```
{,[x#"=";"(:)-"]}

```

Example;

```
f:{,[x#"=";"(:)-"]}
-1(f'!10);          /print out the result of calling f where x is 0 1 2 3 4 5....
(:)-
=(:)-
==(:)-
===(:)-
====(:)-
=====(:)-
======(:)-
=======(:)-
========(:)-
=========(:)-

```

Explanation;

```
{}                 /function x is implicit and is an int
x#"="              /take (#) x of "=" --> so 3#"=" gives "==="
,[x#"=";"(:)-"]    /comma is a join that takes 2 args --> ,[x;y] gives the concatination of x and y --> "a","abc" is the same as ,["a";"abc"] and gives "aabc"

```
> 1 votes

# Answer
# Perl, 16 + 1 (`-p` flag) = 17 bytes

```
$_="="x$_."(:)-"

```

Needs `-p` flag, so run with :

```
perl -pe '$_="="x$_."(:)-"'

```
> 1 votes

# Answer
## Minkolang 0.15, 12 bytes

```
"=(:)-"nD$O.

```

Try it here!

### Explanation

```
"=(:)-"         Push this to the stack in reverse order - ["-",")",":","(","="]
       n        Take number from input
        D       Pop k and duplicate top of stack (the "=") k times
         $O.    Output whole stack as characters and stop.

```
> 1 votes

# Answer
# Befunge-98, 24 bytes

Takes numerical input from the user, then prints the snake.

```
'=&:00pk:00gk,"-):("4k,@

```
> 1 votes

# Answer
# Matlab / Octave, 22 bytes

```
@(n)[~(1:n)+61 '(:)-']

```

This is an anonymous function.

**Try it on Ideone**.

### Explanation

Assume `n= 5`.

`1:n` produces the row vector `[1 2 3 4 5]`.

`~(1:n)` negates each entry, so it gives `[0 0 0 0 0]`.

`...+61` adds `61` to each entry, so it gives `[61 61 61 61 61]`. `61` is the ASCII value of character `=`.

`[... '(:)-']` concatenates that with the string `'(:)-'`. This automatically converts `[61 61 61 61 61]` into the string `'====='` before the concatenation.
> 1 votes

# Answer
# Dyalog APL, 13 bytes

```
'(:)-',⍨⍴∘'='

```

`'(:)-',⍨` the snake head appended to
`⍴∘'='` *n* repetitions of a body segment

TryAPL online!

A proper function. The equivalent program is `'(:)-',⍨⎕⍴'='`.
> 1 votes

# Answer
# Brainfuck, 53 bytes

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

```

Explanation:

```
++++[->+++++<]    We build a 20 as 5*4
>[->+++>++<<]     We build a 60 and a 40 in two neighboring cells out of the 20, by multiplying the 20 with 3 and with 2
,>+<[->.<]        Read input, and print 61 ('=') as many times as the input idicates
>>.<---.>+.++++.  Print out the rest, "(:)-", noting how close each character is to either 60 or 40.

```
> 1 votes

# Answer
# x86 COM, 29 bytes

```
8A 0E 82 00 80 E9 30 B4
02 B2 3D CD 21 49 75 FB
BA 18 01 B4 09 CD 21 C3
28 3A 29 2D 24

```

aka

```
16DA:0100 8A0E8200      MOV     CL,[0082]
16DA:0104 80E930        SUB     CL,30
16DA:0107 B402          MOV     AH,02
16DA:0109 B23D          MOV     DL,3D
16DA:010B CD21          INT     21
16DA:010D 49            DEC     CX
16DA:010E 75FB          JNZ     010B
16DA:0110 BA1801        MOV     DX,0118
16DA:0113 B409          MOV     AH,09
16DA:0115 CD21          INT     21
16DA:0117 C3            RET
16DA:0118 283A          SUB     [BP+SI],BH // Snake Head
16DA:011A 292D          SUB     [DI],BP    // Snake Head
16DA:011C 2400          AND     AL,00      // Snake Head

```

Name it "snake.com"

Call it from cmd (tested with Win XP), parameters 1 to 9 supported:

```
snake 5

```

results in

```
=====(:)-

```
> 1 votes

# Answer
## C#, 42 bytes

```
string w(int n)=>new string('=',n)+"(:)-";

```

Try it here!
> 1 votes

# Answer
## Lua, 28 Bytes

Takes input in the form of a command-line argument and outputs via its return value. Even if it uses a return statement, it is still a full program :).

```
return("="):rep(...).."(:)-"

```
> 1 votes

# Answer
# LiveScript, 15 bytes

```
->'='*it+'(:)-'

```
> 1 votes

# Answer
# BASIC, 30 bytes

Let's keep it simple in BASIC. QB64 and TRS-80 Extended Color BASIC both tie, since TRS-80 needs a line number but doesn't need the space after `INPUT`, and it won't let you use `INPUT` in immediate mode. One liners are rare on a 32x16 screen.

## TRS-80: *(should also work on Microsoft GW-BASIC/BASICA)*

```
0INPUTL:?STRING$(L,"=");"(:)-"

```

## QB64:

```
INPUT L:?STRING$(L,"=");"(:)-"

```
> 1 votes

# Answer
# Java 1.7, 46 bytes

A recursive (and shorter) alternative to the iterative and 'replace' versions.

```
String f(int n){return n>0?"="+f(--n):"(:)-";}

```

Run it here.

This function first builds the *n* tail elements recursively, then appends the head.
> 1 votes

# Answer
## Brainfuck, ~~47~~ ~~46~~ 44 bytes

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

```

Try it online! Takes input as a single byte value (e.g. space is 32). The program requires an interpreter with 8-bit cells and a tape not bounded on the left.

`+[+<-[<]>->>++]` (found by a bit of brute forcing) initialises the tape to

```
[253, 0, 0, 232, 0, 0, 40, 0, 59, 86, 0]
                                      ^

```

We then increment the 59 to 61 with `<<++` and read the input char with `<,`. `[->.<]` then outputs the required number of `=`, and `<.>>---.<<+.++++.` outputs the `(:)-` portion, making use of the aforementioned 61 as well as the 40 two cells away.
> 1 votes

# Answer
# Fish (\>\<\>), 33 bytes:

An upside down F cause \>\<\>. Takes integer as command line argument by running `./fish.py snake.fish -v [number]`.

```
\
"
-
)
:
(!;!?lo<
=
"
>{1-:?!^}:

```

Try it here! The best explanation is to watch it with animation on the website.
> 1 votes

# Answer
# Befunge 93, 25 bytes

Try it Online!

```
1+:&`#v_"=",
"(:)-"<@,,,,

```

Not compatible with '98, because the `&` character acts like `r` when there is no input, instead of repeating the last token
> 1 votes

# Answer
# C++14, 59 bytes

As unnamed lambda:

```
#import<string>
[](int n){return std::string(n,61)+"(:)-";}

```

Usage:

```
#include<iostream>

#import<string>
auto f=
  [](int n){return std::string(n,61)+"(:)-";}
;

int main(){
  std::cout << f(2) << std::endl;
  std::cout << f(5) << std::endl;
  std::cout << f(10) << std::endl;
}

```
> 1 votes

# Answer
# Turing machine code, 242 bytes

```
0 * * r 0
0 _ _ l A
A 0 9 l A
A 1 0 r 1
A 2 1 r 1
A 3 2 r 1
A 4 3 r 1
A 5 4 r 1
A 6 5 r 1
A 7 6 r 1
A 8 7 r 1
A 9 8 r 1
A _ _ r 3
1 _ = l 2
1 * * r 1
2 = = l 2
2 * * * A
3 = = r 4
3 * _ r 3
4 = = r 4
4 _ ( r 6
6 _ : r 7
7 _ ) r 8
8 _ - * halt

```

Try it online.
> 1 votes

# Answer
# Common Lisp, 29 bytes

```
(format t"~v{=~}(:)-"(read)1)

```
> 1 votes

# Answer
# Befunge-98 (FBBI), ~~22~~ 18 bytes

Saved 4 bytes by putting the `"-):("` at the beginning. This let me get rid of the separate printing of the head, and also the `'` for pushing the `=`.

```
"-):(="&k:$$>:#,_@

```

Try it online!

### Explanation

```
"-):(="                   Pushes '-):(=' to the stack - the head reversed
       &k:                Duplicates the = N+1 times (now there are N+2 '='s on the stack)
          $$              Discards 2 so that there are N '='s
            >:#,_         Prints all the top non-zero chars on the stack (the whole snake)
                 @        Exits

```
> 1 votes

# Answer
**VBA Excel, 23 bytes**

using Immediate window and cell \[A1\] as input

`?string([A1],"=")"(:)-"`
> 1 votes

# Answer
# Vyxal, ~~11~~ 9 bytes

```
\=*\:øb‹+

```

Try it Online!
> 1 votes

# Answer
# Pyth, 10 bytes

```
+*\=Q"(:)-

```

Test suite.

```
+*\=Q"(:)-
    Q        get input
 *\=         repeat "=" that many times
+    "(:)-   append "(:)-"

```
> 0 votes

# Answer
# C++, 106 103 bytes

```
#include <iostream>
void s(int n){for(int i=0;i<n;i++){std::cout<<"=";}std::cout<<"(:)-"<<std::endl;}

```

## Usage

```
#include <string>
int main(int argc, char *argv[]) {
    int length = std::stoi(argv[1]);
    s(length);
    return 0;
}

```

## Ungolfed

```
#include <iostream> // for printing
void outputSnake(int length) {
    for (int i = 0; i < length; i++) { // iterates over length of snake
        std::cout << "="; // prints an equals sign
    }
    std::cout << "(:)-" << std::endl; // prints rest of snake
}

```

---

Thanks @LeakyNun for shaving off 3 bytes.
> 0 votes

# Answer
# \>\<\>, ~~26~~ 23 bytes

```
:?!v"="o1-
oo;>"-):("oo

```

*-3 bytes thanks to Leaky Nun*

Test it here. (you have to input the code manually)
> 0 votes

# Answer
# Java, 133 bytes

```
public class Snake {
    public void s(int n){
        for(int i=0;i<n;i++){
            System.out.print("=");
        }
        System.out.println("(:)-");
    }
}

```
> 0 votes

# Answer
# Bash, ~~52~~ 36 bytes

~~```
while [[ ${#a} -lt $1 ]];do a=$a=;done;echo "$a(:)~"

```~~
```
printf -vs %$1s;echo "${s// /=}(:)~"

```

Excellent suggestion by @manatwork.

If one would like to use external programs (sed) this could be a bit smaller(31 bytes):

```
printf "%$1s(:)~"|sed 's/ /=/g'

```

Run like that:

```
$ bash snake.sh 1
=(:)~
$ bash snake.sh 3
===(:)~

```
> 0 votes

# Answer
## Javascript (using external library) (39 bytes)

```
n=>_.Range(0,n).Write("=",x=>"")+"(:)-"

```

Link to lib: https://github.com/mvegh1/Enumerable

Code explanation: Create an array of n elements, and Write a concatenated string with "=" as the delimiter and an empty string as the current element. Then concatenate the head of the snake
> 0 votes

# Answer
# Matricks, 24 bytes

Very simple, just wanted to show off the new matrix definition feature.

```
m61:1:n;;a<40,58,41,45>;

```

Run with `python matricks.py snek.txt [[]] <input> --asciiprint`
> 0 votes

# Answer
# MATL, 12 bytes

```
61iY"'(:)-'h

```

**Try it on MATL Online**.

### Explanation

```
61       % ASCII value for '='
i        % Take input number, n
Y"       % Row vector with 61 repeated n times
'(:)-'   % Push this string
h        % Concatenate horizontally. This converts to string. Implicitly display

```
> 0 votes

# Answer
# Nim, 46 bytes

```
import strutils,future
n=>repeat("=",n)&"(:)-"

```

This is an anonymous function that must be passed to a procedure to be used. To test, use the testing program below:

```
import strutils,future
proc test(f: int -> string) = echo f(#[Your input here]#)
test(n=>repeat("=",n)&"(:)-")

```
> 0 votes

# Answer
## Clojure, 35 bytes

```
#(str(apply str(repeat %\=))"(:)-")

```

This is an anonymous/unnamed function that takes a single integer as an argument and returns a string.
> 0 votes

# Answer
## ECMAScript 6, ~~37~~ ~~44~~ 37 bytes

Try it here!

### Golfed

```
alert("=".repeat(prompt())+"(:)-");

```

### Ungolfed

```
alert("=".repeat(prompt()) + "(:)-");

```

### Revisions

* Original revision.
* Added `alert();` because it used to save to a variable, `n`. Try it here!
* Used ECMAScript 6's `String.prototype.repeat` method instead of the previous method that didn't even work and took more bytes. Try it here!

---

## ECMAScript 6, 53 bytes

This is a version of the above code that is a function, not a full program. Try it here!

### Golfed

```
function makeSnakeArt(n){return"=".repeat(n)+"(:)-")}

```

### Ungolfed

```
function makeSnakeArt(n) {
    return "=".repeat(n) + "(:)-"
}

alert(makeSnakeArt(5));

```

### Revisions

* Original revision, stemming off the 3rd revision of the full program. Try it here!
* Returns the snake instead of alerting it. Try it here!
> 0 votes

# Answer
## PL/SQL: 28 bytes

```
rpad('=','&n','=')||'(:)-');

```
> 0 votes

# Answer
# VBA, 37 bytes

```
Function S(L):S=String(L,"=")&"(:)-"

```

and `enter` gives the `End Function`. Immediate window of VBA editor:

```
?S(41)
=========================================(:)-

```
> 0 votes

# Answer
# Brainfuck, 67 bytes

Code:

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

```

Explanation:

```
> At #1
++++++[>++++++++++<-]>+< Put '=' in #2
, Input into #1
[->.<] Output '=' #1 times thereby emptying #1
<++++[>++++++++++<-]>. Put '(' in #1 and output

> At #2
--- Change #2 to ':'
. Output

< At #1
+.++++. Change to '(' and 'minus' and output

```

Try it online!

Input works using the corresponding ASCII characters - that is, to input 33 you would type `!`. For convenience, you can use `\d` as the input in the interpreter linked, where `d` is any non-negative integer.
> 0 votes

# Answer
# Julia, 15 bytes

```
x->"="^x*"(:)-"

```

Wow, this is short.
> 0 votes

# Answer
# Racket, 46 bytes

```
(λ(n)(string-append(make-string n#\=)"(:)-"))

```

Pretty terrible golfing language :)))
> 0 votes

# Answer
# , 10 chars / 13 bytes

```
⍘=Ċï+'(:)-

```

`Try it here (ES6 browsers only).`

Should be rather self-explanatory.
> 0 votes

# Answer
# Silicon, 12 bytes

```
I"="*"(:)-"+

```

**Explanation:**

```
I"="*"(:)-"+

    *   Times
I       Get an integer as input
"="     Push "="

"(:)-"  Push "(:)-"
+       Append

```

**Alternatively, 11 bytes:**

```
"="ã"(:)-"+

```
> 0 votes

# Answer
# PHP, 27 bytes

Not the most wonderfull creation, but with register\_globals on you can set it via url.

```
<?=str_repeat('=',$n)?>(:)-

```
> 0 votes

# Answer
# Ruby, 20 bytes

```
->n{puts?=*n+"(:)-"}

```
> 0 votes

# Answer
# Ruby, 27 bytes

```
puts"="*($*[0].to_i)+"(:)-"

```
> 0 votes

# Answer
# J, 14 bytes

```
'(:)-',~'='#~]

```

Very simple. This is a five train:

```
'(:)-' ,~ '=' #~ ]

```

Both strings, in this case, become constant verbs. `#~` essentially repeats its left argument the amount of times as its right argument. `,~` then appends its left argument to the end of its right argument.

Test cases:

```
   f 2
==(:)-
   f 7
=======(:)-
   f 10
==========(:)-
   f 0
(:)-

```

I think that it would look more snake-like with a tilde at the end, but eh.
> 0 votes

# Answer
# Kotlin, 34 bytes

```
{String(ByteArray(it){61})+"(:)-"}

```

This assumes that a function of `(Int)->String` type is requested (in such case, `it` is assumed to be an `Int`). Version with explicit typing (40 bytes):

```
{n:Int->String(ByteArray(n){61})+"(:)-"}

```

Try it out on the JVM target:

```
fun main(args: Array<String>) {
    val f: (Int)->String = {String(ByteArray(it){61})+"(:)-"}
    println(f(5))
}

```
> 0 votes

# Answer
# R, 39 bytes

Mildly different than others above

```
for(i in 1:scan())cat("=");cat("(:)-")

```

or, if we can precede the line with the input

```
->n;for(i in 1:n)cat("=");cat("(:)-")

```
> 0 votes

# Answer
## Perl, 16 bytes

```
say'='x<>.'(:)-'

```

Takes input from stdin
> 0 votes

# Answer
## Pyke, 10 bytes

```
\=*"(:)-"+

```

Try it here!

Or 8 bytes (noncompeting)

```
\=*"(:)-

```

Try it here!
> 0 votes

# Answer
# Python, 23 bytes

```
print'='*input()+'(:)-'

```
> 0 votes

# Answer
## Ruby, 24 bytes

```
def f(l) ?=*l+"(:)-";end

```
> 0 votes

# Answer
# PyMin, 15 bytes

```
»"="*¬+"(:)-"

```
> 0 votes

# Answer
# GameMaker Language, 49 bytes

```
s="(:)-"for(a=0;a<argument0;a++){s="="+s}return s

```
> 0 votes

# Answer
# Factor 34

```
[ [ "="write ] times "(:>~"print ]

```

Quotation (anonymous function) that takes a number and prints a snake.

Alternative (also 34):

```
[ 61 <string> ":>~""("glue print ]

```

<sup>Sorry, but i made some aesthetic changes...</sup>

```
10 [ [ "="write ] times "(:>~"print ] call
==========(:>~

```
> 0 votes

# Answer
## Neoscript, 15 bytes

```
{n|'=*n+"(:)-"}

```
> 0 votes

# Answer
# Fourier, 28 bytes

```
I(61ai^~i)40a-8a58a32a41a+4a

```

Try it online
> 0 votes

# Answer
## GNU sed, 16 bytes

```
y/0/=/;s/$/(:)-/

```

Since sed has no native support for numbers, the input is given in unary based on this consensus.

**Run:**

```
sed -f snake.sed <<< "000"

```

**Output:**

```
===(:)-

```
> 0 votes

# Answer
# Scala, 30 Bytes

```
(x:Int)=>print(("="*x)+"(:)-")

```
> 0 votes

# Answer
# Microscript, 14 bytes

```
ic'=P]"-):("ah

```
> 0 votes

# Answer
# Microscript II, 13 bytes

```
"="sN*p"(:)-"

```
> 0 votes

# Answer
# SNOBOL4 (CSNOBOL4), 39 bytes

```
 OUTPUT =LPAD('(:)-',INPUT + 4,'=')
END

```

Try it online!
> 0 votes

# Answer
# Charcoal, 7 bytes

```
×=Ｎ(:)-

```

Try it online!

This is equivalent to the following code:

```
Print(Times("=", InputNumber()));
Print("(:)-");

```
> 0 votes

# Answer
# Excel VBA, 20 Bytes

Anonymous VBE immediate window function that takes input, `a`, from range `[A1]` and outputs a snake of the length `a` to the VBE immediate window.

```
?[Rept("=",A1)]"(:)-

```
> 0 votes

# Answer
# Sinclair ZX80 (4K ROM) ~39 bytes

```
 1 INPUT L
 2 FOR I=1 TO L
 3 PRINT "=";
 4 NEXT I
 5 PRINT "(:)-"

```

No explanation needed really.
> 0 votes

# Answer
# JavaScript 6, input unary '=', 11B

```
x=>x+'(:)-'

```

Standard rule allowes it.

Fix it if that's not what you want.
> 0 votes

---
Tags: code-golf, string, ascii-art, kolmogorov-complexity
---


title: Mimic R's print(x, digits=n)

text:
# Question
Title: Mimic R's print(x, digits=n)
In R print(x, digits=n) does something a little complicated.

It always shows all the digits to the left of the decimal point and then, if there are any digits to the right it rounds the whole number so that at most n digits are shown. However, leading 0s are not counted. Here are examples to show how the function works.

```
print(2,digits=2)
2
print(23,digits=2)
23
print(23.12,digits=2)
23
print(2.12,digits=2)
2.1
print(0.126,digits=2)
0.13
print(23236.12,digits=6)
23236.1
print(123,digits=2)
123
print(0.00, digits=2)
0
print(23236.12,digits=1)
23236
print(1.995,digits=3)
2
print(0.0336, digits=3)
0.0336

```

Given decimal number \\$0 \<= x \<= 2^{40}\\$ and \\$n \leq 22\\$ as inputs, your code should mimic R's print(x, digits=n) function.

# Rounding

This is different from my comment below, apologies. I didn't understand the problems with rounding before. It turns out rounding has no easily understandable rule in R (or Python for that matter). For example,

```
print(0.05, digits=1)
0.05
print(0.15, digits=1)
0.1
print(0.25, digits=1)
0.2
print(0.35, digits=1)
0.3
print(0.45, digits=1)
0.5
print(0.55, digits=1)
0.6
print(0.65, digits=1)
0.7
print(0.75, digits=1)
0.8
print(0.85, digits=1)
0.8
print(0.95, digits=1)
0.9

```

As a result, you can round either up or down as you choose in your answer. If you can follow what R does, all the better, but it is not a strict requirement.

# Answer
> 5 votes
# Desmos, 44 bytes

```
f(x,n)=round(x,max(0,n-floor(log(x+0^x))-1))

```

Try It On Desmos!

Try It On Desmos! - Prettified

I think this should work??? Tell me if there's anything wrong.

# Answer
> 5 votes
# , 5 bytes

```
print

```

Attempt This Online!

Somebody had to do it.

# Answer
> 2 votes
# Python, 52 bytes

```
lambda n,d:(f'{n:.{d}g}',s:=str(round(n)))[d<len(s)]

```

Attempt This Online!

# Answer
> 1 votes
# Python, ~~77 84 81 67~~ 66 bytes

-3 thanks to solid.py

```
lambda n,d:len(str(n).split('.')[0])<d and f"{n:.{d}g}"or round(n)

```

Attempt This Online!

# Answer
> 1 votes
# , 34 bytes

```
\(n,d)round(n,max(d-log10(n)-1,0))

```

Attempt This Online!

The answer is 29 bytes longer than the question...

# Answer
> 0 votes
# Retina 0.8.2, 116 bytes

```
^\d+
$*
(1)+,([.0]*(?<-1>\.?\d)+((?<=\..*)|\d*))\.?([5-9])?.*
$2$#4$*#
^[.9]*#
0$&
T`#9d`_d`.[.9]*#
\.?(?<=\..*)0+$

```

Try it online! Link includes test cases. Takes input in the order `n,x`. Explanation:

```
^\d+
$*

```

Convert `n` to unary.

```
(1)+,([.0]*(?<-1>\.?\d)+((?<=\..*)|\d*))\.?([5-9])?.*
$2$#4$*#

```

Capture `n` in `$#1`, so that a balancing group can be used to count significant digits, but if we don't pass a decimal point, capture all the digits before the decimal point. Also note whether the next digit (if any) is at least `5`. Keep only the counted or integer digits and the next digit flag.

```
^[.9]*#
0$&

```

If the value is all `9`s and the next digit was at least `5` then prefix a `0` for the overflow.

```
T`#9d`_d`.[.9]*#

```

If the next digit was at least `5` then increment the captured digits.

```
\.?(?<=\..*)0+$

```

Remove any trailing zeros in the decimal part.

---
Tags: code-golf
---