title: Draw the "Cool S"

text:
# Question
Title: Draw the "Cool S"
## Introduction

We all know the cool S (also known as Superman S, Stüssy S, Super S, Skater S, Pointy S, Graffiti S etc. etc.): billions of schoolchildren around the world drew this S and immediately felt proud of themselves. In case you've forgotten or had a *completely uncool childhood*, here is an image of said cool S:

Given a scale factor `n` as input (where \\$1\leq n\leq 20\\$), output the Cool S in ASCII art.

## How to Draw It

From the Wikipedia page on the Cool S:

## Output

The Cool S when `n` = 1 is:

```
   ^
  / \
 /   \
/     \
|  |  |
|  |  |
\  \  /
 \  \/
 /\  \
/  \  \
|  |  |
|  |  |
\     /
 \   /
  \ /
   v

```

And for different values of `n`, you simply make the output `n` times bigger. For example, `n`=2:

```
     ^
    / \
   /   \
  /     \
 /       \
/         \
|    |    |
|    |    |
|    |    |
|    |    |
\    \    /
 \    \  /
  \    \/
  /\    \
 /  \    \
/    \    \
|    |    |
|    |    |
|    |    |
|    |    |
\         /
 \       /
  \     /
   \   /
    \ /
     v

```

Note that the vertical sections are two times longer and the spacing between the vertical lines is two times wider.

And when `n`=3:

```
       ^
      / \
     /   \
    /     \
   /       \
  /         \
 /           \
/             \
|      |      |
|      |      |
|      |      |
|      |      |
|      |      |
|      |      |
\      \      /
 \      \    /
  \      \  /
   \      \/
   /\      \
  /  \      \
 /    \      \
/      \      \
|      |      |
|      |      |
|      |      |
|      |      |
|      |      |
|      |      |
\             /
 \           /
  \         /
   \       /
    \     /
     \   /
      \ /
       v

```

***Note:*** Although not required, your code may also be able to support `n`=0:

```
 ^
/ \
\\/
/\\
\ /
 v

```

## Winning

The shortest program in bytes wins.

# Answer
# Charcoal, 58 53 47 43 41 bytes

```
Ｎθ≔⊕⊗θδ↗θ/⊗θ↘δ^‖Ｂ↓‖Ｍ← vＭδ⁰⊗θ↗⊕θＭ⁰δ↗θ/⊗θ⟲Ｔ

```

Try it online!

I just wanted to try another approach, this draws the outside via reflections (thanks to Neil for expanding the idea) and then draws the inside part. As Charcoal has `:Left` as default direction to draw lines, I make use of that direction as much as possible to save some bytes by drawing the S horizontally, like this:

```
     /----\    /----\
    /      \  /      \
   /        \/        \
  /         /          \
 /         /            \
v     ----/    /----     ^
 \            /         /
  \          /         /
   \        /\        /
    \      /  \      /
     \----/    \----/

```

And then I just need to rotate the canvas 90 degrees counterclockwise.
> 17 votes

# Answer
# Charcoal, ~~47~~ ~~42~~ 41 bytes

```
Ｆv^«↓⊗θ↘⊗⊕θ←↓⊗θ↙⊕⊗θ↖ι↖⊕⊗θ→↑⊗θ↗⊕θＭθ⁺⊗θ⊕θ⟲⁴

```

Try it online! Link is to verbose version of code. Explanation: Draws the following lines in order:

```
   ^
  / \
 /   \
/     \
|  1  |
|  1  |
\  2  /
 \  2/
 8\  2
8  \  2
7  |  3
7  9  3
6     4
 6   4
  6 4
   5

```

Where `5` is the current character of the string `v^`. At the end of the first loop the cursor is then positioned at point `9`. The entire canvas is then rotated so that the other half of the Cool S can be drawn. (The canvas actually gets rotated twice, but this is just an implementation detail.)

Charcoal doesn't support `RotateCopy(:Up, 4)` but if it did then this would work for 33 bytes:

```
↖^↖⊕⊗θ→↑⊗θ↗⊕θ‖ＢＭ↓↙⊗θ→↓⊗θ⟲Ｃ↑⁴Ｊ⁰¦⁰v

```
> 16 votes

# Answer
# Python 3, ~~255~~ ~~249~~ ~~248~~ 209 bytes

-6 bytes thanks to Kevin Cruijssen

-1 byte thanks to Kevin Cruijssen

-39 bytes thanks to Rod and Jo King

```
n=int(input())
m=2*n
a,b,q,c,l='\ \n/|'
f=m*b
s=q+q.join([f[d:]+c+b*2*d+b+a+f[d:]for d in range(m+1)]+[l+f+l+f+l]*m+[d*b+a+f+a+f[d*2:]+c+d*b for d in range(n)]+[n*b+a+f+a+c+n*b])
print(f,'^'+s+q+s[::-1]+f,'v')

```

Try it online!

It now handles n=0.
> 15 votes

# Answer
# Canvas, ~~36~~ ~~32~~ 29 bytes

```
«|＊‼ｌ├／Ｌ１^╋；╶╵＼∔∔│α╶«├：╵╋：↔↕∔

```

Try it here!

A whole lot of stack manipulation. (outdated) explanation:

```
«|*                                an array of input*2 "|"s
   ‼                               cast to a 2D object (needed because bug)
    :                              duplicate that (saved for the center line)
     l├                            height+2
       /                           create a diagonal that long
        L1^╋                       and in it, at (width; 1) insert "^"
            ;∔                     append the vertical bars
                               ^
                              /
          so far done:       /
                            /
                            |
                            |
              ⁸╵                   input+1
                \                  antidiagonal with that size
                 ∔                 appended to the above
                  │                mirror horizontally
                              ^
                             / \
                            /   \
                           /     \
                current:   |     |
                           |     |
                           \     /
                            \   /                                                       |
                   α               get the 2nd to last popped thing - the antidiagonal  |
                    └∔             append it to the vertical line copied way before:    \
                      ⁸«├          input/2 + 2                                            \
                         :╵        duplicate + 1
                           ╋       at (input/2 + 2; input/2 + 3) in the big part insert  ^
                            :↔↕∔   mirror a copy vertically & horizontally and append that to the original

```
> 10 votes

# Answer
# C (gcc), ~~260~~ 254 bytes

-6 bytes thanks to ceilingcat.

```
f(n){int s=2*n++,t=s+1,I[]={1,t,s,n,n,s,t,1},A[]={s,1,1,1,2*t,1,t,t,1,t,1,n,t,t,1,t,t,1,1,1,t,s,1,1},x;for(s=8;s--;)for(n=0;n<I[s];n++,puts(""))for(t=3;t--;)x=s*3+t,printf("%*c",n*("AAAA?BAAAAC@?ABAAACA@AAA"[x]-65)+A[x],"w!!!0]}}}]]00]]}}}]!0_!!"[x]-1);}

```

Try it online!

## Rundown

We can divide the shape into parts:

```
 ^           Top cap
/ \          Top slope
|||          Sides
\\/          Twist, part 1
/\\          Twist, part 2
|||          Sides
\ /          Bottom slope
 v           Bottom cap

```

Each part could be described by a number of lines, three chars, and three relationships to certain values that decides the field-width at each line.

A first iteration came to be:

```
#define g(x,s,A,B,C)for(i=0;i<x;i++)printf("%*c%*c%*c\n",A,*s,B,s[1],C,s[2]);
f(n)
{
    int s=2*n++,t=s+1,i;

    g(1,  "  ^",  1,      1,  t-1)
    g(t, "/ \\",t-i,      1,2*i+1)
    g(s,  "|||",  1,      t,    t)
    g(n,"\\\\/",i+1,      t,t-2*i)
    g(n,"/\\\\",n-i,  2*i+1,    t)
    g(s,  "|||",  1,      t,    t)
    g(t, "\\/ ",i+1,2*t-2*i,    1)
    g(1,  "  v",  1,      1,  t-1)
}

```

The calls to the `g()` macro looks very much like a table could be constructed and looped over. Field-widths are sometimes related to the index counter, and sometimes not. We can generalise the field-width to be `F * i + A`, where F is some factor to multiply `i` with, and A is some value to add to the width. So the last width of the fourth call above would be `-2 * i + t`, for example.

Thus we get:

```
f(n){int s=2*n++,t=s+1,         s = size of "side" parts, t = size of top and bottom slopes
I[]={1,t,s,n,n,s,t,1},          The number of lines per part.
A[]={...},x;                    A[] holds the values to add to each field-width.
for(s=8;s--;)                   Loop through the parts.
for(n=0;n<I[s];n++,puts(""))    I[s] decides how many lines to the part. Ends with newline.
for(t=3;t--;)                   Go through the three chars of each line.
x=s*3+t,                        Calculate offset.
printf("%*c",                   Print the char.
n*("..."[x]-65)+A[x],           Build field-width. The string holds the index factor, A[]
                                holds the offset part.
"..."[x]-1);}                   The char itself is grabbed from the string.
                                Shifted by 1 to eliminated double backspaces.

```

In the end it was not much shorter than a tightened version of the `g()` calling one, but shorter is shorter.
> 6 votes

# Answer
# Python 2, ~~227~~ ~~208~~ ~~207~~ ~~202~~ ~~196~~ 181 bytes

```
I=n=2*input()
R,L,S,P='/\ |'
k=n*[2*(P+S*n)+P]
exec"k=[R+S+2*S*I+L]+k+-~I%2*[L+S*n+L+S*I+R];I-=1;"*-~n
print'\n'.join(t.center(2*n+3)for t in['^']+k+[a[::-1]for a in k[::-1]]+['v'])

```

Try it online!

Thks to Jo King for 1 byte; and then another 5 bytes total (via `n => 2*n`).

Works for `n=0` as well.
> 4 votes

# Answer
# C (gcc), 379 353 344 334 bytes

I used a couple of `#define`s for subexpression elimination and several globals to communicate between the internal functions. The main loop goes {0,1,2,3,3,2,1,0} to construct the S.

Thanks to Jonathan Frech for the suggestions.

```
#define z(a,b...)printf("%*c%*c%*c\n"+a,b);}
#define y(a){for(i=~-a*t;v*i<v*a*!t+t;i+=v)
i,n,p,r,t,u,v;a(){z(6,r+2,94+t*24)b()y(-~r)z(3,-i-~r,47+u,i*2+2,92-u)c()y(r)z(0,~r,124,~r,124,~r,124)d()y(-~n)z(0,i+1,92-u,2*(n-t*i)+1,92,2*(n-!t*i)+1,47+u)(*x[])()={a,b,c,d};f(s){r=2*s;for(p=0;p<8;x[7*t-p++*(2*t-1)](n=s))t=p>3,v=2*!t-1,u=t*45;}

```

Try it online!
> 4 votes

# Answer
# PHP, ~~378~~ ~~374~~ ~~378~~ ~~377~~ ~~376~~ ~~335~~ ~~331~~ 328 bytes

-3 bytes, thanks to manatwork

-4 bytes, used str\_pad instead of str\_repeat

-41 bytes, thanks to manatworks' suggestions

-1 byte, merged two increments into a +=2

-1 byte, removed superfluous \

~~-4 bytes by echoing once.~~ Forgot I needed to pass the string into the function so this is more bytes

Works for n = 0 as well.

```
function s($b){return str_pad($w,$b);}echo s($i=1+$a=2*$argv[1]).'^
';for(;$i;$j++,$y=$z.$y)echo$z=s(--$i).'/'.s(++$j).'\
';for(;$k<$a;$k++)$x.='|'.s($a).'|'.s($a).'|
';echo$x;for(;$l<=$a/2;)echo s($m++).$c='\\',s($a).$c.s($a-$l++*2).'/
';for(;$m;$n+=2)echo s(--$m).'/'.s($n).$c.s($a).'\
';echo$x.strtr($y,'/\\','\/').s($a+1).v;

```

Try it online!
> 4 votes

# Answer
# Java, 435 bytes

The function itself takes 435 bytes. There is certainly room for improvement, "high level" by analyzing the rules about where to place which character (in the end the S is point-symmetric), and "low-level", by classical golfing (maybe pulling out another variable or combining two of the `for`-loops). But it's a first shot with this rather ungolfy language:

```
import static java.util.Arrays.*;
import static java.lang.System.*;

public class CoolS
{
    public static void main(String[] args)
    {
        print(1);
        print(2);
        print(3);
    }
    static void print(int n){int i,r,d=3+6*n,w=3+n*4,h=6+n*10,m=n+n,v=w/2,k=h-1,j=w-1;char t[],S='/',B='\\',P='|',s[][]=new char[h][w];for(char x[]:s)fill(x,' ');s[0][v]='^';s[k][v]='v';for(i=0;i<1+m;i++){r=i+1;t=s[r];t[v-r]=S;t[v+r]=B;t=s[k-r];t[v-r]=B;t[v+r]=S;}for(i=0;i<m;i++){r=2+m+i;t=s[r];t[0]=t[v]=t[j]=P;t=s[k-r];t[0]=t[v]=t[j]=P;}for(i=0;i<1+n;i++){r=2+m+m+i;t=s[r];t[i]=t[i+1+m]=B;t[j-i]=S;t=s[d-i];t[i]=S;t[v-i]=t[j-i]=B;}for(char x[]:s)out.println(x);}
}

```
> 3 votes

# Answer
# \>\<\>, 1024 bytes

```
i'0'-i1+:?!v1-'0'-$a*+1v
v          <           <
>~     :1-2*3+ >1-' 'v       v                                             oa&0~~~<
 v&1:oa*2:~o'^'^?:o  <                                              >~'/'o$:v    <^        <
>>' 'o1-: ?v   v                  >@ '\'o$v v   -1o<           >          v >:?vv^ -1<     ^     <
:^         <   ~                  ~>      \:>:?v       v  >'/'v^o' '^!?:-1<:<  > ' 'o^ >'\'o:1-?v^
- vo' '<:&o'/' < <                ^^?:o' '\  \ >' '/'\'\~$^ > o:?v~1>$  :?v$^   ~!   oa  $+2$-1 <
^1\1-:?^~'\'oao v                /        \-1<:@@~o/o1-    v^a<  >1+^v:$-2<vo'\'<      ^@~<v             <
 v^?:+1v!?:-1&+2/            /   /        \        \' '^!?:<         <     >$@@:>1-' 'o:?v^      >~'\'o$v^    oa<
       >         ^     /-1   /-1 /        \        \       \:0:<                ^        <   v      -1< :v o' '<^ +1$-2  <      v    -1<
 >~&~1&         >:2*:1->'|'o1>@@:>' 'o1-:?^~@'|'o:?^~ao:  ?^~&?^                 1+2*0     >:>:?!^' 'o^ >>1-: ?^~'/'o:2-?^@@2*ao>' 'o:?^'v'o ;

```

Takes one number `1-99` as input and draws the Cool S.
The program uses only one stack to store the number of spaces.
It is almost not golfed, coded just for practice and fun :D
Try it online!
> 3 votes

# Answer
# Python 3, ~~321~~ 307 bytes

Thanks to @EsolangingFruit for saving 14 bytes

```
n=int(input())
b,f='\/'
c,l=4*n+3,10*n+6
r=range
h=c//2
L=[c*[' ']for _ in r(l)]
L[0][h],L[-1][h]='^v'
for i in r(h):a=L[h-i];a[i],a[c+~i]=f,b
for i in r(2*n):L[h-~i][0::h]='|'*3
for i in r(n+1):a=L[h+h+i];a[c+~i],a[i:c-1:h]=f,b*2
for i in r(1,l//2):L[l+~i]=L[i][::-1]
print('\n'.join(''.join(i)for i in L))

```

Try it online!

# Python 2, 303 bytes

```
n=int(input())
b,f='\/'
c,l,r=4*n+3,10*n+6,range
h=c/2
L=[c*[' ']for _ in r(l)]
L[0][h],L[-1][h]='^v'
for i in r(h):a=L[h-i];a[i],a[c+~i]=f,b
for i in r(2*n):L[h-~i][0::h]='|'*3
for i in r(n+1):a=L[h+h+i];a[c+~i],a[i:c-1:h]=f,b*2
for i in r(1,l/2):L[l+~1]=L[i][::-1]
print'\n'.join(''.join(i)for i in L)

```

Try it online!
> 2 votes

# Answer
# Regenerate, 180 bytes

```
( {2*$~1}) ^\n(( {#3-1}|$1)/(  $4| )\\\n){#1+1}((\|$1\|$1\|\n){#1})(( $8|)(\\$1\\)( {#10-2}|$1)/\n){$~1+1}(( {#12-1}|$8)/(  $13|)$9\n){$~1+1}$5(( $15|)\\( {#16-2}|$4)/\n){#1+1}$1 v

```

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

### Explanation

Hoo boy, this is long. It's not actually super-complicated, though; once you get a few basic principles of golfing in Regenerate, this just uses the same techniques over and over.

```
( {2*$~1})

```

Group 1: Take the command-line argument (`$~1`), multiply it by 2, and add that many spaces.

```
 ^\n

```

Complete the first line with one more space, `^`, and a newline.

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

```

Group 2 generates one line of the `/ \` section. Repeat it (length of group 1, plus 1) times. It contains groups 3 and 4.

```
( {#3-1}|$1)/

```

Group 3: Add spaces, one fewer than the last time we matched group 3; or, if group 3 hasn't been matched before, start with the contents of group 1 (arg * 2 spaces) instead. After group 3, add a forward slash.

```
(  $4| )\\\n

```

Group 4: Add spaces, two more than the last time we matched group 4; or, if group 4 hasn't been matched before, start with one space instead. After group 4, add a backslash and a newline.

```
((\|$1\|$1\|\n){#1})

```

Group 5 is the whole vertical lines section, which we're capturing because we can reuse it verbatim later. Specifically, this is (length of group 1) repetitions of group 6, which consists of: pipe, group 1, pipe, group 1, pipe, newline.

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

```

Group 7 generates one line of the `\ \/` section. Repeat it (argument plus 1) times. It contains groups 8, 9, and 10.

```
( $8|)

```

Group 8: Add spaces, one more than the last time we matched group 8; or, if group 8 hasn't been matched before, start with empty string instead.

```
(\\$1\\)

```

Group 9: backslash, group 1, backslash (capture for reuse later).

```
( {#10-2}|$1)/\n

```

Group 10: Add spaces, two fewer than the last time we matched group 10; or, if group 10 hasn't been matched before, start with the contents of group 1 instead. After group 10, add a forward slash and a newline.

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

```

Group 11 generates one line of the `/\ \` section. Repeat it (argument plus 1) times. It contains groups 12 and 13.

```
( {#12-1}|$8)/

```

Group 12: Add spaces, one fewer than the last time we matched group 12; or, if group 12 hasn't been matched before, start with the most recent contents of group 8 instead. After group 12, add a forward slash.

```
(  $13|)$9\n

```

Group 13: Add spaces, two more than the last time we matched group 13; or, if group 13 hasn't been matched before, start with empty string instead. After group 13, add the contents of group 9 (two backslashes with some spaces in between) and a newline.

```
$5

```

Add the contents of group 5 again (vertical pipes section).

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

```

Group 14 generates one line of the `\ /` section. Repeat it (length of group 1, plus 1) times. It contains groups 15 and 16.

```
( $15|)\\

```

Group 15: Add spaces, one more than the last time we matched group 15; or, if group 15 hasn't been matched before, start with empty string instead. After group 15, add a backslash.

```
( {#16-2}|$4)/\n

```

Group 16: Add spaces, two fewer than the last time we matched group 16; or, if group 16 hasn't been matched before, start with the most recent contents of group 4 instead. After group 16, add a forward slash and a newline.

```
$1 v

```

For the last line, add the contents of group 1, a space, and `v`.
> 2 votes

# Answer
# C (gcc), ~~271~~ ~~261~~ ~~253~~ 230 bytes

-10 bytes by moving `2*` inside `S` macro

-8 bytes by placing `u,d` in the global scope and replacing `(n-u)` with `d`

-23 bytes by abusing the C preprocessor, thanks to @ceilingcat

```
#define S(i,c)printf("%*s"#c,2*i,"");
#define R(m)}for(u=0,d=n*m+1;d--;u++){S(0+
#define V(x,y)S(x,\\\n)R(2-1)0,|)S(n,|)S(n,|\n)R(y)u,\\)S(
u,d;f(n){{S(n+1,^\n)R(2)d,/)V(u+1,1)n,\\)S(d,/\n)R(1)d,/)S(u,\\)V(n,2)d+1,/\n)}S(n+1,v\n)}

```

Try it online!
> 1 votes

# Answer
# Vyxal `C`, 49 bytes

```
\^?d›(\/n꘍øM)\|?꘍m∞?dḊ?›(\\?꘍m?›n-d꘍\/J)W:ṘRJṪ\vJ

```

Try it Online!

Will add explanation tomorrow.
> 0 votes

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


title: Circular chained compound

text:
# Question
Title: Circular chained compound
# Task

Given a positive integer `n`, output the joined compound of circles

The circles are of square of size `n+2` but removing the corner edges and the middle, before finally overlapping `n` times of itself

E.g.

```
2

```

-\>

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

```

-\>

```
 ##
#  #
#  #
 ##

```

-\>

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

```

# Testcases

```
1
->
 #
# #
 #

2
->
 ## ##
#  #  #
#  #  #
 ## ##

3
->
 ### ### ###
#   #   #   #
#   #   #   #
#   #   #   #
 ### ### ###

4
->
 #### #### #### ####
#    #    #    #    #
#    #    #    #    #
#    #    #    #    #
#    #    #    #    #
 #### #### #### ####

```

Trailing spaces are allowed

You have to use the character `#`

You have to join the strings by newlines (no lists)

This is , so shortest code wins!

# Answer
# 05AB1E, 15 bytes

```
'#úR×Ćи¬DÙÂ‡.ø»

```

Try it online or verify the first 5 results.

**Explanation:**

```
'#             '# Push "#"
  ú             # Pad it with the (implicit) input amount of leading spaces
   R            # Reverse it so the spaces are trailing
    ×           # Repeat this the (implicit) input amount of times as string
     Ć          # Enclose; append its own head (the "#")
      и         # Repeat it the (implicit) input amount of times as list
       ¬        # Push its first item (without popping the list)
        D       # Duplicate it
         Ù      # Uniquify its characters: "# "
          Â     # Bifurcate; short for Duplicate & Reverse copy: " #"
           ‡    # Transliterate all "# " to " #" in the duplicated string
            .ø  # Surround the list with this string as leading/trailing item
              » # Join by newlines
                # (after which the result is output implicitly)

```

I initially tried to use the Canvas builtin, but it ended up at twice the amount of bytes..
> 3 votes

# Answer
# , 37 32 31 30 28 bytes

```
'# '{~(>:+*:)($=/~0,~])0,#&1

```

Try it online!

*-2 thanks to ovs for realizing XOR could be replaced with XNOR*

## key idea

The 2d pattern we seek is just the XOR function table of these two 1d patterns:

```
   0 1 1 1 0 1 1 1 0 1 1 1 0
  --------------------------
0 |0 1 1 1 0 1 1 1 0 1 1 1 0
1 |1 0 0 0 1 0 0 0 1 0 0 0 1
1 |1 0 0 0 1 0 0 0 1 0 0 0 1 <-- XOR TABLE
1 |1 0 0 0 1 0 0 0 1 0 0 0 1
0 |0 1 1 1 0 1 1 1 0 1 1 1 0

```
> 11 votes

# Answer
# Lua, 86 bytes

```
x,a,c=...," ","\n"b=a.rep;d=b(a..b("#",x),x)print(d..c..b(b("#"..b(a,x),x+1)..c,x)..d)

```

Attempt This Online! Tried moving some stuff around but couldn't get an improvement.
> 6 votes

# Answer
# K (ngn/k), 37 35 34 30 26 bytes

```
{"# "(1,s)=\:1,/x#,s:&x,1}

```

Try it online!

Yay my second k answer!

Uses @Jonah's approach.

*¯2 bytes thanks to @doug in the k tree*

*¯1 bytes by using `@`*

*¯4 bytes thanks to @ovs and @doug*

*¯4 bytes thanks to @Traws*
> 6 votes

# Answer
# Vyxal `C`, 16 bytes

```
v\#₌≬₅*Ṅ꘍R₅*ǏȮJJ

```

Try it Online!

(IMO) this is some pretty elegant code. It uses some quite neat tricks to achieve the score it is. The output format's still stupid though.

```
v\#              # Fill 1..n with spaces
   ₌-----        # Apply both to the stack...
    ≬---         # The next three elements as one
     ₅*Ṅ         # Repeat each by its length and join with spaces
        ꘍        # And prepend n spaces to each #
         R       # Reverse each of those so a # is at the start
          ₅*     # Repeat each of those by the required length
            Ǐ    # Append the first character (#)
             Ȯ   # Push the item under (the #  #  #) to the stack
              JJ # Append that and prepend it
                 # (C flag) join by newlines and centre

```

An approach similar to Jonas' answer, but independently derived:

# Vyxal `j`, 18 bytes

```
›D?*"ʀ$Ḋƒv꘍ƛ‛ #$İ∑

```

Try it Online!

The last 7 bytes exist because of the stupid output format, and some Vyxal bugs.

# Vyxal `joe`, 18 bytes

```
v\#*Ṅðp…£v\#?꘍*Ǐ¥J

```

Try it Online!

The initial version of the first approach. Who's Joe?
> 5 votes

# Answer
# Ruby, 46 bytes

```
->n{[z=(" "+?#*n)*n,[?#+(" "*n+?#)*n]*n,z]*$/}

```

Try it online!
> 4 votes

# Answer
# BQN, 25 bytesSBCS

Port of Jonah's excellent J answer.

```
" #"⊏˜·≠⌜´+⟜1(+⥊↑⟜1)¨1∾×˜

```

Run online!
> 4 votes

# Answer
# Haskell, 69 bytes

```
f n=unlines[[" # "!!(0^mod x(n+1)+0^y)|x<-[0..n*n+n]]|y<-[0..n]++[0]]

```

Try it online!
> 4 votes

# Answer
# Python, 63 bytes

```
lambda n:"\n".join(n*(a+n*b)+a for a,b in[" #",*n*["# "]," #"])
```

Attempt This Online!
> 3 votes

# Answer
# x86-64 machine code, 33 bytes

```
56 B8 20 0A B0 23 5A 52 AA 34 03 59 51 F3 AA 34 03 FF CA 75 F3 66 AB FF CE 79 E9 7A E4 88 17 59 C3

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as a null-terminated byte string, and takes the number n in RSI.

In assembly:

```
f:  push rsi            # Push n onto the stack.
sl: .byte 0xB8, 0x20, 0x0A  # These bytes combine with the next instruction to form
            #  mov eax, 0x23B00A20. In particular, the lowest byte (AL) is 0x20 (' ')
            #                           and the second-lowest byte (AH) is 0x0A ('\n').
pl: mov al, 0x23    # (Executed for the middle lines) Set AL to 0x23 ('#').
    pop rdx; push rdx   # Set RDX to n. (This is 2 bytes; mov edx, [rsp] would be 3.)
l:  stosb               # Write AL to the string, advancing the pointer.
    xor al, 3           # Change AL from ' ' to '#' or vice versa.
    pop rcx; push rcx   # Set RCX to n.
    rep stosb           # Write AL to the string RCX times, advancing the pointer.
    xor al, 3           # Change AL from ' ' to '#' or vice versa.
    dec edx             # Subtract 1 from EDX.
    jnz l               # If it's not zero, jump back. (Repeats n times.)
    stosw               # Write AL and AH ('\n') to the string, advancing the pointer.
    dec esi             # Subtract 1 from ESI.
    jns pl              # If it's not negative (which occurs n times),
                        #  jump back to make a line starting with '#'.
    jpe sl              # Jump back to make a line starting with ' '
                        #  if the sum of the eight low bits is even.
                        #  This is true for -1 (…11111111) but not for -2 (…11111110).
    mov [rdi], dl       # Add DL (the low byte of RDX), which is 0, to the string.
    pop rcx             # Take n off the stack.
    ret                 # Return.

```
> 3 votes

# Answer
# PowerShell, 58 bytes

```
param($n)($t=(' '+'#'*$n)*$n);,(('#'+' '*$n)*$n+'#')*$n;$t

```

Try it online!
> 3 votes

# Answer
# C (gcc), 102 bytes

*shorter version thanks to @ceilingcat!*

```
i=-1,j;main(n){for(n+=scanf("%d",&n);j=i++<n;puts(""))for(;j-->n-n*n;putchar("# "[!(j%n)^(i^n&&i)]));}

```

Try it online!

# C (GCC), 107 bytes

```
main(i,j,n){scanf("%d",&n);++n;for(i=-1;i++<n;puts(""))for(j=-1;j++<n*n-n;putchar("# "[!(j%n)^(i^n&&i)]));}
```

Attempt This Online!

Indented version:

```
main(i,j,n){
    scanf("%d",&n);
    ++n;
    for(i=-1;i++<n;puts(""))
        for(j=-1;j++<n*n-n;
            putchar("# "[!(j%n)^(i^n&&i)]));
}

```
> 3 votes

# Answer
# Python, ~~71~~ 67 bytes

```
lambda n:"\n".join([t:=" "+f'{"#"*n} '*n,*["#"+f'{" "*n}#'*n]*n,t])
```

Attempt This Online!

-4 bytes from @Unrelated String
> 2 votes

# Answer
# APL+WIN, 37 bytes

Prompts for n. Index origin = 0

```
' #'[(v,0)∘.≠((n×n+1)⍴v←0,(n←⎕)⍴1),0]

```

Try it online! Thanks to Dyalog APL Classic
> 2 votes

# Answer
# Charcoal, 16 bytes

```
ＮθＦθＧＨ+→⁺²θ⁺ ×θ#

```

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

```
Ｎθ

```

Input `n`.

```
Ｆθ

```

Repeat `n` times...

```
ＧＨ+→⁺²θ⁺ ×θ#

```

... draw a hollow polygon using the directions Right, Down, Left, Up, Right, of size `n+2`, using a string consisting of a space and `n` `#`s. Each polygon therefore starts at the top left of the "circle" and finishes at the top right, ready to start the next one.
> 2 votes

# Answer
# MATL, ~~18~~ 17 bytes

```
WBtTh!-GtQ*Q:Z)Zc

```

Try it online! Or verify all test cases.

### Explanation

Consider input `n = 3` as an example.

```
WB     % Implicit input: n. 2^n, convert to binary.
       % STACK: [1 0 0 0]
tTh    % Duplicate, push 1, concatenate horizontally
       % STACK: [1 0 0 0], [1 0 0 0 1]
!-     % Transpose, subtract element-wise with broadcast
       % STACK:  [0 -1 -1 -1
                  1  0  0  0
                  1  0  0  0
                  1  0  0  0
                  0 -1 -1 -1]
GtQ*Q: % Push n, duplicate, add 1, multiply, add 1: gives n^2+n+1. Range (1-based)
       % STACK:  [0 -1 -1 -1
                  1  0  0  0
                  1  0  0  0
                  1  0  0  0
                  0 -1 -1 -1], [1 2 3 4 5 6 7 8 9 10 11 12 13]
Z)     % Horizontal indexing (1-based, modular)
       % STACK: [0 -1 -1 -1  0 -1 -1 -1  0 -1 -1 -1  0
                 1  0  0  0  1  0  0  0  1  0  0  0  1
                 1  0  0  0  1  0  0  0  1  0  0  0  1
                 1  0  0  0  1  0  0  0  1  0  0  0  1
                 0 -1 -1 -1  0 -1 -1 -1  0 -1 -1 -1  0]
Zc     % Convert non-zeros to '#'. Implicit display (char(0) is displayed as space)
       % STACK: [' ### ### ### '
                 '#   #   #   #'
                 '#   #   #   #'
                 '#   #   #   #'
                 ' ### ### ### ']

```
> 2 votes

# Answer
# Jelly, 16 bytes

```
‘ð;×Ż€⁸ḍn€/ị⁾# Y

```

**Try it online!**

```
‘ð;×Ż€⁸ḍn€/ị⁾# Y - Main Link: integer, N
‘                - increment -> N+1
 ð               - start a new dyadic chain - f(N+1, N)
   ×             - multiply -> (N+1)×N
  ;              - concatenate -> [N+1, (N+1)×N]
    Ż€           - zero range each -> [[0..N+1], [0..(N+1)×N]
      ⁸          - chain's left argument -> N+1
       ḍ         - divides? (vectorises) -> [[1,0,...,0,1], [1,0,...,0,1,0,...,0,1,0,...,1]]
          /      - reduce by:
         €       -   for each:
        n        -     not equal (vectorises)
           ị⁾#.  - index into "# " (vectorises)
               Y - join with newline characters

```
> 2 votes

# Answer
# Python 3, ~~93~~ 82 bytes

Jonah's observation that this pattern can be formed easily with an XOR table intrigued me, and I wanted to see if this would produce something short in Python. Unfortunately, I couldn't come up with a good way to build the required patterns golfily, and the result clocks in 30 bytes longer than the other python answer here:

```
lambda x:"\n".join("".join(" #"[i^j]for i in[0,*[1]*x]*x+[0])for j in[0,*[1]*x,0])

```

Try it online!

Edit -11 bytes: from @DLosc's idea of using lists of ints instead of strings.

## Explanation

```
lambda x:
                                                                   for j in [0,*[1]*x,0]  ## Builds the list [0,1,1,...0], with x 1s, and loops over it
                                         for i in [0,*[1]*x]*x+[0]                        ## Builds the list [0,1,1,...0,1,1,...0,....], i.e. [0,1...] with x 1s, repeated x times, with an extra 0 at the end
                           (" ","#")[i^j]                                                 ## '#' if i xor j, else ' '
                   "".join(                                       )                       ## .join the characters of this line
         "\n".join(                                                                     ) ## Encapsulate it in a list for output

```
> 2 votes

# Answer
# Perl 5 `-pa`, 43 bytes

```
say$_=$".('#'x$_.$")x$_,($/.y/ #/# /r)x"@F"

```

Try it online!
> 2 votes

# Answer
# Mathematica 12, 83 bytes

```
StringRiffle[StringJoin/@Table[If[#∣i⊻#∣j,"#"," "],{j,0,#},{i,0,#2#}]&[#+1,#],"\n"]&

```

Uses the obvious divisibility trick, and *Mathematica*'s good unicode parsing

Try it online!
> 2 votes

# Answer
# flax `C`, 21 19 18 bytes

```
₊ #iZŻ≠⌜ŻF₎⍴⊂µ¬W1⍪

```

~~Not happy with the byte count...~~

Slightly better.

-1 byte by implicit joining of newlines.
> 2 votes

# Answer
# Retina 0.8.2, 79 bytes

```
.+
$*
1
$_¶
^
$%' #¶
¶$
¶$%` #
\b¶
# ¶
%(`1
$_¶
1(?=.*(.))
$1
.¶

(.+)(.).
$2$1

```

Try it online! Explanation:

```
.+
$*

```

Convert to unary.

```
1
$_¶

```

Replicate the line of `n` `1`s `n` times.

```
^
$%' #¶

```

Prefix a line of `n` `1`s with a suffix of  `#`. This indicates the pattern for the first line.

```
¶$
¶$%` #

```

Append another such line.

```
\b¶
# ¶

```

Append `#`  to the original `n` lines. These indicate the pattern for the intermediate lines.

```
%(`

```

Apply the rest of the script separately to each line.

```
1
$_¶

```

Repeat each line `n` times. This also leaves an extra copy of the two pattern characters on a line on its own.

```
1(?=.*(.))
$1

```

Replace each `1` with the last character on the line.

Delete last character on each line as it is joined with the next line.

```
(.+)(.).
$2$1

```

Move the final copy of the first pattern character to the start of the entire line and delete the final copy of the second pattern character.
> 1 votes

# Answer
# Retina, 40 bytes

```
.+
*$( $&*#)¶$&*$(*$(#$&* )#¶)$&*$( $&*#

```

Try it online! Link includes test cases. Explanation: Just some boring string repetition. The final line parses as `$&*$( $&*#)¶$&*$($&*$(#$&* )#¶)$&*$( $&*#)` where the `$()` is a grouping construct and `$&*` repeats the character or group the number of times given by the input.
> 1 votes

# Answer
# JavaScript (V8), ~~66~~ 65 bytes

```
n=>(t=(r=s=>s.repeat(n))(' '+r('#'))+`
`)+r(r('#'+r(' '))+`#
`)+t

```

Try it online!
> 1 votes

# Answer
# Haskell, 86 bytes

```
t=(.cycle).take
f n=unlines$t(n+2)[t(n^2+n+1)[" # "!!(x+y)|x<-l]|y<-l]where l=1:t n[0]

```

Try it online!
> 1 votes

# Answer
# Headascii, 121 bytes

```
+OUO{^)+E:ROD-}.UOD++++[]]]][]]O[UO{N-)!@++E:]PUO{^):]+++PD-};}.UO)++++E:U[{N-)+++E:]+++PUO{^):]PD-};}.OUUO{^)@+E:RO!D-}.

```

Whew!

Try it here! Code will have to be copied and executed as shown:

```
erun("+OUO{^)+E:ROD-}.UOD++++[]]]][]]O[UO{N-)!@++E:]PUO{^):]+++PD-};}.UO)++++E:U[{N-)+++E:]+++PUO{^):]PD-};}.OUUO{^)@+E:RO!D-}.","your input here")

```

But also, it takes input by charcode, so for example if you wanted to input 4, you'd type

```
"\u0004"

```

Which I think is perfectly valid :D

Code breakdown:

```
+OUO{^)+E:ROD-}. block 0
+O               push 1 to global as a flag
  UO             get n/push n to global
  U {^)  :  D-}  loop n times
          RO       push n to global
       +E      . goto block 1

UOD++++[]]]][]]O[UO{N-)!@++E:]PUO{^):]+++PD-};}. block 1
UOD                                              push flag to global
   ++++[]]]][]]O                                 push 32 to global
                [                                and store it
                 UO                              push n to global
                   {N-)     :  U              }  loop n times
                             ]P                    append 32 to string
                               UO                  push n to global
                               U {^):     D-};     loop n times
                                     ]+++P           append 35 to string
                       !@                        print string w/trailing
                                                 newline and clear string
                         ++E                   . goto block 2

UO)++++E:U[{N-)+++E:]+++PUO{^):]PD-};}. block 2
UO)                                      if flag is 0
   ++++E                                  goto block 5
        :                               else
         U[                               store 32
           {N-)    :     U           }    loop n plus 1 times
                    ]+++P                   append 35 to string
                         UO                 push n to global
                           {^):  D-};       loop n times
                               ]P             append 32 to string
               +++E                   .   goto block 3

OUUO{^)@+E:RO!D-}. block 3
O                  push 0 to global as flag
 U                 discard previous flag state
  UO               push n to global
  U {^)   :   D-}  loop n times
           RO        push n to global
             !       print string w/trailing newline
       @           clear string
        +E       . goto block 1

block 4 is empty

```

Using the global array length as an extra register is a fun trick i just learned doing this :)
> 1 votes

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


title: Count the trailing zeros

text:
# Question
Title: Count the trailing zeros
Given two positive integers \\$n\\$ and \\$b\\$, such that \\$n \> 2\\$ and \\$n \> b \> 1\\$, count the trailing zeros when converting \\$n\\$ to base \\$b\\$. Your program should be able to handle any value of \\$b\\$ within your integer maximum.

The digits of \\$n = 18\\$, \\$b = 3\\$ are \\$\[2,0,0\]\\$, so the correct output is \\$2\\$.
The digits of \\$n = 107\\$, \\$b = 43\\$ are \\$\[2, 42\]\\$, so the correct output is \\$0\\$

This is , so the shortest code in bytes wins

## Test cases

```
  n   b  out
512   2   9
248   2   3
364 265   0
764   2   2
336 284   0
517 422   0
554  37   0
972   3   5
 12   6   1
 72   2   3
 44   2   2
 51  16   0
 32   2   5
 56   7   1
 60   2   2
  8   3   0
 18   3   2
107  43   0

```

---

Credit to Anush for the inspiration

There is a one byte answer in Jelly. Can you find it?

# Answer
# Vyxal, 1 byte

```
Ǒ

```

Try it Online!

*laughs in stolen jelly built-ins*
> 11 votes

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

```
{*&|y\x}

```

Try it online!

* `|y\x` convert `x` to base `y`, reversing the resulting digits
* `&` use monadic where, e.g. convert `0 0 2` into `2 2`
* `*` return the first value
> 10 votes

# Answer
# Python 2, 31 bytes

Returns `False` for `0`.

```
f=lambda n,b:n%b<1and-~f(n/b,b)

```

Try it online!
> 9 votes

# Answer
# Jelly, 1 byte

Try it online!

Don't know Jelly
> 8 votes

# Answer
# .NET Regex, 35 bytes

```
\G(?=1+,1(1+))(?=(1\1)+,)(?<-2>\1)+

```

Try it online! Test suite written using Retina. Takes `n,b` as input in unary as strings of `1`s and outputs the result as the number of successful matches. Explanation:

```
\G

```

Each match must begin at the end of the previous match (with the first match beginning at the start of the string).

```
(?=1+,1(1+))

```

Look ahead to find `b` and capture `b-1` as `\1`.

```
(?=(1\1)+,)

```

Ensure that `1\1`, i.e. `b`, divides `n`.

```
(?<-2>\1)+

```

Subtract `b-1` times the quotient, leaving the quotient, i.e. `n/b`. This value is then the input to the next match.
> 8 votes

# Answer
# Python 3, ~~83~~ ~~78~~ ~~57~~ ~~47~~ 40 bytes

```
f=lambda n,b:1+f(n/b,b)if n>n%b<=0else 0

```

*Finally figured out how to use a lambda to solve this*
> 7 votes

# Answer
# JavaScript (V8), 22 bytes

*-3 thanks to @user*

```
d=>g=x=>x%d?0:g(x/d)+1

```

Try it online!
> 6 votes

# Answer
# MATL, ~~11~~ 8 bytes

```
_YAPf1)q

```

Inputs are in reverse order.

Try it online! Or verify all test cases.

### Explanation

Consider inputs `n = 12321`, `b = 3` as an example.

```
_    % Implicit input: b. Negate
     % STACK: -3
YA   % Implicit input: n. Convert n to specified base. A negative base -b is
     % interpreted as digits 0,1,...,b-1, and b can be arbitrarily large.
     % (A positive base b is interpreted as chars '0','1',...,'9','A','B',...,
     % and then b cannot exceed 36)
     % STACK: [1 2 1 2 2 0 1 0 0]
P    % Flip
     % STACK: [0 0 1 0 2 2 1 2 1]
f    % Find: indices of non-zeros
     % STACK: [3 5 6 7 8 9]
1)   % First entry
     % STACK: 3
q    % Subtract 1. Implicit display
     % STACK: 2

```
> 6 votes

# Answer
# MMIX, 28 bytes (7 instrs)

```
35020001 F7010000
1E000001 E7020001
FE030006 5303FFFD
F8030000

```

# Explanation

```
    NEG  $2,0,1     // set $2 to -1
    PUT  rD,0       // clear hidiv register
lop DIVU $0,$0,$1   // set $0 to $0/$1 and rR to $0%$1
    INCL $2,1       // increment $2
    GET  $3,rR      // $3 = rR
    PBZ  $3,lop     // if $3, jump back to loop
    POP  3,0        // return three registers; $2 goes into lowest slot!

```

The only tricks I used were to start the register at -1 to simplify the logic, and to use the properties of `POP` to shift the register while returning. The MMIX register shuffle is useful when golfing.

(It's possible to shave an extra tetra by using `DIV` instead of `DIVU` and omitting the `PUT`, but this changes the semantics to be signed instead of unsigned. For completeness, this leads to the following machine code.)

```
35020001 1C000001 E7020001
FE030006 5303FFFD F8030000

```
> 6 votes

# Answer
# Raku, 22 bytes

```
{($^n,*/$^x.../\./)-2}

```

Try it online!

`$^n, * / $^x ... /\./` is a sequence starting with `$^n` (the first argument to the function), where each term is obtained by dividing the previous one by `$^x` (the second argument to the function), and ending when a term matches the regex `/\./` (ie, a period). Subtracting 2 from this sequence treats it as a number equal to its length.
> 5 votes

# Answer
# Risky, 8 bytes

```
0+02?}?0?+1*?:0

```

Try it online!

## Explanation

```
0        0
+      +
0        0
2    prepend to
?        first input
}      base convert
?        second input
0  reduce
?        accumulator
+      +
1        1
*    ×
?        item
:      =
0        0

```

This problem translates really nicely to a Risky program. I had to add only two filler characters to make the tree symmetrical.
> 5 votes

# Answer
# C (gcc), ~~38~~ 27 bytes

Saved 11 bytes thanks to AZTECCO!!!

```
f(n,b){n=n%b?0:1+f(n/b,b);}

```

Try it online!
> 4 votes

# Answer
# , 16 12 bytes

```
[:#.~0=#.inv

```

Try it online!

-4 thanks to xash!

* `#.inv` Convert to list of base digits
* `0=` Converts zeroes to ones, everything else to 0.
* `[:#.~` Use that number as a mixed base to convert itself to a number -- effectively zeroes out everything to the left of the rightmost 0, summing all the ones (that were originally trailing zeroes).
> 4 votes

# Answer
# Pari/GP, 9 bytes

```
valuation

```

Try it online!
> 4 votes

# Answer
# Wolfram Language (Mathematica), 15 bytes

```
IntegerExponent

```

Try it online!

Built-in.
> 3 votes

# Answer
# Charcoal, 11 bytes

```
ＩＬ⊟⪪⭆↨ＮＮ¬ι0

```

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

```
      Ｎ     Input `n`
     ↨      Converted to base
       Ｎ    Input `b`
    ⭆       Map over elements and join
         ι  Current element
        ¬   Logical Not
   ⪪      0 Split string on literal `0`
  ⊟         Take the last string of `1`s
 Ｌ          Take the length
Ｉ           Cast to string
            Implicitly print

```
> 3 votes

# Answer
# Retina 0.8.2, 34 bytes

```
\d+
$*
+%`^(1+),(\1)+$
¶$1,$#2$*
¶

```

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

```
\d+
$*

```

Convert `b` and `n` to unary.

```
+%`^(1+),(\1)+$
¶$1,$#2$*

```

Repeatedly divide `n` by `b`.

Count the number of divisions.
> 3 votes

# Answer
# Brachylog, 9 bytes

```
ḃ₎,0a₁=kl

```

Try it online!

```
  ,0         Append a 0 to
ḃ₎           the digits of n in base b.
    a₁       Find the largest suffix
      =      all elements of which are equal,
       k     remove its last element,
        l    and output its length.

```

The shorter `ḃ₎a₁≡ᵛ⁰l` cannot handle cases with no trailing zeroes, since `a₁` cannot generate an empty suffix of a non-empty list, and if it could `≡ᵛ⁰` would fail on it anyhow.

Without utilizing base conversion:

# Brachylog, 11 bytes

```
⟨{f↔∋~^}h⟩t

```

Try it online!

```
    ∋          An element
  f            of the list of factors
⟨{     } ⟩     of n
   ↔           in descending order
     ~^ h t    is b raised to the power of the output.

```
> 3 votes

# Answer
# , 38 bytes

```
f=function(n,b)`if`(n%%b,0,1+f(n/b,b))

```

Try it online!
> 3 votes

# Answer
# Red, 48 bytes

```
f: func[n b][either(n % b)> 0[0][1 + f n / b b]]

```

Try it online!
> 3 votes

# Answer
# Julia, 18 bytes

```
n*b=n%b<1&&1+n/b*b

```

Try it online!
> 3 votes

# Answer
# Japt `-g`, 5 bytes

```
ìV Ôð

```

Try it

```
ìV Ôð     :Implicit input of integers U=n & V=b
ìV        :Convert U to a base-V digit array
   Ô      :Reverse
    ð     :0-based indices of truthy (non-zero) elements
          :Implicit output of first element

```
> 3 votes

# Answer
# Emacs Lisp, 45 bytes

```
(defun f(n b)(if(=(% n b)0)(+(f(/ n b)b)1)0))

```

Try it online!

It seems that recursive functions doesn't work for Emacs Lisp on TIO.
> 3 votes

# Answer
# Hy, 40 bytes

```
(defn f[n b](if(% n b)0(+(f(/ n b)b)1)))

```

Try it online!
> 3 votes

# Answer
# Haskell, 32 bytes

```
a?b|a`mod`b>0=0|c<-a`div`b=1+c?b

```

Try it online!
> 2 votes

# Answer
# Desmos, 64 bytes

```
c=[0...log_bn]
a=n/b^c
f(n,b)=max(c\left\{a=ceil(a):1,0\right\})

```

Try It On Desmos!

Try It On Desmos(Prettified)!

Function to test on: \\$f(n,b)\\$

It seems like it only works if you copy/paste one expression at a time, instead of copy/pasting it all at once.
> 2 votes

# Answer
# Ruby, 27 bytes

```
f=->n,b{n%b>0?0:1+f[n/b,b]}

```

Try it online!
> 2 votes

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

```
f=(n,b)=>n=n%b>0?0:1+f(n/b,b)

```

Try it online!
> 2 votes

# Answer
# Excel, 52 bytes

```
=LET(x,SEQUENCE(LOG(A2,B2)),MAX(x*(MOD(A2,B2^x)=0)))

```

My first attempt below with built-ins was limited because `BASE` only works up to 36. As a bonus the second attempt was shorter. Goes to show, built-ins aren't always the answer.

## Initial Attempt, 70 bytes

```
=LET(x,BASE(A2,B2),q,SEQUENCE(LEN(x)),MAX(q*(RIGHT(x,q)=REPT("0",q))))

```

## Using LAMBDA from Insider Beta, 41 bytes

```
=LAMBDA(n,b,IF(MOD(n,b)=0,f(n/b,b)+1,0))

```

The above is 40 bytes plus 1 byte to set it equal to f in the Name Manager.
> 2 votes

# Answer
# 05AB1E, 5 bytes

```
вRĀ1k

```

First input is base \\$b\\$, second input is \\$n\\$.

Try it online or verify all test cases.

**Explanation:**

```
в      # Convert the (implicit) input `n` to the (implicit) input-base `b` as list
 R     # Reverse this list
  Ā    # Truthify each value (0 remains 0; everything else becomes 1)
   1k  # And get the first (0-based) index of a 1 in this list
       # (after which this index is output implicitly as result)

```
> 2 votes

# Answer
# Pyth, 11 bytes

```
Mtf@_jGHtT;

```

Try it online!
> 2 votes

# Answer
# Factor, 58 bytes

```
:: g ( n b -- m ) n b mod 0 > [ 0 ] [ n b / b g 1 + ] if ;

```

Try it online!
> 2 votes

# Answer
# GAWK, 32 bytes

```
{for(;$1/$2^++e!~/\./;);$0=e-1}1

```

Strangely, does not work on TIO, and also couldn't run it in mawk.

```
{for(;                 starts the loop
      $1/$2^++e        divides n by b^(e), e increasing each time
               !~/\./  continue while this division does not match a dot
                       (i.e, while it's a integer)
    ;);                the semicolon after the for means "run no command while looping"
    $0=e-1             after looping, substitutes the input ($0) for e-1
}1                     shows $0

```
> 1 votes

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


title: Output the Iccanobif Sequence

text:
# Question
Title: Output the Iccanobif Sequence
Write a program or named function that will output or return the sequence up to the `n`th integer in the Iccanobif sequence, documented on OEIS as A014258. Note that only the zeroth element in the sequence (`0`) will be printed if `n` is zero.

The sequence is generated by starting like the standard Fibonacci sequence, but after adding the two previous numbers, you flip the result and drop any leading zeros. An interesting fact, to me at least, is that this sequence is not strictly increasing (see the list below). It also seems to be (and probably is) strictly greater than or equal to the Fibonacci sequence.

Your program's input must be an integer.

The first 20 numbers of the sequence are provided here for your viewing pleasure:

```
0, 1, 1, 2, 3, 5, 8, 31, 93, 421, 415, 638, 3501, 9314, 51821, 53116, 739401, 715297, 8964541, 8389769

```

Standard loopholes are forbidden.

Shortest program wins.

EDIT: Added a note to clarify that the sequence starts with the zeroth element and should be included if `n` is zero.

### Example IO possibilities:

```
0    ->    0
1    ->    0 1
6    ->    0 1 1 2 3 5 8
17   ->    [0, 1, 1, 2, 3, 5, 8, 31, 93, 421, 415, 638, 3501, 9314, 51821, 53116, 739401, 715297]

```

Now that there are several answers, below are my implementations in Python 2 that I worked hard to hide with markup:

Iterative:

> ```
> #Closest to my initial program. 73 bytes. It should also be noted that this program
>  cannot reach a stack overflow. It runs for n=5000 in less than 10 seconds.
>
> i,a,b=input(),0,1
> print a
> while i:print b;i,a,b=i-1,b,int(str(a+b)[::-1])
> ```

Recursive:

> ```
> #Note that this prints n trailing newlines. 64 bytes.
>  Will hit a stack overflow error for large values of n.
>
> def f(n,i=0,j=1):print i,n and f(n-1,j,int(str(i+j)[::-1]))or'';
> ```

# Answer
> 3 votes
# Pyth, ~~17~~ ~~15~~ 14

```
Pu+Gs_`s>2GQU2

```

Try it online

Very basic implementation, starts with `range(2)` and adds a number of elements equal to the input, then ~~slices off the extras~~ pops off the last element.

Thanks @Jakube for pointing out the `>` reversal thingy.

### Explanation

```
Pu+Gs_`s>2GQU2    : Q = eval(input) (implicit)
P                 : all but the last element
 u         QU2    : reduce Q times starting with [0, 1]
  +G              : add to the previous result
       s>2G       : sum of the last two elements of G
    s_`           : int(reversed(repr(above value)))

```

# Answer
> 4 votes
## Python 2, 58 bytes

```
a=0;b=1
exec"print a;a,b=b,int(str(a+b)[::-1]);"*-~input()

```

Uses `str` to convert rather than backticks because large enough numbers in Python 2 are written with an L at the end. I tried a recursive function, but it turned out longer (61):

```
f=lambda n,a=0,b=1:-~n*[0]and[a]+f(n-1,b,int(str(a+b)[::-1]))

```

# Answer
> 3 votes
# K, ~~25~~ 23 bytes

```
{-1_ x{x,.|$+/-2#x}/!2}

```

A simple modification of one of the examples at No Stinking Loops.

The phrase `.|$` casts a number to a string, reverses it and then evaluates it.

## Edit:

Sloppy attention to boundary conditions on my part. More correct now:

```
  {-1_ x{x,.|$+/-2#x}/!2}'0 1 6 10
(,0
 0 1
 0 1 1 2 3 5 8
 0 1 1 2 3 5 8 31 93 421 415)

```

## Edit 2:

`(x+1)#` can be replaced with `-1_`, saving 2 characters. The space is necessary because otherwise `_x` would be an identifier, when I want the "drop" operator applied to a variable called `x`.

# Answer
> 3 votes
# Julia, 79 bytes

```
f=n->(t=[0,1];for i=2:n push!(t,t[i]+t[i-1]|>string|>reverse|>int)end;t[1:n+1])

```

This creates a function that accepts an integer as input and returns an integer array.

Ungolfed + explanation:

```
function f(n)
    # Start with the usual Fibonacci stuff
    t = [0,1]

    # Looooooooooooooop
    for i = 2:n
        # Compute the Iccanobif number by piping results
        iccanobif = t[i] + t[i-1] |> string |> reverse |> int

        # Jam it into t
        push!(t, iccanobif)
    end

    # Return the first n + 1
    t[1:n+1]
end

```

Examples:

```
julia> f(1)
2-element Array{Int64,1}:
 0
 1

julia> f(17)
18-element Array{Int64,1}:
      0
      1
      1
      2
      3
      5
      8
     31
     93
    421
    415
    638
   3501
   9314
  51821
  53116
 739401
 715297

```

# Answer
> 3 votes
# Haskell, ~~64~~ 49 bytes

```
a!b=a:b!(read$reverse$show$a+b)
q n=0:take n(1!1)

```

Usage example: `q 15` -\> `[0,1,1,2,3,5,8,31,93,421,415,638,3501,9314,51821,53116]`

How it works: `!` recursively builds an infinite list of iccanobif numbers starting with it's first argument (the second argument must be the next iccanobif number). `q` takes the first `n` numbers from the iccanobif list starting with `1, 1` and prepends a `0`.

# Answer
> 3 votes
# T-SQL, 149

Very straight forward inline table function that uses a recursive CTE query. As it is using INTs this will top out at 37. Adding in CASTs for bigints will allow it to go further to 63

```
create function i(@ int)returns table return with r as(select 0I,1N union all select n,reverse(i+n)+0from r)select 0n union all select top(@)n from r

```

It is used as follows

```
select * from i(0)
n
-----------
0

(1 row(s) affected)

select * from i(1)
n
-----------
0
1

(2 row(s) affected)

select * from i(6)
n
-----------
0
1
1
2
3
5
8

(7 row(s) affected)

select * from i(17)
n
-----------
0
1
1
2
3
5
8
31
93
415
421
638
3501
9314
51821
53116
715297
739401

(18 row(s) affected)

```

# Answer
> 2 votes
# CJam, 18 bytes

```
U1{_2$+sW%i}ri*;]p

```

**How it works**

```
U1                      e# First two numbers in the series
  {        }ri*         e# Run the loop input numbers times
   _2$+                 e# Get sum of last two numbers in the series
       sW%i             e# Convert to string, inverse and convert back to a number
                ;       e# Remove the last number to get only first n + 1 numbers.
                 ]p     e# Wrap all numbers in an array and print the array

```

Try it online here

# Answer
> 2 votes
# Java - ~~126~~ 124

I haven't seen Java around this site in awhile...

```
void f(int b){for(int c=0,d=1,g;b-->=0;d=Integer.valueOf(new StringBuilder(c+(c=d)+"").reverse()+""))System.out.println(c);}

```

`f(5)` prints `0 1 1 2 3 5 8 31 93 421 415 638`

# Answer
> 2 votes
# SWI-Prolog, ~~141~~ ~~131~~ 121 bytes

```
a(X,R):-X>1,A is X-1,a(A,B),reverse(B,[K,L|_]),W is K+L,name(W,Z),reverse(Z,Y),name(E,Y),nth0(X,R,E,B);X=1,R=[0,1];R=[0].

```

Running `a(17,X).` outputs:

```
[0, 1, 1, 2, 3, 5, 8, 31, 93, 421, 415, 638, 3501, 9314, 51821, 53116, 739401, 715297]

```

Takes about 10 seconds to output the result of `a(10000,X).` on my computer.

Edit: The 121 bytes version above is a one predicate definition = one liner. The old 131 bytes version is the following (must be runned as `p(17,X)`):

```
a(0,[0]).
a(1,[1,0]).
a(X,[E|B]):-A is X-1,a(A,B),B=[K,L|_],W is K+L,name(W,Z),reverse(Z,Y),name(E,Y).
p(X,Y):-a(X,Z),reverse(Z,Y).

```

# Answer
> 2 votes
## \>\<\> (Fish) ~~592~~ 254 Bytes

Not super golfed (42/43 blanks that do nothing and a total of 30 redirection tokens) , but was an interesting exercise getting it working in the first place.

```
10!/{:}0=?v/{1-}}:{+:0}!/a,:1%-:0=?!v~{:1!/$:@0=?!v$~}}:&{{&*\
/-$/    ;n/\oo", "n:    \       }+1{/     \$-1$*a /|.!20}}01@/
* :{:}(?v:{!":}-1!/$:@0=?!v$~{:}1!/$:@0=?!v$~}}}:&{{{&*:1%-*&{{&+}}{1+}02.
b .1 +bb   \      \$-1$*a /       \$-1$,a /
\*9{~~~{/

```

You can test it here, providing the desired length in the initial stack.

EDIT: More than halved byte count

# Answer
> 2 votes
# PHP, 114, 109 bytes

```
function f($n){if($n==0)return 0;$f=[0,1];for($i=2;$i<=$n;++$i){$f[$i]=strrev($f[$i-1]+$f[$i-2]);}return $f;}

```

Nothing fancy, just an average fibonacci algorithm with the string reverse magic.

Ungolfed:

```
function f($n)
{
    if($n == 0) return 0;
    $f = [0, 1];
    for ($i=2; $i<=$n; ++$i){
        $f[$i] = strrev($f[$i-1] + $f[$i-2]);
    }
    return $f;
}

```

# Answer
> 2 votes
# Husk, 10 bytes

```
↑¡ȯ↔Σ↑_2ŀ2

```

Try it online!

# Answer
> 1 votes
# JavaScript (ES2015), ~~81~~ 73 bytes

```
(a,b=0,c=1)=>{for(;a-->-1;c=[...(b+(b=+c)+"")].reverse().join``)alert(b)}

```

Running this function (named `f`) with `6`:

```
f(6);// alerts: 0, 1, 1, 2, 3, 5, 8

```

# Answer
> 1 votes
### Excel VBA, 279 bytes

```
n = InputBox("n")
For i = 0 To n
If i < 2 Then
Cells(i + 1, 1) = i
ElseIf i > 6 Then
x = Cells(i, 1) + Cells(i - 1, 1)
l = Len(x)
v = CStr(x)
For j = 1 To l
r = r + Right(v, 1)
v = Left(v, l - j)
Next j
Cells(i + 1, 1) = r
r = ""
Else
Cells(i + 1, 1) = Cells(i, 1) + Cells(i - 1, 1)
End If
Next i

```

Running the macro will prompt the user to enter a value for n.

The results will then be printed row by row in column A:

# Answer
> 1 votes
# Pip, 13 bytes

I'm pretty sure all the features used in this program were present in Pip before this question was asked.

```
LaSio:+RVi+oi

```

Takes input as command-line argument. Try it online!

### Explanation

```
               a is 1st cmdline arg; i is 0; o is 1 (implicit)
La             Loop (a) times:
       RVi+o   Reverse of i+o
      +        Unary + treats its operand as a number, thus removing leading 0's
    o:         Assign the result to o...
  Si           ... before swapping i and o
            i  After the loop, output i

```

The two variables' values evolve like so:

```
Iter   o   i (output)
   0   1   0
   1   0   1
   2   1   1
   3   1   2
   4   2   3
   5   3   5
   6   5   8
   7   8  31
   8  31  93
   9  93 421
  10 421 415

```

# Answer
> 1 votes
# Jelly, 7 bytes

```
+ṚḌɗÐ¡1

```

Try it online!

Reads `n` from STDIN

## How it works

```
+ṚḌɗÐ¡1 - Main link. No arguments
        - By default, set the left argument to 0
      1 - Set the right argument to 0
    Ð¡  - Read n from STDIN and do the following n times:
          Start with x = 0, y = 1, then update according to
          x, y = y, f(x,y), collecting each intermediate step
   ɗ    - Define f(x, y):
+       -   x + y
 Ṛ      -   Reversed digits
  Ḍ     -   Back to integer

```

# Answer
> 1 votes
# Vyxal `W`, ~~10~~ 9 bytes

```
01?(~+Ṙ)_

```

Try it Online!

-1 thanks to Steffan

Similar to the CJam answer.

```
01?(~+Ṙ)_ # 'W' flag prints the entire stack
01        # Push 0, then 1
  ?(   )  # Loop input number of times
    ~+    # Add the previous 2 numbers without popping
      Ṙ   # Reverse the result (given a number, the output will be a number)
        _ # Pop the last result

```

# Answer
> 1 votes
# , 87 bytes

```
function(n)while(n+1){n=n-1;show(+F);F=T+(T=F);F=F%/%10^(z=0:log10(F))%%10%*%10^rev(z)}

```

Try it online!

# Answer
> 0 votes
# Pushy, 18 bytes (non-competing)

```
Z1{:2d+vFs@KjkvF;_

```

**Try it online!**

It's not the most elegant of programs, but it works.

```
Z1     \ Push 0 and 1 to begin the sequence
{:     \ Input times do:
 2d+   \   Add the last two terms
 vF    \   Send to second stack
 s     \   Split into digits
 @Kjk  \   Reverse and join into one number
 vF;    \   Send back to first stack
_      \ At the end of the program, print the whole stack.

```

# Answer
> 0 votes
# Jelly, 9 bytes

```
0+ṚV$¥Ð¡1

```

Try it online!

# Answer
> 0 votes
# R, 134 bytes

```
i=function(n){s=c(0,1);for(i in 3:n){s[i]=as.numeric(paste0(rev(strsplit(as.character(s[i-2]+s[i-1]),'')[[1]]),collapse=''))};cat(s)}

```

Example:

```
> i(10)
0 1 1 2 3 5 8 31 93 421

```

Would love to see if somebody had a better R alternative than to take your number, make it a string, reverse it and turn it back into a number again.

# Answer
> 0 votes
# Groovy, 70 bytes

```
{r={"$it".reverse() as int};f={n->n<3?1:r(f(n-1))+r(f(n-2))};r(f(it))}

```

---

```
{
    r={"$it".reverse() as int};       // Reverse digits, costly using string.
    f={n->n<3?1:r(f(n-1))+r(f(n-2))}; // Recursive Iccanobbif implementation.
    r(f(it))                          // Reverse final output.
}

```

# Answer
> 0 votes
# Japt, 10 bytes

Outputs the `n`th element, 0-indexed.

```
@Zä+ Ìsw}g

```

Try it

---
Tags: code-golf, number, sequence, fibonacci
---


title: Draw an ASCII pencil

text:
# Question
Title: Draw an ASCII pencil
Task is pretty simple. Your program should take a number `N` from `1` to `20` and draw the following ASCII art.
When `N=1`:

```
_____
| | |
| | |
| | |
| | |
| | |
| | |
| | |
|_|_|
\   /
 \-/
  v

```

When `N=2`:

```
_______
|  |  |
|  |  |
|  |  |
|  |  |
|  |  |
|  |  |
|  |  |
|  |  |
|  |  |
|  |  |
|  |  |
|  |  |
|  |  |
|  |  |
|  |  |
|__|__|
\     /
 \---/
  \ /
   v

```

When `N=3`:

```
_________
|   |   |
|   |   |
|   |   |
|   |   |
|   |   |
|   |   |
|   |   |
|   |   |
|   |   |
|   |   |
|   |   |
|   |   |
|   |   |
|   |   |
|   |   |
|   |   |
|   |   |
|   |   |
|   |   |
|   |   |
|   |   |
|   |   |
|   |   |
|___|___|
\       /
 \-----/
  \   /
   \ /
    v

```

And etc. Trailing spaces are allowed.

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

# Answer
# Charcoal, 30 bytes

```
Ｎθ×_θ↑×⁸θ←×_⊕θ↓_↓×⁸θ↘¹Ｐ⊕θ↘θv‖Ｂ

```

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

```
Ｎθ

```

Input `n`.

```
×_θ

```

Print the `n` `_`s near the bottom left of the pencil.

```
↑×⁸θ

```

Print the `3n` `|`s up the middle of the pencil.

```
←×_⊕θ↓_

```

Print the left half of the `_`s at the top of the pencil.

```
↓×⁸θ

```

Print the left `3n` `|`s of the pencil.

```
↘¹

```

Print the first `\` at the bottom left of the pencil.

```
Ｐ⊕θ

```

Print the left half of the `-`s near the bottom of the pencil without moving the cursor.

```
↘θ

```

Print the rest of the `\`s at the bottom left of the pencil.

```
v

```

Print the `v` at the bottom of the pencil.

```
‖Ｂ

```

Reflect to complete the pencil.
> 6 votes

# Answer
# Zsh, 175 bytes

```
x=\|${(l:n=$1:)}
x+=$x\|
<<<${x//?/_}
repeat n\*8-1 <<<$x
<<<${x// /_}
q=\\${(l:n*2+1:)}/
<<<$q
q=${q// /-}
repeat n q=${${q/?\///}/\\?/ \\}&&<<<$q&&q=${q//-/ }
<<<${q/\\*/ v}
```

Attempt This Online!

30 bytes spent on the line on the tip :(
Attempt This Online!
> 5 votes

# Answer
# 05AB1E, 44 bytes

```
Ì'_×'|IúRĆI8*.Dð'_:'\I>úRηRεNið'-:]`\'v).º.c

```

Try it online or verify all test cases.

**Explanation:**

```
Ì         # Increase the (implicit) input by 2
 '_×     '# Push a string with that many amount of "_"
'|       '# Push "|"
  Iú      # Pad it with the input amount of leading spaces
    R     # Reverse the string, so the spaces are trailing
     Ć    # Enclose; append its own head "|"
I8*       # Push the input, and multiply it by 8
   .D     # Duplicate the string that many times on the stack
ð'_:     '# On the top copy, replace all spaces with "_"
'\       '# Push "\"
  I>ú     # Pad it with the input+1 amount of leading spaces
     R    # Reverse the string, so the spaces are trailing
      η   # Pop and push a list of its prefixes
       R  # Reverse this list of prefixes
 ε        # Map over each string:
  Ni      #  If the 0-based map-index is 1 (so the second string):
    ð'-: '#   Replace all spaces with "-"
 ]        # Close both the if-statement and map
  `       # Pop and push all values separated to the stack
   \      # Discard the top copy (the loose "\")
    'v   '# Push a "v" instead
)         # Wrap all strings on the stack into a list
 .º       # Mirror each line with overlapping center
   .c     # Pad leading spaces to centralize everything, and join by newlines
          # (after which the result is output implicitly)

```
> 5 votes

# Answer
# brainfuck, 573 bytes

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

```

Try it online!

Hi, this is my first doing code-golf challenge. yeah, I think it can be shorter if It has a better variable position arrangement and better ways of creating "\_", "|", " ", "/", "", "-", "v", "\n", but I think I will try to figure it out later.
> 5 votes

# Answer
# Vyxal, 89 bytes

```
d3+\-*,λ\|?n*J\|Jʁ,;→8*‹(ð←†)\-←†\\?d›IJ\/J,ð\\J?d‹\-*J\/J,?‹(n›I\\J?nd-?‹+IJ\/J,)?›I\vJ,

```

Try it Online!

## Explanation

```
d3+\-*,    Print 2n + 3 dashes

λ                Lambda to print:
 \|              Pipe joined with
   ?n*J;         A string (arg) n times joined with
        \|J      Another pipe
            ʁ,→  Palindromised (and set lambda to anon. var)

8*‹(ð←†)         Loop 8*n - 1 times, call the lambda passing a space as arg
\-←†             Call same lambda with dash as arg
\\?d›IJ\/J,      Print \, n*2+1 spaces, and /
ð\\J?d‹\-*J\/J,  Print space, \, n*2-1 dashes, and /

?‹(n›I\\J?nd-?‹+IJ\/J,)    Loop through n-1 with loop index i
   n›I\\J                  Pad n+1 spaces and /
         ?nd-?‹+IJ         Append i-n*2+i-1 spaces
                  \/J,     Append \/ and print

?›I\vJ,                    Print v padded with n+1 spaces

```
> 4 votes

# Answer
# Ruby, ~~127~~ 110 bytes

```
->n{puts ?_*(n*2+3),(-8*n..n).map{|i|a=i*i<2?" -_"[i]:S=" ";i<0?[?|]*3*a*=n:S*i+?\\+a*(n-i<<1|1)+?/},S*-~n+?v}

```

Try it online!
> 4 votes

# Answer
# JavaScript (Node.js), ~~304 bytes~~ 296 bytes

```
x=n=>{p="repeat",u=1,h="\\",o=["|","|","|"],r=o.join(" "[p](n))+"\n",s=o.join("_"[p](n)),e=["-"[p](2*n+3)];for(e.push(r[p](8*n-1)+s),e.push([h,"/"].join(" "[p](2*n+1))),e.push(" "+h+"-"[p](2*n-1)+"/");u<n;)e.push(" "[p](1+u)+h+" "[p](2*n-2*u++-1)+"/");return e.push(" "[p](n+1)+"V"),e.join("\n")}

```

Try it online!

This is my first try at code golfing so it's a very simplistic attempt. The long version would be:

```
var x=(n) => {
  // Set some utility variables
  let i = 1
  let space = ' '
  let backslash = '\\'
  let repeat = 'repeat'
  let pipes = ['|', '|', '|']
  let segment = pipes.join(space[repeat](n)) + '\n'
  let lastsegment = pipes.join("_"[repeat](n))

  // Create the first line of dashes, the body with the last segment and the first line of the tip
  let pencil = ["-"[repeat](n * 2 + 3), segment[repeat](8 * n - 1) + lastsegment, [backslash, "/"].join(space[repeat](n * 2 + 1))]

  // Create the dashed tip line and the rest of the empty tip in a loop
  for(pencil.push(space+backslash+"-"[repeat](2*n-1)+"/");i<n;){
    pencil.push(space[repeat](1+i)+backslash+space[repeat](2*n-2*i++-1)+"/")
  }

  // Add the tip, join the array and return
  pencil.push(space[repeat](n + 1) + "V")
  return pencil.join("\n")
}

```
> 3 votes

# Answer
# C (gcc), 211 bytes

```
#define F(N,I)for(I=N;I>0;I--)
#define P(C)putchar(C);
i,j;main(c,v){F(2*c+3,i)P(95)P(10)F(8*c,i){F(2,v){P('|')F(c,j)P(i<2?95:32)}P('|')P(10)}F(c+1,i){P(92)F(2*i-1,j)P(i^c?32:45)P(47)P(10)F(c-i+2,j)P(32)}P('v')}

```

Try it online!

This is my first time code golfing.

The number of arguments is used as the input, though the value of those arguments is irrelevant. In the example on Try it online, 2 additional arguments are passed (in addition to the program name itself) so here, n=3.

The main obfuscations used are

* define macros for printing characters and for loops
* replacing character literals with their decimal encoding (where it saved characters)
* the use of `main()`'s argument variables for temporary storage
* and, naturally, the removal of white-space.

I decided to have all `for` loops run backwards as it ends up using slightly fewer symbols overall due to the loop used for aligning the tip of the pencil.
> 3 votes

# Answer
# Python 3.8 (pre-release), 155 bytes

```
lambda n:'_'*(2*n+3)+f'\n|{(" "*n+"|")*2}'*(8*n-1)+f'\n|{("_"*n+"|")*2}\n'+'\n'.join(' '*i+('v'*(i>n)or f'\\{" -"[i==1]*(2*n-2*i+1)}/')for i in range(n+2))

```

Try it online!

Sorry... can't shorten no more.
> 2 votes

# Answer
# PowerShell, 134 bytes

inspired by Zaelin Goodman.

```
param($n),'__'+,'| '*(8*$n-1)+'|_'|%{,$_[0]*3-join("$($_[1])"*$n)}
0..$n|%{' '*$_+"\$((' ','-')[$_-eq1]*(2*$n+1-2*$_))/"}
' '*++$n+'v'

```

Try it online!
> 2 votes

# Answer
# JavaScript (ES6), 143 bytes

```
n=>'_'[R='repeat'](w=n*2+3)+(g=x=>x<0?`
|${s=' _'[+!++x][R](n)}|${s}|`+g(x):`
`+' '[R](x)+(x>n?'v':`\\${' -'[+!~-x][R](w-++x*2)}/`+g(x)))(-8*n)

```

Try it online!
> 2 votes

# Answer
# C++ (gcc), ~~252~~ ~~245~~ 241 bytes

```
#import<iostream>
#define g(i,n)for(int i=0;i<n;++i)
#define c std::cout<<
int f(int n){g(i,2*n+3)c'_';c'\n';g(i,8*n){g(j,2){c'|';g(k,n)c" _"[i==8*n-1];}c"|\n";}g(i,n+2){g(j,i)c' ';if(i+~n){c'\\';g(j,n-~n-i-i)c" -"[i==1];c"/\n";}else c'v';}}

```

Try it online!

* *7 bytes saved thanks to ceilingcat*
* *4 bytes saved thanks to ceilingcat*
> 2 votes

# Answer
# PowerShell (Version \<=6), 139 bytes

```
param($n)'_'*(2*$n+3)
,($b=('|'+' '*$n)*2+'|')*(8*$n-1)
$b|% *ce ' '"_"
0..$n|%{' '*$_+"\$((' ','-')[$_-eq1]*(2*$n+1-2*$_))/"}
' '*++$n+'v'

```

Try it online!

# PowerShell (Version \>=7), 140 bytes

```
param($n)'_'*(2*$n+3)
,($b=('|'+' '*$n)*2+'|')*(8*$n-1)
$b|% *ace ' '"_"
0..$n|%{' '*$_+"\$((' ','-')[$_-eq1]*(2*$n+1-2*$_))/"}
' '*++$n+'v'

```

Try it online!
> 1 votes

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

```
n=>[(g=([[f,...d]])=>d.join((r=(n,c=' ')=>c.repeat(n+!~n))(n,f)))`____`,r(8*n-1,g` |||
`)+g`_|||`,g` \\ /`,(i=0,G=([[b,e,f]])=>r(++i)+b+r(2*(n-i)+1,f)+e)`\\/-`,...Array(n-1).fill`\\/`.map(G),G`v `].join`
`

```

Try it online!

The core of this solution lies in the ~~ab~~use of template parameters and tags in some internal functions:

* `r(n,c)` is just `c.repeat(n)`, except `n` changes to `0` if it's `-1`, and `c` defaults to a space.
* `g([[f,...d]])` joins `d` with `r(n,f)`.
* `G([[b,e,f]])` is similar to `g` but adds increasing padding on each iteration (for the pencil tip).

ES6 destructuring in function parameters allows for the use of template strings in place of comma separated character arguments, like this:

```
const f1 = (a,b,c) => [c,b+a];
const f2 = ([[a,b,c]]) => [c,b+a];
console.log(f1('a','b','c')) // -> ['c', 'ba']
console.log(f2`abc`)         // -> ['c', 'ba']

```
> 1 votes

# Answer
# Vyxal, ~~40~~ 37 bytes

```
⇧\_*\|?꘍Ǐ?8*Ḋ\_Ḟ\\?›꘍¦Ṙ1‡\-Ḟ¨M÷_\vWøṗ

```

Try it Online!

## How?

```
⇧\_*\|?꘍Ǐ?8*Ḋ\_Ḟ\\?›꘍¦Ṙ1w‡\-Ḟ¨M÷_\vWøṗ
⇧                                       # Push input + 2
 \_*                                    # Push that many underscores
    \|                                  # Push "|"
      ?꘍                                # Append the input amount of spaces
        Ǐ                               # Append its own head, aka "|"
         ?8*                            # Push input * 8
            Ḋ                           # Duplicate the string that many times
             \_Ḟ                        # On the top string, replace all spaces with "_"
                \\                      # Push a backslash
                  ?›꘍                   # Append input+1 spaces
                     ¦                  # Pop and push its prefixes
                      Ṙ                 # Reverse
                       1‡\-Ḟ¨M          # On the second string, replace all spaces with a hyphen
                              ÷_        # Push each item of that to the stack, and discard the top one (a backslash)
                                \v      # Push "v"
                                  W     # Wrap everything on the stack into a list
                                   øṗ   # Palindromise everything, center, and join by newlines

```

*-2 bytes thanks to emanresu A*
> 1 votes

# Answer
# Perl 5 \+ `-M5.10.0 -n`, 127 bytes

```
//;say for"_"x($'*2+3),($_=join$"x$_,qw(|)x3)x(8*$'-1),y/ /_/r,(map$"x$_.v92.($_-1?$":'-')x(2*($'-$_)+1)."/",0..$')
,$"x$'." v"
```

Try it online!
> 1 votes

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


title: Bake a slice of Pi

text:
# Question
Title: Bake a slice of Pi
Write a program or function that prints or outputs this exact text (consisting of 142 characters):

```
()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
 \::\433832|
  \::\79502|
   \::\8841|
    \::\971|
     \::\69|
      \::\3|
       \__\|

```

Your program must take no input (except in languages where this is impossible, such as `sed`), and produce the above text (and *only* the above text) as output. A trailing newline is acceptable.

This is , so the shortest answer (in bytes) wins.

# Answer
# MATL, ~~70~~ ~~68~~ 67 bytes

```
'()'12:)l10:&<toYP43Y$51hb(!10Xy'\::\'FFhZ++'|'3$Yc'||\'3:(95'Zd'o(

```

Try it online!

### Explanation

What a mess. But hey, there's a convolution!

The explanation will be clearer if you can *inspect the stack contents after a given statement*. To do it, just insert `X#0$%` at that point. (This means: `X#` show stack contents, `0$` don't implicitly display anything else, `%` comment out rest of the code). For example, see the stack right after the convolution.

```
'()'       % Push this string
12:        % Range [1 2 ... 12]
)          % Index into string (modular, 1-based): gives '()()()()()()'
l          % Push 1 (will be used later)
10:        % Range [1 2 ... 10]
&<         % All pairwise "less than" comparisons. Gives matrix with "true"
           % below the main diagonal, and the remining entries equal to "false"
to         % Duplicate. Convert to numbers (true becomes 1, false becomes 0)
YP43Y$     % Compute pi with 43 significant digits (42 decimals). Gives a string
51h        % Append last decimal, '3' (ASCII 51). This is needed to avoid rounding
b          % Bubble up the true-false matrix, to be used as logical index
(          % Fill the chars from the pi string into the 0-1 matrix, at the positions
           % indicated by the true-false matrix. Thus each 1 is replaced by a char
           % from the pi string. Entries that were 0 remain as 0. This is done in
           % columm-major order...
!          % ...so transpose to make it row-major
10Xy       % Identity matrix of size 10
'\::\'     % Push this string...
FFh        % ...and append two zeros
Z+         % 2D convolution keeping size. The identity matrix convolved with the
           % above string gives the diagonal bands with chars '\'  and ':'
+          % Add to the matrix containing the digits of pi. At each entry, only one
           % of the two matrices is nonzero
'|'        % Push this string
3$Yc       % Three-input string concatenation. This prepends the 1 (which was pushed
           % a while ago) and appends '|' to each row of the matrix. This converts
           % the matrix to char. Note that char 1 will be displayed as a space. We
           % used char 1 and not char 0 (which would be displayed as a space too)
           % because function `Yc` (`strcat`) strips  off trailing space from the
           % inputs, counting char 0 as space, but not char 1
'||\'      % Push this string
3:(        % Assign it to the first 3 entries of the matrix (column-major), that is,
           % to the top of the first column
95         % Push ASCII for '_'
'Zd'o      % Push string 'Zd' and convert to numbers: gives [90 100]. These are the
           % (column-major) indices where the '_' char should appear in the last row
(          % Fill those chars
           % Implicitly display. (Chars 0 and 1 are displayed as space)

```
> 97 votes

# Answer
# Perl, 93 bytes

```
$_=bpi$=;printf'()'x6x!$`.'
%12s',F.ee x!$\--^substr"\32::\\$&|",-12while/.{$\}/g

```

Requires the command line option `-l71Mbignum=bpi`, counted as 14. The `\32` should be replaced by a literal character 26.

**Sample Usage**

```
$ perl -l71Mbignum=bpi pi-slice.pl
()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
 \::\433832|
  \::\79502|
   \::\8841|
    \::\971|
     \::\69|
      \::\3|
       \__\|

```

---

### Perl, 111 bytes

```
$_=bpi$_*($l=($.=$_)-3);printf'()'x($./2)x!$`."
%$.s",F.ee x!$l--^substr"\32::\\$&|",-$.while/.{$l}/g

```

Parameterized version. Requires the command line option `-nMbignum=bpi`, counted as 12.

**Sample Usage**

```
$ echo 10 | perl -nMbignum=bpi pi-slice.pl
()()()()()
|\3.14159|
|:\265358|
\::\97932|
 \::\3846|
  \::\264|
   \::\33|
    \::\8|
     \__\|

$ echo 20 | perl -nMbignum=bpi pi-slice.pl
()()()()()()()()()()
|\3.141592653589793|
|:\2384626433832795|
\::\028841971693993|
 \::\75105820974944|
  \::\5923078164062|
   \::\862089986280|
    \::\34825342117|
     \::\0679821480|
      \::\865132823|
       \::\06647093|
        \::\8446095|
         \::\505822|
          \::\31725|
           \::\3594|
            \::\081|
             \::\28|
              \::\4|
               \__\|

```
> 39 votes

# Answer
## JavaScript (ES6), ~~187~~ 174 bytes

This is *1 byte shorter* than just displaying the plain text.

```
for(y=n=0,s=`()()()()()()
`;y<10;y++,s+=`|
`)for(x=-2;x++<9;)s+=x>y?(Math.PI+'2384626433832795028841971693')[n++]:`\\${y>8?'__':x+1|y>2?'::':'||'}\\`[y-x]||' ';console.log(s)
```
> 24 votes

# Answer
# ///, ~~129~~ 127 bytes

```
/-/\\\\//&/--::--//%/  //#/|
%//!/()()/!!!
|-3.1415926|
|:-53589793|
&2384626|
 &433832#&79502# &8841#%&971#% &69#%%&3#%% -__-|

```

Try it online!
> 17 votes

# Answer
# Python 2, 131 bytes

```
print'()'*6+'\n|\\3.1415926|\n|:\\53589793|'
for n in 2384626,433832,79502,8841,971,69,3,'':print'%11s|'%('\%s'*2%('_:'[n<'']*2,n))

```

Joint effort between Sp3000 and Lynn. Copper saved a byte, too! Ideone link.
> 17 votes

# Answer
# Bash, 153 bytes

```
cat << _
()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
 \::\433832|
  \::\79502|
   \::\8841|
    \::\971|
     \::\69|
      \::\3|
       \__\|
_

```
> 12 votes

# Answer
## Batch, 195 bytes

```
@echo ()()()()()()
@echo ^|\3.1415926^|
@echo ^|:\53589793^|
@set i=\
@for %%d in (2384626 433832 79502 8841 971 69 3)do @call:l %%d
@echo %i%__\^|
@exit/b
:l
@set i= %i%
@echo%i%::\%1^|

```
> 9 votes

# Answer
# Turtlèd, ~~135~~ 129 bytes

(the interpreter isn't really  ~~slightly~~ buggèd (anymore :\])~~, but it does not affect this program~~)

By restructuring and rewriting my program, I golfed... six bytes

And now I have to make new explanation...

Still could be shorter probs though

---

At least the best solution in this lang isn't just writing in the raw data ¯\*(ツ)*

---

```
#3.141592653589793238462643383279502884197169#")()()()()()">10:[)'|l]:[)d'\l]d"(||"2uuu[|;"::"uuu];>"__"[|r'\d]dl[ l[|.+l][\r]ul]

```

## **Try it online** Explanation

Honestly, this doesn't describe the actual program very well, but it does give hints about the commands, so you might understand a little better

```
#3.141592653589793238462643383279502884197169# Some pi. Set the string to thing between #s
                                               the last digit was same as first, and the
                                               string wraps, so digit could be removed
")()()()()()"  Write this string, by writing char 1 to current cell, moving right, char 2...

>              turn right

10             set register to ten

:[)'|l]:       move right by amount in register, while current cell isn't ), write |
               and move left. move right by amount in register

[)d'\l]        while cell is not (, move down, write \, move left

d"(||"         move down and string-write "(||"

2              set register to 2

uuu[|;"::"uuu] Move up three, and while the cell is not |, move down by
               register (2), string-write "::", move up three

               Just remember the turtle is currently pointing right, so up is right.

;>"__"         move down by amount in register, turn right, string-write "__"

[|r'\d]dl      while cell is not |{ move right, write \, move down}, move down, left

```

### COMPLEX THING: NESTED LOOPS

```
[ l[|.+l][\r]ul]

```

While the current cell is not space {move left, execute loop:(While cell not |, write current char of string variable (remember that pi?), increment string pointer, move left), execute loop:(while cell not \\, move right), move up, left}
> 5 votes

# Answer
# Fourier, ~~196~~ 190 bytes

***New feature alert!***

## Code

```
|SaCaaSa|f|~Y0~jY(32aj^~j)|w6(40a41ai^~i)10a~N124a~W92a~S3o46a1415926oWaNaWa58a~CSa53589793oWaNaf2384626oWaNa1wf433832oWaNa2wf79502oWaNa3wf8841oWaNa4wf971oWaNa5wf69oWaNa6wf3oWaNa7wSa95aaSaWa

```

## Explanation

This program is my first demonstration of functions in Fourier:

Functions are defined like so:

```
|code goes here|f

```

The first pipe starts the function declaration. You then put the code in between the pipes. The last pipe ends the function declaration. Finally, the `f` is the variable in which the function is stored. This can be any character, as long as it isn't a reserved function.

For example, in my code, one of the function s is:

```
|SaCaaSa|f

```

Where the variable `S` stores the number 92 and `C` stores the number 58.

When called, the function outputs the following:

```
\::\

```

Since it is the most repeated thing in the pie.

Similarly, to golf down the output, I have used a loop:

```
6(40a41ai^~i)

```

Which repeats the code `40a41a` 6 times. `40a41a` on its own outputs:

```
()

```

So repeating the code six times outputs:

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

```

Thereby outputting the crust of the pie.

**Try it on FourIDE!**

Because I haven't implemented functions in the Python interpreter, this program will not work on http://tryitonline.net
> 5 votes

# Answer
# Pyth, 89 bytes

```
J_2K+.n0."09\07´\C2\84J\01£\07Nl:?í"*"()"6Vr9Zp*dJp?!Z\|?qZ9"|:""\::"p\\p:KZ+ZN\|=+ZN=hJ)p*dJ"\__\|"

```

Try it online!

Replace `\xx` (hexadecimal) with the corresponding ASCII character if you copy/paste the code from this answer; it contains unprintable characters in the packed string which SE filters out.

### Explanation

```
J_2        Sets J to -2
  .n0      Pi; returns 3.141592653589793
  ."(...)" Packed string; returns "2384626433832795028841971693"
 +         Concatenation; returns "3.1415926535897932384626433832795028841971693"
K          Sets K to that string
*"()"6     Repetition; returns "()()()()()()", which is implicitly printed with a newline
 r9Z       Range; returns [9, 8, 7, 6, 5, 4, 3, 2, 1] (Z is initialized to 0)
V          Loop through r9Z, using N as the loop variable
  *dJ      Repetition; d is initialized to " " (returns an empty string if J <= 0)
 p         Print without a newline
  ?!Z      Ternary; if not Z
   \|      then return "|"
   ?qZ9    else, ternary; if Z == 9
    "|:"   then return "|:"
    "\::"  else, return "\::"
 p         Print without a newline
  \\       One-character string; returns "\"
 p         Print without a newline
  :KZ+ZN   Slice; returns K[Z:Z+N], not including K[Z+N]
 p         Print without a newline
 \|        One-character string; returns "|", which is implicitly printed with a newline.
 =+ZN      Adds N to Z
 =hJ       Increments J by 1
)          Ends loop
 *dJ       Repetition; d is initialized to " "
p          Print without a newline
"\__\|"    Returns "\__\|", which is implicitly printed with a newline

```
> 4 votes

# Answer
# Jelly, 83 bytes

surely still quite golfabale

```
7Ḷ⁶ẋ;€“\::\”“|:\”ṭṙ7
⁾()ẋ6⁷⁾|\8ØPæp”|⁷8RUR€µ“⁾ḅ|Za"~ṅỵþȷ^ṇ⁷Ċ’Dṁ;€”|ż@¢Y⁷ø⁶ẋ7“\__\|”

```

**TryItOnline**

How?

```
7Ḷ⁶ẋ;€“\::\”“|:\”ṭṙ7 - Link 1, left side padding and filling
7Ḷ                   - lowered range of 7 ([0,1,2,3,4,5,6])
      “\::\”         - filling ("\::\")
  ⁶ẋ;€               - space character repeated that many times and concatenate for each
            “|:\”    - top crust edge filling ("|:\")
                 ṭ   - tack (append to the end)
                  ṙ7 - rotate to the left by 7 (move top crust filling to the top)

⁾()ẋ6⁷⁾|\8ØPæp”|⁷8RUR€µ - Main Link (divided into two for formatting)
⁾()ẋ6⁷                  - "()" repeated 6 times and a line feed
      ⁾|\               - "|\"
          ØP            - pi
         8  æp          - round to 8 significant figures (top edge of the glaze)
              ”|⁷       - "|" and a line feed
                 8R     - range of 8 ([1,2,3,4,5,6,7,8])
                   U    - reverse ([8,7,6,5,4,3,2,1])
                    R€  - range for each ([[1,2,..8],[1,2,..7],...,[1,2],[1]])
                      µ - monadic chain separation

“⁾ḅ|Za"~ṅỵþȷ^ṇ⁷Ċ’Dṁ;€”|ż@¢Y⁷ø⁶ẋ7“\__\|” - Main link (continued)
“⁾ḅ|Za"~ṅỵþȷ^ṇ⁷Ċ’                       - base 250 representation of the rest of the digits
                 D                      - decimalise (makes it a list)
                  ṁ                     - mould (into the shape of the array formed above)
                     ”|                 - "|"
                   ;€                   - concatenate for each
                         ¢              - call last link (1) as a nilad
                       ż@               - zip (with reversed operands)
                          Y⁷            - join with line feeds, and another line feed
                            ø           - niladic chain separation
                             ⁶ẋ7        - space character repeated 7 times
                                “\__\|” - "\__\|" the very bottom of the pie wedge

```
> 4 votes

# Answer
# PowerShell, 105 bytes

```
'()'*6
'|\3.1415926|
|:\53589793|'
2384626,433832,79502,8841,971,69,3|%{" "*$i+++"\::\$_|"}
' '*7+'\__\|'

```

Try it online!

*Not sure how I never answered this challenge ... I upvoted it and several of the other answers. Oh well, better late than never?*

This puts six balanced parens as a string on the pipeline, then a literal string (saves two bytes) of the next two rows. Then, we loop through the rest of the numbers, each iteration incrementing the number of prepended spaces (`$i`) concatenated with `\::<number>|`. Finally, we create a string of the tip of the pie. Those strings are all left on the pipeline, and an implicit `Write-Output` sticks a newline between.

This is 39 bytes shorter than just printing the pie.
> 4 votes

# Answer
# Python 2, ~~193~~ 176 bytes

```
P="3.1415926 53589793 2384626 433832 79502 8841 971 69 3".split()
f="()"*6+"\n|\%s|\n|:\%s|\n"%(P[0],P[1])
for s in range(7):f+=" "*s+"\::\\"+P[s+2]+"|\n"
print f+" "*7+"\__\|"

```

Or a shorter, more boring answer:

```
print r"""()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
 \::\433832|
  \::\79502|
   \::\8841|
    \::\971|
     \::\69|
      \::\3|
       \__\|"""

```
> 3 votes

# Answer
# C# 220 213 209 208 202 201 (171\*) Bytes

\*I find this to be unoriginal and cheating

```
void F()=>Console.Write(@"()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
 \::\433832|
  \::\79502|
   \::\8841|
    \::\971|
     \::\69|
      \::\3|
       \__\|");

```

201 Bytes:

```
void f(){var s="()()()()()()\n";for(int i=0;i<9;)s+=(i<1?"|":i<2?"|:":"\\::".PadLeft(i+1))+$"\\{new[]{3.1415926,53589793,2384626,433832,79502,8841,971,69,3}[i++]}|\n";Console.Write(s+@"       \__\|");}

```

220 bytes:

I'm sure that there is something to be golfed here

```
void f(){string s="()()()()()()\n",x="       ";for(int i=9,j=0;i>0;j+=i--)s+=(i>7?"|"+(i<9?":":"")+"\\":x.Substring(i)+@"\::\")+$"{Math.PI}32384626433832795028841971693".Substring(j,i)+"|\n";Console.Write(s+x+@"\__\|");}

```
> 3 votes

# Answer
# Ruby, ~~140~~ ~~138~~ 137 bytes

My solution to this problem in ruby, this is my first code golf answer :D

```
[0,2384626,433832,79502,8841,971,69,3,1].map{|n|puts n<1?"()"*6+"\n|\\3.1415926|\n|:\\53589793|":"\\#{n>1?"::\\#{n}":"__\\"}|".rjust(12)}

```

**Readable version and explanation:**

```
for n in [-1,2384626,433832,79502,8841,971,69,3,0]
  if n < 0 # n == -1
    puts "()"*6+"\n|\\3.1415926|\n|:\\53589793|"
  else
    if n > 0 # digits of pi
      puts "\\::\\#{n}|".rjust(12)
    else # edge of pie
      puts "\\__\\|".rjust(12)
    end
  end
end

```

Nothing really clever, just using some simple loops :)

**Output:**

```
()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
 \::\433832|
  \::\79502|
   \::\8841|
    \::\971|
     \::\69|
      \::\3|
       \__\|

```
> 3 votes

# Answer
# Charcoal, 31 bytes

```
×⁶()↙↓¹⁰↖↖¹⁰↓↓²↘⁸Ｍ↑__↖←¤:↗¤ＵＧPi

```

Try it online!

You may be wondering: what is this sorcery? How can you fill with `ＵＧPi`? Well, Charcoal is starting to get Wolfram Language support, in the hope that one day it can be competitive in more challenges!

## Previous, 71 bytes

```
×⁶()↙↓¹⁰↖↖¹⁰↓↓²↘⁸Ｍ↑__↖←¤:↗¤3.141592653589793238462643383279502884197169

```

Try it online!

## Verbose

```
Print(Multiply(6, "()"));
Move(:DownLeft)
Print(:Down, 10)
Move(:UpLeft)
Print(:UpLeft, 10)
Move(:Down)
Print(:Down, 2)
Print(:DownRight, 8)
Move(:Up)
Print("__")
Move(:UpLeft)
Move(:Left)
Fill(":")
Move(:UpRight)
Fill("3.141592653589793238462643383279502884197169")

```

Note that this is different as the deverbosifier automatically compresses strings and does not remove redundant commands.

## With compressed strings, 52 bytes

```
×⁶¦()↙↓¹⁰↖↖¹⁰↓↓²↘⁸↑__↖←¤:Ｍ↗¤”i¶∧²uτ¶R›    §Ｑ´⌈#_⮌ＰOÞ”

```

## xxd output

```
0000000: aab6 ba28 291f 14b1 b01c 1cb1 b014 14b2  ...()...........
0000010: 1eb8 125f 5f1c 11ef 3acd 1def 0469 0a01  ...__...:....i..
0000020: b275 f40a 52be 0999 9fa4 d1e0 1a23 5f86  .u..R........#_.
0000030: d04f de04                                .O..

```

Try it online!
> 3 votes

# Answer
# PHP, 170 bytes

no arbritrary precision Pi in PHP? Calculating takes much more space than Copy&Paste. Doesn´t matter that the last digit here is cut, not rounded; but in 64 bit Pi the last digit gets rounded up.

```
for(;$i<11;)echo str_pad($i?["\\__\\","|\\","|:\\","\\::\\"][$i>9?0:min(3,$i)].[3.1415926,53589793,2384626,433832,79502,8841,971,69,3][$i-1]."|
":"
",13,$i++?" ":"()",0);

```

Run with `php -r '<code>'`

**uncommented breakdown**

```
for(;$i<11;)
    echo str_pad($i?
         ["\\__\\","|\\","|:\\","\\::\\"][$i>9?0:min(3,$i)]
        .[3.1415926,53589793,2384626,433832,79502,8841,971,69,3][$i-1]
        ."|\n"
    :"\n"
    ,13,$i++?" ":"()",0);

```
> 2 votes

# Answer
# Python 2, ~~183~~ 171 bytes

```
p,d=[2384626,433832,79502,8841,971,69,3],"|\n"
c=("()"*6)+d[1]+"|\\"+`3.1415926`+d+"|:\\"+`53589793`+d
for x in range(7):c+=" "*x+"\\::\\"+`p[x]`+d
print c+" "*7+"\\__\\|"

```

Does't really do anything clever. Just builds up a big string then prints it out.

**EDIT**

Reduced to 171 after reading @Lynn's answer and learning. Sorry if it is wrong to (shamelessly) steal some bytes from you without you suggesting it. Please tell me if so and I will roll back the change.

**Output**

```
python pi.pie.py

()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
 \::\433832|
  \::\79502|
   \::\8841|
    \::\971|
     \::\69|
      \::\3|
       \__\|

```
> 2 votes

# Answer
# Stax, 63 bytes

```
ü?½Pi<Θ*q}ü¿▒5Ç>cdƒ±<Gw►,─ô╟▒g•iâÑ♠514Φ⌂!Ñεùáèè♂ÑD╔«dÿ47¡ô#UV•╧

```

Run and debug online!

Shorter than the accepted MATL answer. It would definitely be shorter if more digits were stored as the constant pi in Stax.

(What is that `Pi<0` in the code?)

## Explanation

Uses the ASCII equivalent to explain, which is

```
.()6*PVP$2ME.|\a+"|:\"a+"!RNyb2L$-!mV=223w+&O-"!{"\::\"s$+mELr"\__\"]+|>m'|+

```

Expalantion:

```
.()6*PVP$2ME.|\a+"|:\"a+
.()                           "()"
   6*P                        Print 6 times
      VP$                     First two lines of pi in the output
         2ME                  Push the two lines separately on the stack
            .|\a+             Prepend the first line with "|\"
                 "|:\"a+      Prepend the second line with "|:\"

"..."!{"\::\"s$+mELr"\__\"]+|>m'|+
"..."!                                [2384626,433832,79502,8841,971,69,3]
      {"\::\"s$+m                     Convert each element to a string and prepend "\::\"
                 ELr                  Prepend the first two lines to array
                    "\__\"]+          Append "\__\" to the converted array
                            |>        Right align text
                              m'|+    Append "|" to each array element and print

```
> 2 votes

# Answer
# Java 7, ~~260~~ ~~236~~ 191 bytes

```
String d(){return"()()()()()()\n|\\3.1415926|\n|:\\53589793|\n\\::\\2384626|\n \\::\\433832|\n  \\::\\79502|\n   \\::\\8841|\n    \\::\\971|\n     \\::\\69|\n      \\::\\3|\n       \\__\\|";}

```

Sigh, simply outputting the pie is shorter, even with all the escaped backslashes.. \>.\>
Here is previous answer with a tiny bit of afford, although still not very generic or fancy (**236 bytes**):

```
String c(){String n="\n",p="|",q=p+n,x="\\::\\",s=" ",z=s;return"()()()()()()"+n+p+"\\"+3.1415926+q+p+":\\53589793"+q+x+2384626+q+s+x+433832+q+(z+=s)+x+79502+q+(z+=s)+x+8841+q+(z+=s)+x+971+q+(z+=s)+x+69+q+(z+=s)+x+3+q+(z+=s)+"\\__\\|";}

```

A pretty boring answer, since simply outputting the result without too much fancy things is shorter in Java than a generic approach.

**Ungolfed & test code:**

Try it here.

```
class M{
  static String c(){
    String n = "\n",
           p = "|",
           q = p + n,
           x = "\\::\\",
           s = " ",
           z = s;
    return "()()()()()()" + n + p + "\\" + 3.1415926 + q + p + ":\\53589793" + q + x + 2384626 + q + s
            + x + 433832 + q + (z += s) + x + 79502 + q + (z += s) + x + 8841 + q
            + (z += s) + x + 971 + q + (z += s) + x + 69 + q + (z += s) + x + 3 + q
            + (z += s) + "\\__\\|";
  }

  public static void main(String[] a){
    System.out.println(c());
  }
}

```

**Output:**

```
()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
 \::\433832|
  \::\79502|
   \::\8841|
    \::\971|
     \::\69|
      \::\3|
       \__\|

```
> 1 votes

# Answer
# Qbasic, 175 bytes

```
?"()()()()()()":?"|\3.1415926|":?"|:\53589793|":?"\::\2384626|":?" \::\433832|":?"  \::\79502|":?"   \::\8841|":?"    \::\971|":?"     \::\69|":?"      \::\3|":?"       \__\|"

```
> 1 votes

# Answer
# Lua, 152 Bytes

```
print[[()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
 \::\433832|
  \::\79502|
   \::\8841|
    \::\971|
     \::\69|
      \::\3|
       \__\|]]

```

Try as I might I could not compress this pi.

Lua is just too verbose to do it, maybe a pi of greater size, but not this one.

Another solution, 186 Bytes.

```
s="()()()()()()\n|\\3.1415926|\n|:\\53589793|\n"i=0 for z in('2384626|433832|79502|8841|971|69|3|'):gmatch'.-|'do s=s..(' '):rep(i)..'\\::\\'..z.."\n"i=i+1 end print(s..'       \\__\\|')

```

Annoyingly Lua's pi isn't accurate enough to even fill the pi. :(
> 1 votes

# Answer
# Javascript, 172 bytes

Paste into your console to run.

```
for(y=n=0,s=`()()()()()()
`;y<10;y++,s+=`|
`)for(x=-2;x++<9;)s+=x>y(Math.PI+'2384626433832795028841971693'[n++]:`\\${y>8?'__':x+1|y>1?'::':'||'}\\`[y-x]||' ';console.log(s)

```
> 1 votes

# Answer
# Deadfish~, 871 bytes

```
{iiii}cicdcicdcicdcicdcicdcic{ddd}dc{{i}}{i}iiiic{ddd}ddc{dddd}dcdddddciiiciiicdddciiiiciiiic{d}iiiciiiic{{i}ddd}c{{d}}{d}ddddc{{i}}{i}iiiic{dddddd}ddddddc{iii}iiiic{dddd}icddciiciiicicddciicddddddc{{i}ddd}iiic{{d}}{d}ddddc{{i}dd}iic{ddd}ddddcc{iii}iiiic{dddd}ddciciiiiicddddciicddddciiiic{{i}ddd}c{{d}}{d}ddddc{ii}iic{iiiiii}c{ddd}ddddcc{iii}iiiic{dddd}cdcciiiiicdddddcdc{{i}ddd}iiiic{{d}}{d}ddddc{ii}iicc{iiiiii}c{ddd}ddddcc{iii}iiiic{dddd}iiiciicddddcdddddciic{{i}ddd}iiiic{{d}}{d}ddddc{ii}iiccc{iiiiii}c{ddd}ddddcc{iii}iiiic{ddd}ddddddccddddcdddc{{i}ddd}iiiiic{{d}}{d}ddddc{ii}iicccc{iiiiii}c{ddd}ddddcc{iii}iiiic{ddd}dddddcddcddddddc{{i}ddd}iiiiic{{d}}{d}ddddc{ii}iiccccc{iiiiii}c{ddd}ddddcc{iii}iiiic{dddd}iiciiic{{i}ddd}dddc{{d}}{d}ddddc{ii}iicccccc{iiiiii}c{ddd}ddddcc{iii}iiiic{dddd}dc{{i}ddd}iiic{{d}}{d}ddddc{ii}iiccccccc{iiiiii}ciiiccdddc{iii}iic{{d}}{d}ddddc

```

Try it online!

Just because.
> 1 votes

# Answer
**JavaScript (ES6), ~~170 bytes~~ 165 bytes**

~~is a bit "cheated", since if run on the console, the return value would be displayed
```
v=0;("()()()()()()\n|9|:87654321".replace(/\d/g,(o)=>"\\"+(Math.PI+'2384626433832795028841971693').substr(v,o,v-=-o)+"|\n"+(o<9?" ".repeat(8-o)+(o>1?"\\::":"\\__\\|"):""))

```~~

After some teaking, the function looks like this(function must be called with parameter with the value 0):

```
v=>`()()()()()()
 |9 |:87654321\\__\\|`.replace(/\d/g,o=>`\\${(Math.PI+"2384626433832795028841971693").substr(v,o,v-=-o)}|
${" ".repeat(9-o)+(o<9&o>1?"\\::":"")}`)

```

If you want to call the function 167 bytes:

```
z=v=>`()()()()()()
 |9 |:87654321\\__\\|`.replace(/\d/g,o=>`\\${(Math.PI+"2384626433832795028841971693").substr(v,o,v-=-o)}|
${" ".repeat(9-o)+(o<9&o>1?"\\::":"")}`)

/*could be run like this or directly in the console*/
console.info("\n"+z(0));
```
> 0 votes

# Answer
# PHP, 142 bytes

Sneaky-sneaky :) `php` just prints everything out without trying to interpret them as PHP code if it does not see any `<?php ?>` pairs.

```
()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
 \::\433832|
  \::\79502|
   \::\8841|
    \::\971|
     \::\69|
      \::\3|
       \__\|

```
> 0 votes

# Answer
# Husk, 76 bytes

```
`:+R' 7"¦__¦|":*"()"6§+(mo:'|t↑2)↓2m↓3z+zR¢" "Nmo`:'|+"¦::¦"Cṫ9Γ·::'.ṁs↑54İπ

```

Try it online!

There's probably some interesing way to shorten this further.
> 0 votes

# Answer
# Vyxal, 64 bytes

```
‛()6*15∆Iṅ\.1Ṁ½÷$‛|\p$`|:\\`p"43∆I16ȯ7ɾṘẇvṅ‛\:mvp‛\_mJJ\|vJJ12↳⁋

```

Try it Online!
> 0 votes

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