title: Construct a Tornado

text:
# Question
Title: Construct a Tornado
According to me, a tornado looks like this:

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

```

This tornado starts out with width `n`, and on each next line, a character is removed from either the left or the right, depending on the input.

# Input

The input will be a list of some sort of any two unique values (a string of two unique characters works too), and an optional positive integer to indicate the starting width. If the optional integer is not taken, then the starting width is 1 greater than the length of the list. Let the starting width be `n`.

# How to make a tornado

In my example, I choose my list to contain `1`s and `0`s, though you may choose any two distinct constant values, or a string of any two distinct constant characters.

The first row will consist of `n` non-whitespace characters (you may choose any consistent character; I choose `#` for my example).

Then, for each number in the list, if the number is `0`, remove the left character and create a new row; if it's a `1`, remove the right character and create a new row.

Thus, the above tornado is the output for `8, [1, 0, 0, 0, 1, 0, 0]`.

# Output

The output can be a list of strings, a list of lists of characters, or a multiline string. Trailing whitespace on each line is allowed, and a trailing newline at the end is allowed.

# Test Cases

These testcases include the starting width and use lists of `1, 0`.

```
5, [1,0,0,1]

#####
####
 ###
  ##
  #

10, [1,0,0,1,0,1,0,0,1]

##########
#########
 ########
  #######
  ######
   #####
   ####
    ###
     ##
     #

7, [1,1,1,1,1,1]

#######
######
#####
####
###
##
#

```

# Rules

* Standard loopholes apply
* Shortest code in bytes wins!
* Background doesn't have to be a space (I forgot to specify this earlier).
* Your language only has to support numbers (widths) that it can handle, but if your interpreter were rewritten with a larger number size, it has to theoretically work.

# Reference Implementation

# Answer
> 10 votes
# Python 2, ~~66~~ 59 bytes

-7 bytes thanks to Arnold Palmer

```
x,z=input()
for i in range(x):print' '*sum(z[:i])+'#'*(x-i)

```

Try it online!

`0` to remove from the right, `1` to remove from the left

# Answer
> 9 votes
# , ~~15~~, 12 bytes

```
ïÀé#òÙxHxG@"

```

Try it online!

`l` for right, (makes perfect sense, doesn't it?) and `>` for left.

# Answer
> 7 votes
# vim, 85 82 bytes

```
o"cp:s/#/ <C-v><CR>0"cy$<ESC>"ayy7hR$/<ESC>"bdd:s/[][, ]\+/<C-v><CR>@/g<CR>ggAa#<C-v><ESC><ESC>^D@"^"cy$:2,$:norm D@"

```

`<ESC>` is 0x1B, `<CR>` is `0x0D`, `<C-v>` is 0x16. And `<ESC>OH` is a multibyte sequence representing the HOME key.

The input uses `a` as the "remove left" value and `b` as the "remove right" value.

```
" @a will remove from the left; @b will remove from the right.
o"cp:s/#/ <C-v><CR>0"cy$<ESC>"ayy
7hR$/<ESC>"bdd

" split the input into digestible chunks
:s/[][, ]\+/<C-v><CR>@/g<CR>
gg

" Create the first line
Aa#<C-v><ESC><ESC>
^D
@"^"cy$

" Create tornado
:2,$:norm D@"

```

No TIO link, unfortunately. I couldn't get it working under V. Test by copying code into tornado.vim (replacing `<ESC>`, etc with their actual bytes) and running as follows:

```
$ echo '8, [b, a, a, a, b, a, a]' > a.txt
$ { cat tornado.vim; echo ':wq'; } | vim a.txt
$ cat a.txt

```

-3 bytes due to Neil's suggestion.

# Answer
> 5 votes
# 05AB1E, ~~11~~ 9 bytes

-2 bytes thanks to Erik the Outgolfer

```
0×=²v¨yú=

```

Remove from left: `1`
Remove from right: `0`

Try it online!

```
0×        # Make a string of n 0s
  =       # Print without popping
   ²v     # For each character in input (call it y):
     ¨    #   Remove the last character of the current string
      yú  #   Pad with y spaces
        = #   Print without popping

```

# Answer
> 4 votes
# Retina, ~~30~~ 28 bytes

```
.?
$`#$&$'¶
T`d`#`#.*
T`d` _

```

Try it online! Takes just a string of 0s and 1s and calculates the width based on the string. Explanation: The first stage takes the input string and duplicates it once for each boundary point, inserting a `#` at that point. The second stage then changes all the digits after the `#` to more `#`s, creating the triangle. The third stange then deletes all the remaining ones and changes the zeros to spaces which results in the torndao's "wobble".

# Answer
> 3 votes
# Python 2, ~~58~~ 57 bytes

edit: saved 1 byte thanks to xnor

```
l,a=input()
s="#"*l
for i in a+[0]:print s;s=" "*i+s[:-1]

```

Try it online!

1 to remove from the left, 0 to remove from the right.

# Answer
> 3 votes
# , 32 19 bytes

```
' #'#~0(,.#\.)@,+/\

```

Try it online!

-13 thanks to miles

Very belated update...

# Answer
> 3 votes
## Perl, 43 bytes

**42 bytes code + 1 for `-l`.**

```
$_="#"x<>;do{print}while<>|0?s/#$//:s/#/ /

```

Try it online!

# Answer
> 3 votes
# , ~~85~~ 82 bytes

3 bytes saved thanks to Giuseppe

```
function(n,l)for(k in 1:n)cat(rep(" ",sum(c(0,l)[1:k])),rep("%",n-k+1),"
",sep="")

```

Try it online!

Explanation:

```
function(n,l){
  for(k in 1:n){                      # Proceed line by line
    cat(                              # Concatenate...
        rep(" ",sum(c(0,l)[1:k])),    # ...required number of leading spaces,...
        rep("%",n-k+1),               # ...required number of tornado characters...
        "\n",                         # ...and a new line.
        sep=""                        # Join without spaces
        )
  }
}

```

# Answer
> 3 votes
## Haskell, 50 bytes

```
h n=scanl(\s i->[(' ':),id]!!i$init s)$'#'<$[1..n]

```

Try it online!

If the input list can be a list of function names, we can save a byte

### Haskell, 49 bytes

```
f=id
g=(' ':)
h n=scanl(flip id.init)$'#'<$[1..n]

```

Usage example: `h 5 [g,f,f,g]`.

Try it online!

How it works:

```
           '#'<$[1..n]   -- build the first line of the tornado, i.e. n times '#'
scanl(    )              -- repeatedly apply the given function to the starting
                         -- value and the next element of the input list and
                         -- return a list of the intermediate results
  \s i->                 -- the function takes a string s and a number i
            init s       -- and first drops the last element of s
      [    ]!!i          -- and then picks and apply a funtion from the list
        (' ':)           --  i = 0:  prepend a space
        id               --  i = 1:  do nothing

```

# Answer
> 3 votes
# C, ~~68~~ ~~63~~ 62 bytes

```
s;f(w,i)int*i;{for(;w;s+=*i++)printf("%*s%0*d\n",s,"",w--,0);}

```

This makes use of the dynamic field width specification in a `printf()` format string. The function is called like this:

```
#include <stdio.h>

s;f(w,i)int*i;{for(;w;s+=*i++)printf("%*s%0*d\n",s,"",w--,0);}

int main() {
    f(8, (int[]){0, 1, 1, 1, 0, 1, 1});
}

```

As suggested by @EasyasPi, this swaps the meaning of zero and one in the control string to save a negation in the loop increment expression. Which is fine by the "you may choose any two distinct constant values" rule.

# Answer
> 3 votes
# ArnoldC, 3132 bytes

ArnoldC doesn't have string concatenations, so this builds a tornado out of `8`s and uses `1`s to space it out. ArnoldC also only supports up to 16-bit integers, so it overflows with input longer than 7 digits. (So it will only make mini-tornadoes)

`1` is left, any other digit is right (although I wouldn't recommend `0`, since you can't start with that.)

Input: `1221122`

Output:

```
88888888
18888888
18888881
18888811
11888811
11188811
11188111
11181111

```

Golfed code:

```
IT'S SHOWTIME
HEY CHRISTMAS TREE d
YOU SET US UP 0
HEY CHRISTMAS TREE e
YOU SET US UP 0
HEY CHRISTMAS TREE m
YOU SET US UP 0
GET YOUR ASS TO MARS m
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
HEY CHRISTMAS TREE l
YOU SET US UP 0
GET YOUR ASS TO MARS l
DO IT NOW g m
DO IT NOW h l m
YOU HAVE BEEN TERMINATED
LISTEN TO ME VERY CAREFULLY g
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE m
GIVE THESE PEOPLE AIR
HEY CHRISTMAS TREE i
YOU SET US UP 2
HEY CHRISTMAS TREE n
YOU SET US UP m
STICK AROUND n
GET TO THE CHOPPER n
HERE IS MY INVITATION n
HE HAD TO SPLIT 10
ENOUGH TALK
BECAUSE I'M GOING TO SAY PLEASE n
GET TO THE CHOPPER i
HERE IS MY INVITATION i
GET UP 1
ENOUGH TALK
YOU HAVE NO RESPECT FOR LOGIC
CHILL
I'LL BE BACK i
HASTA LA VISTA, BABY
LISTEN TO ME VERY CAREFULLY h
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE l
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE m
GIVE THESE PEOPLE AIR
HEY CHRISTMAS TREE o
YOU SET US UP -2
GET TO THE CHOPPER o
HERE IS MY INVITATION o
GET UP l
ENOUGH TALK
HEY CHRISTMAS TREE k
YOU SET US UP 1
STICK AROUND o
GET TO THE CHOPPER k
HERE IS MY INVITATION k
YOU'RE FIRED 10
ENOUGH TALK
GET TO THE CHOPPER o
HERE IS MY INVITATION o
GET DOWN 1
ENOUGH TALK
CHILL
HEY CHRISTMAS TREE p
YOU SET US UP 0
HEY CHRISTMAS TREE f
YOU SET US UP 0
HEY CHRISTMAS TREE i
YOU SET US UP 0
HEY CHRISTMAS TREE q
YOU SET US UP l
HEY CHRISTMAS TREE d
YOU SET US UP 0
HEY CHRISTMAS TREE e
YOU SET US UP 1
HEY CHRISTMAS TREE a
YOU SET US UP 0
HEY CHRISTMAS TREE b
YOU SET US UP 0
HEY CHRISTMAS TREE c
YOU SET US UP l
STICK AROUND q
GET TO THE CHOPPER i
HERE IS MY INVITATION 0
ENOUGH TALK
GET TO THE CHOPPER a
HERE IS MY INVITATION d
ENOUGH TALK
GET TO THE CHOPPER b
HERE IS MY INVITATION e
ENOUGH TALK
GET TO THE CHOPPER c
HERE IS MY INVITATION l
ENOUGH TALK
STICK AROUND c
BECAUSE I'M GOING TO SAY PLEASE a
GET TO THE CHOPPER i
HERE IS MY INVITATION i
GET UP 1
YOU'RE FIRED 10
ENOUGH TALK
GET TO THE CHOPPER a
HERE IS MY INVITATION a
GET DOWN 1
ENOUGH TALK
BULLSHIT
GET TO THE CHOPPER f
HERE IS MY INVITATION b
LET OFF SOME STEAM BENNET c
ENOUGH TALK
BECAUSE I'M GOING TO SAY PLEASE f
GET TO THE CHOPPER i
HERE IS MY INVITATION i
GET UP 1
YOU'RE FIRED 10
ENOUGH TALK
BULLSHIT
GET TO THE CHOPPER i
HERE IS MY INVITATION i
GET UP 8
YOU'RE FIRED 10
ENOUGH TALK
YOU HAVE NO RESPECT FOR LOGIC
YOU HAVE NO RESPECT FOR LOGIC
GET TO THE CHOPPER c
HERE IS MY INVITATION c
GET DOWN 1
ENOUGH TALK
CHILL
GET TO THE CHOPPER i
HERE IS MY INVITATION i
HE HAD TO SPLIT 10
ENOUGH TALK
TALK TO THE HAND i
GET TO THE CHOPPER q
HERE IS MY INVITATION q
GET DOWN 1
ENOUGH TALK
GET TO THE CHOPPER p
HERE IS MY INVITATION m
HE HAD TO SPLIT k
I LET HIM GO 10
ENOUGH TALK
GET TO THE CHOPPER k
HERE IS MY INVITATION k
HE HAD TO SPLIT 10
ENOUGH TALK
GET TO THE CHOPPER f
HERE IS MY INVITATION p
YOU ARE NOT YOU YOU ARE ME 1
ENOUGH TALK
BECAUSE I'M GOING TO SAY PLEASE f
GET TO THE CHOPPER d
HERE IS MY INVITATION d
GET UP 1
ENOUGH TALK
BULLSHIT
GET TO THE CHOPPER e
HERE IS MY INVITATION e
GET UP 1
ENOUGH TALK
YOU HAVE NO RESPECT FOR LOGIC
CHILL
I'LL BE BACK i
HASTA LA VISTA, BABY

```

Try it online!

Ungolfed code (5178 bytes):

```
IT'S SHOWTIME
    HEY CHRISTMAS TREE left
        YOU SET US UP 0
    HEY CHRISTMAS TREE right
        YOU SET US UP 0
    HEY CHRISTMAS TREE input
        YOU SET US UP 0
        GET YOUR ASS TO MARS input
        DO IT NOW
        I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
    HEY CHRISTMAS TREE width
    YOU SET US UP 0
    GET YOUR ASS TO MARS width
    DO IT NOW calcwidth input
    DO IT NOW buildline width input
YOU HAVE BEEN TERMINATED

LISTEN TO ME VERY CAREFULLY calcwidth
    I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE input
    GIVE THESE PEOPLE AIR
    HEY CHRISTMAS TREE result
    YOU SET US UP 2
    HEY CHRISTMAS TREE calc
    YOU SET US UP input
    STICK AROUND calc
        GET TO THE CHOPPER calc
        HERE IS MY INVITATION calc
        HE HAD TO SPLIT 10
        ENOUGH TALK
        BECAUSE I'M GOING TO SAY PLEASE calc
            GET TO THE CHOPPER result
        HERE IS MY INVITATION result
        GET UP 1
        ENOUGH TALK
    YOU HAVE NO RESPECT FOR LOGIC
    CHILL
    I'LL BE BACK result
HASTA LA VISTA, BABY

LISTEN TO ME VERY CAREFULLY buildline
    I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE width
    I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE input
    GIVE THESE PEOPLE AIR

    HEY CHRISTMAS TREE ctr
        YOU SET US UP -2
        GET TO THE CHOPPER ctr
            HERE IS MY INVITATION ctr
            GET UP width
        ENOUGH TALK
    HEY CHRISTMAS TREE mask
        YOU SET US UP 1
        STICK AROUND ctr
            GET TO THE CHOPPER mask
                HERE IS MY INVITATION mask
                YOU'RE FIRED 10
            ENOUGH TALK
            GET TO THE CHOPPER ctr
                HERE IS MY INVITATION ctr
                GET DOWN 1
            ENOUGH TALK
        CHILL
    HEY CHRISTMAS TREE digit
        YOU SET US UP 0
    HEY CHRISTMAS TREE decider
        YOU SET US UP 0
    HEY CHRISTMAS TREE result
        YOU SET US UP 0
    HEY CHRISTMAS TREE lines
        YOU SET US UP width
    HEY CHRISTMAS TREE left
        YOU SET US UP 0
    HEY CHRISTMAS TREE right
        YOU SET US UP 1
    HEY CHRISTMAS TREE leftcounter
        YOU SET US UP 0
    HEY CHRISTMAS TREE rightcounter
        YOU SET US UP 0
    HEY CHRISTMAS TREE widthcounter
    YOU SET US UP width
    STICK AROUND lines
        GET TO THE CHOPPER result
            HERE IS MY INVITATION 0
        ENOUGH TALK
        GET TO THE CHOPPER leftcounter
            HERE IS MY INVITATION left
        ENOUGH TALK
        GET TO THE CHOPPER rightcounter
            HERE IS MY INVITATION right
        ENOUGH TALK
        GET TO THE CHOPPER widthcounter
            HERE IS MY INVITATION width
        ENOUGH TALK
        STICK AROUND widthcounter
            BECAUSE I'M GOING TO SAY PLEASE leftcounter
                GET TO THE CHOPPER result
                    HERE IS MY INVITATION result
                    GET UP 1
                    YOU'RE FIRED 10
                ENOUGH TALK
                GET TO THE CHOPPER leftcounter
                    HERE IS MY INVITATION leftcounter
                    GET DOWN 1
                ENOUGH TALK
            BULLSHIT
                GET TO THE CHOPPER decider
                    HERE IS MY INVITATION rightcounter
                    LET OFF SOME STEAM BENNET widthcounter
                ENOUGH TALK
                BECAUSE I'M GOING TO SAY PLEASE decider
                    GET TO THE CHOPPER result
                        HERE IS MY INVITATION result
                        GET UP 1
                        YOU'RE FIRED 10
                    ENOUGH TALK
                BULLSHIT
                    GET TO THE CHOPPER result
                        HERE IS MY INVITATION result
                        GET UP 8
                        YOU'RE FIRED 10
                    ENOUGH TALK
                YOU HAVE NO RESPECT FOR LOGIC
            YOU HAVE NO RESPECT FOR LOGIC

            GET TO THE CHOPPER widthcounter
                HERE IS MY INVITATION widthcounter
                GET DOWN 1
            ENOUGH TALK
        CHILL
        GET TO THE CHOPPER result
            HERE IS MY INVITATION result
            HE HAD TO SPLIT 10
        ENOUGH TALK
        TALK TO THE HAND result
        GET TO THE CHOPPER lines
            HERE IS MY INVITATION lines
            GET DOWN 1
        ENOUGH TALK
        GET TO THE CHOPPER digit
            HERE IS MY INVITATION input
            HE HAD TO SPLIT mask
            I LET HIM GO 10
        ENOUGH TALK
        GET TO THE CHOPPER mask
            HERE IS MY INVITATION mask
            HE HAD TO SPLIT 10
        ENOUGH TALK
        GET TO THE CHOPPER decider
            HERE IS MY INVITATION digit
            YOU ARE NOT YOU YOU ARE ME 1
        ENOUGH TALK
        BECAUSE I'M GOING TO SAY PLEASE decider
            GET TO THE CHOPPER left
                HERE IS MY INVITATION left
                GET UP 1
            ENOUGH TALK
        BULLSHIT
            GET TO THE CHOPPER right
                HERE IS MY INVITATION right
                GET UP 1
            ENOUGH TALK
        YOU HAVE NO RESPECT FOR LOGIC
    CHILL
    I'LL BE BACK result
HASTA LA VISTA, BABY

```

# Answer
> 2 votes
# , ~~116~~ ~~109~~ 102 bytes

*-5 bytes thanks to user2390246* (and another 2 I saved myself)

Outgolfed by user2390246

```
function(n,l){k=cumsum
m=matrix(' ',n,n)
for(i in 1:n)m[k(c(1,!l))[i]:k(c(n,-l))[i],i]='#'
write(m,'',n,,'')}

```

Try it online!

Returns an anonymous function that takes `n` and a vector `l` with `0` for removing from the left and `1` for removing from the right, and prints the result to console with the right formatting.

# Answer
> 2 votes
# Japt, ~~14~~ 13 bytes

*-1 byte thanks to @ETH*

```
å+ uP £X+QpV´

```

Input is the array, then the size. Array values are `""` or `" "`, which represent removing from the right or left, respectively. Uses `"` instead of `#` and returns as an array of strings.

The idea here was to first create an array of the left padding for each line, hence the input strings. Then, each line gets the `"`s added, using the fact that the amount of `"`s decreases by 1 each time.

## Try it online!

These all use the `-R` flag to format the output by joining it with newlines.

## Explanation

```
å+ uP £X+QpYnV

```

Implicit: `U` = input array, `V` = input number.

```
å+ uP

```

Cumulatively reduce the input array (`å`) with string concatenation (`+`). This results in the array of each intermediate value of the reduction. Then, prepend (`u`) an empty string (`P`) to the array.

```
£X+

```

Map `£` each value to itself (`X`) concatenated with...

```
QpV´

```

The quote character (`Q`) repeated (`p`) `V--` () times. This also decrements `V` each time.

# Answer
> 2 votes
# K (ngn/k), ~~22~~ 19 bytes

```
{(-x,x-\y)$|,\x#$0}

```

Try it online!

Takes two args: the starting width (x), and the list of values (y). Returns a list of strings, with `"0"` in place of `"#"`.

* `x#$0` initialize a string with `x` copies of `"0"`, e.g. `"00000"`
* `|,\` get the reversed prefixes of that string, e.g. `("00000";"0000";"000";"00";,"0")`
* `(-x,x-\y)` determine how long each line of the output should be (with no trailing spaces) and negate it, e.g. `-5 -4 -4 -4 -3`
* `(...)$...` left-pad each line (with spaces) to its proper length

# Answer
> 1 votes
# Haskell, ~~67~~ 64 bytes

The input is flipped: `0` means remove right, and `1` remove left:

```
f n=zipWith(\x y->(' '<$[1..y])++('#'<$[1..n-x]))[0..].scanl(+)0

```

Try it online!

### "Ungolfed"

```
f n = zipWith (\x y-> replicate y ' ' ++ replicate (n-x) '#') [0..] . scanl (+) 0

```

# Answer
> 1 votes
# Java (OpenJDK 8), ~~138~~ 133 bytes

```
a->n->{char[]s=new char[n];int i=n,v,k[]={0,--n};for(;i-->0;s[i]=35);for(;i++<n;s[k[v=a[i%n]]]=32,k[v]-=v-1|v)System.out.println(s);}

```

Try it online!

# Answer
> 1 votes
# JavaScript (ES6), 64 bytes

Anonymous function taking parameters in currying syntax (a)(b). In the b array an empty string represents removing from right and a space represents removing from left.

```
a=>b=>b.reduce((t,v)=>t+'\n'+(a.pop(),p+=v)+a,a=Array(a+1),p='')

```

Using 1 and 0 like in the examples the score is 70

```
a=>b=>b.reduce((t,v)=>t+'\n'+(a.pop(),v?p:p+=' ')+a,a=Array(a+1),p='')

```

**Test**

```
F=
a=>b=>b.reduce((t,v)=>t+'\n'+(a.pop(),p+=v)+a,a=Array(a+1),p='')

function update() {
  var b=B.value.match(/\d/g)

  if (b) {
    b=b.map(v=>+v?'':' ')
    O.textContent = F(b.length+1)(b)
  }
  else
    O.textContent = 'invalid input'
}

update()

```

```
Input B (0 and 1) <input id=B value='1001' oninput='update()'>
<pre id=O></pre>
```

# Answer
> 1 votes
# Scala, ~~41~~ 39 bytes

```
n=>_.scanLeft("#"*n)(" "+_.init drop _)

```

Try it online!

Uses 1 for dropping a hash on the right, 0 for dropping a hash on the left. Accepts `(n)(list)`. Outputs a list of strings.

## Input and output reversed, 35 bytes

```
n=>_.scanRight("#"*n)(" "*_+_.init)

```

Try it online!

Help! The sky's falling down!

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

```

# Answer
> 1 votes
# Vyxal, 10 bytes

```
×*…?(Ṫn$꘍…

```

Try it Online!

## How?

```
×*…?(Ṫn$꘍…
×*          # Repeat an asterisk the first (implicit) input amount of times
  …         # Print without popping
   ?(       # Loop through the second input
     Ṫ      # Remove the last character of the current string
      n$꘍   # Prepend the current item amount of spaces
         …  # Print without popping

```

# Answer
> 0 votes
# PowerShell, 53 bytes

```
param($a,$b)"#"*$a;0..$a|%{" "*($i+=$b[$_])+"#"*--$a}

```

Try it online!

Takes input `$a` as the optional integer and `$b` as the array of `1` and `0`s. (Note that my array of `1` and `0` is flip-flopped from the challenge's.) Constructs the initial line of `#` and leaves that on the pipeline. Then loops from `0` to `$a`. Each iteration, we output a possibly-incremented number of spaces, followed by a pre-decremented number of `#`. Yes, this will spit out a blank trailing newline at the end, since we're looping up to `$a` rather than the number of items in the list.

All the individual strings are left on the pipeline and output with a newline separator between them is implicit at program completion.

# Answer
> 0 votes
# C#, 181 bytes

```
n=>a=>{var r=new string[n];r[0]=new string('#',n);for(int i=1,p;i<n;++i){r[i]=r[i-1];p=a[i-1]?r[i].LastIndexOf('#'):r[i].IndexOf('#');r[i]=r[i].Remove(p,1).Insert(p," ");}return r;}

```

Try it online!

Full/Formatted Version:

```
class P
{
    static void Main()
    {
        System.Func<int, System.Func<bool[], string[]>> f = n => a =>
        {
            var r=new string[n];
            r[0]=new string('#',n);

            for (int i = 1, p; i < n; ++i)
            {
                r[i] = r[i - 1];
                p = a[i - 1] ? r[i].LastIndexOf('#') : r[i].IndexOf('#');
                r[i] = r[i].Remove(p, 1).Insert(p, " ");
            }

            return r;
        };

        System.Console.WriteLine(string.Join("\n", f(5)(new[] { true, false, false, true })));

        System.Console.ReadLine();
    }
}

```

# Answer
> 0 votes
# Charcoal, 17 bytes

```
ＦＮ«Ｐ×#⁺¹ι¿Ｉ§⮌ηι↑↖

```

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

```
ＦＮ«

```

The first input gives the number of loop iterations.

```
Ｐ×#⁺¹ι

```

Since loop indices default to zero-indexed, we add one here to get the correct number of `#`s.

```
¿Ｉ§⮌ηι

```

Starting from the bottom of the tornado and working up saves a byte, but we then need to reverse the second input so that we can index the current digit.

If the current digit is a `1`, move up. This makes the previous row have an extra `#` at the end.

If the current digit is a `0`, move up and left. This makes the previous row have an extra `#` at the start.

# Answer
> 0 votes
# C#, 159 bytes

```
using System.Linq;n=>a=>new[]{new string('#',n)}.Concat(a.Select((_,i)=>{var s=a.Take(i+1).Count(j=>j==0);var h=n-i-1;return new string('#',h).PadLeft(s+h);}))

```

**Explanation**

```
 new[] { new string('#', n) }                //start with n number of hashes
                .Concat(                     //append...
                    a.Select((_, i) =>       //    map each element of array
                    {
                        var s = a.Take(i + 1).Count(j => j == 0);  // count the number of 0's up to, and including, this point
                        var h = n - i - 1;                         // number of hashes for this step
                        return new string('#', h).PadLeft(s + h);  // number of hashes padded left with number of 0s
                    }));

```

Try it online!

# Answer
> 0 votes
## PHP, 136 bytes

```
$b=explode(',',end($argv));$a=$argc==3?$argv[1]:count($b)+1;$c=0;for(;$a;--$a){printf("% {$c}s%'#{$a}s\n",'','');$c+=!array_shift($b);}

```

Save in a php file and test with `php file.php 8 '1,0,0,0,1,0,0'`. Output:

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

```

Alas, getting the input ready is half of the job.

Another version (158 bytes) using `str_repeat` instead of `printf` and...`goto` of all things:

```
$b=explode(',',end($argv));$a=$argc==3?$argv[1]:count($b)+1;$c=0;z:
echo str_repeat(' ',$c).str_repeat('#',$a)."\n";while(--$a){$c+=!array_shift($b);goto z;}

```

# Answer
> 0 votes
# Jelly, 11 bytes

```
ŻµJṚżÄUØṖxⱮ

```

Try it online!

Uses `0` for `1` and `1` for `0`, and outputs a list of rows with `!` for `#`. (Note the convenience testing footer `¬ÇY$€Y`: negate, join each output on newlines, join the outputs on newlines.)

```
Żµ             Consider the input with 0 prepended.
    ż          Zip
  J            [1 .. length]
   Ṛ           reversed
     Ä         with the cumulative sums,
      U        and reverse each pair.
          Ɱ    For each pair,
         x     vectorizing repeat
       ØṖ      printable ASCII.

```

Since dyadic zipwith-vectorization pads with 0 when the shapes of the arguments don't match, every character in the list of printable ASCII characters is repeated 0 times except for space and `!`.

# Answer
> 0 votes
# APL (Dyalog Unicode), 18 bytes

Takes 1's and 0's swapped.

```
(0,-+\⎕)⌽⊖↑,\⎕/'#'

```

Try it online!

`⎕/'#'` create a string of length `n`.
`,\` get all prefixes of the string.
`⊖↑` arrange the prefixes in a character matrix with the longest one at the top.
`+\⎕` cumulative sums of the input list.
`0,-` take the negative of every value and prepend a 0.
rotate each row of the character matrix by a corresponding number of characters.

I think there might be a way to get a list of all column heights and use this to get the output with `⍉↑'#'/⍨¨`, but I couldn't figure it out.

# Answer
> 0 votes
# Stax, 9 bytes

```
éPQ─\▐┐·è

```

Run and debug it

takes `0` as `-1` and `1` as `0`.

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


title: Bracket Depth List

text:
# Question
Title: Bracket Depth List
## Challenge

Your challenge is simple, calculate the depth of each matching brackets in the given input e.g. `(()()(()))`-\>`[[1,1,[1]]]`, and output it in the form of a list/array/string representation

## Explanation:

For every bracket in the input, you have to count how many nested brackets there are for that part of the input e.g. `()` has 1 depth

Although if find a bracket of depth 2 e.g. `(())`, a list `[]` is formed from the 1st bracket `( )` has to be added to the output with the 2nd bracket, `()` of depth 1 inside that list

## Test cases:

```
() -> [1]
[[][]] -> [[1,1]]
{}{}{{}}{{{}}} -> [1,1,[1],[[1]]

```

## Others

You may assume that there are only lists and `1`'s will be in the required output

For the output, you are allowed to output the depth as a list/array, or as a string representation e.g. `1 1 [1]` for `()()(())`

You can output it in other ways, but the depth of the brackets must be distinguishable from each other.

Your answer should be able to handle one type of bracket (one of `()`, `[]`, or `{}`), at your choice.

You may assume that input is balanced and only uses the type of bracket you chose.

# Answer
# Python, ~~236~~ 155 bytes

```
def r(o):
 v="[";s=a=n=0
 for c in o:
  if c=="(":
   if s<1:a=n+1
   s+=1
  else:
   s-=1
   if a==n:v+="1,"
   elif s<1:v+=r(o[a:n])
  n+=1
 return v+"]"

```

Is this a good solution? No. But I don't think there'll be another answer here soon, and I'm very new to codegolf so I thought I might try my luck here :p

Attmpt this online!
> 4 votes

---
Tags: code-golf, array, balanced-string, ragged-list
---


title: Draw an ASCII-art rainbow

text:
# Question
Title: Draw an ASCII-art rainbow
Draw an ASCII-art rainbow!

# Input

An integer between 0 and 1000, inclusive.

# Examples

Input 0:

```

/\
||

```

Input 1:

```
 _
/ \
| |

```

Input 2:

```
 __
/  \
|  |

```

Input 3:

```
 ___
/   \
|   |

```

The first row is a space followed by *n* underscores.

The second row is a slash followed by *n* spaces, and a backslash.

The third row is a pipe followed by *n* spaces, and a pipe.

Trailing spaces are allowed.

This is . Shortest code wins.

# Answer
# i386 (16-bit mode) Bootsector, 512 bytes

All i386 bootsectors have to be 512 bytes, so... Without the padding required by i386, it is 137 bytes. Since I can't easily post a TIO link, here's a screenshot of it running:

This code registers the BIOS interrupt `int 0x69` to take the number in the `bx` register and use it as input. Thus, doing

```
mov bx, 3
int 0x69

```

is equivalent to the last test case. The disassembled, Intel-syntax source is:

```
[org 0x7c00]

xor ax, ax
mov es, ax
cli
mov dx, interrupt
mov [es:0x69*4], dx
mov ax, cs
mov [es:0x69*4+2], ax
sti

xor bx, bx
int 0x69
call newline
mov bx, 1
int 0x69
call newline
mov bx, 2
int 0x69
call newline
mov bx, 3
int 0x69
cli
hlt

interrupt:
or bx, bx
jz special
push bx
mov ax, 0x0e20
int 0x10
mov al, '_'
.loop1:
int 0x10
dec bx
jnz .loop1
call newline
mov al, '/'
int 0x10
mov al, ' '
pop bx
push bx
.loop2:
int 0x10
dec bx
jnz .loop2
mov al, '\'
int 0x10
call newline
mov al, '|'
int 0x10
pop bx
mov al, ' '
.loop3:
int 0x10
dec bx
jnz .loop3
mov al, '|'
int 0x10
iret

newline:
mov ax, 0x0e0d
int 0x10
mov al, 0x0a
int 0x10
ret

special:
mov si, s
mov ah, 0x0e
.sloop:
lodsb
int 0x10
or al, al
jnz .sloop
iret

s: db '/', '\', 10, 13, '|', '|'

times 510-($-$$) db 0
dw 0xaa55

```

(Bit verbose, I know, but hey, it's assembly.)
> 31 votes

# Answer
# Charcoal, 11 bytes

```
↑|↗/×_Ｎ¶\¶|

```

Try it online! Link is to verbose version of code. This shape is too simple to tax Charcoal's drawing primitives, so this is just basically printing strings to the canvas. Explanation:

```
↑|

```

Print the left `|` and move the cursor up a line.

```
↗/

```

Print the `/` and move the cursor to the start of the `_`s.

```
×_Ｎ

```

Print the desired number of `_`s. This leaves the cursor just to the right of the last `_`.

```
¶\¶|

```

Move down a line, print a `\`, and print a `|` directly beneath.

Just for fun I thought I'd write a 25-byte version which allows you to vary the height and thickness too:

```
ＮθＮηＵＯηＮ|↑Ｇ→↑η/↗ＵＯθη_‖ＢＯθ

```

Try it online! Link is to verbose version of code. Takes input as inner width, thickness and inner height. Note that Charcoal does not support zero-sized boxes, so all of the inputs need to be at least `1`.
> 10 votes

# Answer
# Rust, ~~76~~ ~~57~~ ~~53~~ ~~51~~ 45 bytes

-4 bytes thanks to madlaina

```
|n|print!(" {:_<1$}
/{0:1$}\\
|{0:1$}|","",n)

```

Try it online

---

Old answer (76 bytes):

```
|n|format!(" ")+&"_".repeat(n)+"
/"+&" ".repeat(n)+"\\
|"+&" ".repeat(n)+"|"

```

Try it online

Just the boring answer. Borrows are needed to satisfy the type checker, unfortunately.
> 7 votes

# Answer
# Integral, ~~37~~ 31 Bytes

```
♂8♦⌡_⌡g►⌡/⌡•8g►⌡\⌡►•⌡|⌡♦8g►⌡|⌡►

```

First real answer in my new language!

Try it

Explanation:

```
(Implicit input)
♂      Triplicate top of stack
8      Push space
♦      Swap
⌡_⌡    Push underscore
g      Repeat string
►      Concatenate
⌡/⌡    Push slash
•      Stack: ...abc -> ...bca
8      Push space
g      Repeat string
►      Concatenate
⌡\⌡    Push backslash
•      Stack: ...abc -> ...bca
⌡|⌡    Push pipe
♦      Swap
8      Push space
g      Repeat string
►      Concatenate
⌡|⌡    Push pipe
►      Concatenate

```
> 5 votes

# Answer
# APL (Dyalog Unicode), 21 bytes (SBCS)

Full program, prompting for `n` from stdin.

```
' /|',' \|',⍨3↑1⎕⍴'_'

```

Try it online!

`'_'` an underscore

`1⎕⍴'_'` cyclically reshaped into a matrix with one row and *n* columns

`3↑` take the first three rows, padding with spaces

`' \|',⍨` append this character-list as a trailing column

`' /|',` prepend this character-list as a leading column
> 5 votes

# Answer
# MAWP 1.1, 95 bytes

```
%@~52WWM52WWM52WWM84W;![1A99M1M5W;]%52W;68W1A;![1A84W;]%68W2W4A;52W;56W1M4W;![1A84W;]%56W1M4W;.

```

Try it!

Explanation:

```
%                  Remove initial 1 from stack
@~                 Push input as integers and reverse stack
52WWM              Add top of stack multiplied by 10 to second
                   stack element  [5,4,3,2] ==> [5,4,23]
52WWM52WWM         Two more times [5,4,3,2] ==> [2345]

84W;               Print a space (8*4=32)

!                  Duplicate top of stack
[                  Start of loop
1A                 Subtract 1
99M1M5W;           Print an underscore ((9+9+1)*5=95)
]                  End of loop. If result from subtraction doesn't
                   equal to 0 jump to start of loop
%                  Remove 0
52W;               Print a newline (5*2=10)

68W1A;             Print a slash (6*8-1=47)
![1A84W;]%         Do the same loop as before but printing spaces instead
68W2W4A;           Print a backslash (6*8*2-4=92)
52W;               Print a newline

56W1M4W;           Print a pipe ((5*6+1)*4=124)
![1A84W;]%         Same loop as second
56W1M4W;           Print a pipe
.

```
> 5 votes

# Answer
# 05AB1E, ~~26~~ 21 bytes

### My original 26 bytes approach:

```
" 0 /1\|1|"3ô„_ vy¹иJNs:}»

```

Explanation:

```
" 0 /1\|1|"3ô„_ vy¹иJNs:}»
" 0 /1\|1|"                   push string template (the idea is to replace 0 and 1 with _ and space respectively using loop count index
           3ô                 split by chunks of 3
             „_               push 2 chars _ and space
               v        }     for each character in the previous string
                y¹и           repeat it by the number in input
                   J          join the new string
                    Ns        push the index before that string to easily replace
                      :       replace in the string template
                         »    join by new lines

```

Try It Online

### 21 bytes (@KevinCruijssen comments):

```
„_ S×ā" 1/2|2"2ô.º»r‡

```

Try It Online
> 5 votes

# Answer
# Python 2, 47 bytes

```
lambda n:" %s\n/%s\\\n|%s|"%("_"*n," "*n," "*n)

```

Try it online!

Inserting the `n`-dependent components into a template using string formatting.

---

**48 bytes**

```
lambda n:" "+"_"*n+"\n/"+" "*n+"\\\n|"+" "*n+"|"

```

Try it online!

Straight up concatenation.
> 5 votes

# Answer
# C (gcc), ~~72~~ 70 bytes

-2 bytes thanks to ceilingcat!

```
f(n){printf(" %s\n/%*c\n|%*2$c",memset(calloc(n,2),95,n),n+1,92,'|');}

```

Try it online!
> 5 votes

# Answer
# 05AB1E, ~~18~~ 17 bytes

```
…_  ε×… /|NèºSsý,

```

Try it online or verify a few more test cases.

**Explanation:**

```
…_                 # Push string "_  "
    ε              # Map over each character in this string:
     ×             #  Repeat it the (implicit) input amount of times as string
      … /|         #  Push string " /|"
          Nè       #  Use the map-index to index into this string
            º      #  Mirror the character (" "→"  "; "/"→"/\"; "|"→"||")
             S     #  Convert the string to a pair of characters
              s    #  Swap so the "_"/" "-string is at the top of the stack
               ý   #  Join the pair with this string as delimiter
                ,  #  And output it with trailing newline

```
> 4 votes

# Answer
# JavaScript (ES8), 50 bytes

```
n=>` ${'_'.repeat(n)}
/${s=''.padEnd(n)}\\
|${s}|`

```

Try it online!

---

# JavaScript (ES6), 50 bytes

```
n=>' '+`_
/ \\
| |`.replace(/_| /g,c=>c.repeat(n))

```

Try it online!
> 3 votes

# Answer
# MATL, 20 bytes

```
' /|'4i:)B95*' \|'v!

```

Try it online!

### How it works

```
' /|'   % Push this string: first column of the output, but as a row (*)
4       % Push 4
i:)     % Implicitly input n; range; modular indexing. This gives a row vector
        % [4 4 ... 4] of length n
B       % Convert to binary. Each number gives a row in the output. So this
        % produces the matrix [1 0 0; 1 0 0; ...; 1 0 0] with n rows
95*     % Multiply each entry by 95 (ASCII code of '_'). This gives the central
        % columns of the output, but transposed, as an n×3 matrix (**)
' \|'   % Push this string: last column of the output, but as a row (***)
v       % Concatenate (*), (**) and (***) vertically
!       % Transpose. Implicitly display

```
> 3 votes

# Answer
# Jelly, 19 bytes

```
“_  ”×“  “/\“||”j"Y

```

A full program accepting a non-negative integer which prints the resulting ASCII art.

**Try it online!**

### How?

```
“_  ”×“  “/\“||”j"Y - Main Link: integer, n (e.g. 3)
“_  ”               - list of characters = ['_', ' ', ' ']
     ×              - multiply -> ['___', '   ', '   '] (now strings, a bit of a hack in Jelly)
      “  “/\“||”    - list of lists of characters = [[' ', ' '], ['/', '\'], ['|', '|']]
                 "  - zip together applying:
                j   -   join -> [[' ', '___', ' '], ['/', '   ', '\'], ['|', '   ', '|']]
                  Y - join with newlines -> [' ', '___', ' ', '\n', '/', '   ', '\', '\n', '|', '   ', '|']
                    - implicit, smashing print
                      >>> ___
                      >>>/   \
                      >>>|   |

```
> 3 votes

# Answer
# Japt, 20 bytes

```
" {ç'_}
/{ç}\\
|{ç}|

```

Try it

`ç` is one of Japt's `repeat` methods for integers; you can probably figure the rest out from there!
> 3 votes

# Answer
# Pyth, 24 bytes

```
%" %s
/%s\\
|%s|"*RQ"_

```

Try it online!

## Explanation

```
%"..."*RQ"_
         "_    : The string literal "_  "
      *RQ      : Multiply each element of the string by input (["___", "   ", "   "])
%"..."         : Do string formating on string with args from previous comamnd

```
> 3 votes

# Answer
# PowerShell, ~~43~~ 41 bytes

-2 bytes thanks to mazzy

```
param($n)' '+'_'*$n
' '*$n|%{"/$_\
|$_|"}

```

Try it online!

Eh, it's ~~okay~~slightly better

Alternative 41 byte solution offered by mazzy
> 3 votes

# Answer
# Java 11, 61 bytes

```
n->" "+"_".repeat(n)+"\n/x\\\n|x|".replace("x"," ".repeat(n))

```

Try it online.

**Explanation:**

```
n->                  // Method with integer parameter and String return-type
  " "                //  Return a space
  +"_".repeat(n)     //  Appended with the input amount of "_"
  +"\n/x\\\n|x|"     //  Appended with "
                     //   /x\
                     //   |x|",
   .replace("x",     //  of which the "x" are replaced with:
     " ".repeat(n))  //   The input amount of spaces

```
> 3 votes

# Answer
# Python 3, 41 bytes

```
lambda n:(f" /|{'_  '*n} \\|\n\n"*3)[::3]

```

Try it online!

How could I forget about f-strings?

---

# Python 3, 43 bytes

```
lambda n:(" /|%s \\|\n\n"%("_  "*n)*3)[::3]

```

Try it online!

Constructs the string transposed, then transposes it using modular arithmetic.
> 3 votes

# Answer
# COW, 420 bytes

```
MoOMoOMoOMoOMoOMoOMoOMMMMoOMoOMoOmoOMMMMOOMMMMOOmoOMoOmOoMOomooMMMMOomoooommoOMoOMoOMoOMoOMooMMMmoOMMMMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMMMMOOmoOMoOMoOMOOmoOMoOmOoMOomoomOoMOomooMMMmoOmoOMMMmOoMMMMoOmOomOomOoMMMMOOmoOmoOmoOMoomOomOomOoMOomooMMMmOoMoomoOmoOmoOMoomOomOoMMMMOOmoOMoomOoMOomoomoOmoOmoOMOoMOoMOoMoomOomOomOomOoMoomoOMMMmoOMMMMOOmoOmoOMoOmOomOoMOomooMMMmoOmoOMMMMoomOomOomOoMOOmoOMoomOoMOomooMMMMoo

```

Try it online!

Pretty happy with 140 instructions (3 bytes per instruction) considering that the ASCII values of the six required characters sum to 400.

### Commented

```
MoOMoOMoOMoOMoOMoOMoO # push 7 to 1st memory block 						blocks: [[7]], register: nil
MMM		      # copy to register 							blocks: [[7]], register: 7
MoOMoOMoO	      # add 3 to 1st block 							blocks: [[10]], register: 7
moOMMM		      # paste 7 to 2nd block							blocks: [10, [7]], register: nil
MOOMMMMOOmoOMoOmOoMOomooMMMMOomoo # set 3rd block to 28 = 7 + 6 + 5 + 4 + 3 + 2 + 1		blocks: [10, [0], 28], register: nil
oom		      # read input n (e.g. 3) into 2nd block					blocks: [10, [3], 28], register: nil
moOMoOMoOMoOMoO	      # add 4 to 3rd block							blocks: [10, 3, [32]], register: nil
Moo		      # print ASCII character 32 (space)					blocks: [10, 3, [32]], register: nil
MMMmoOMMM	      # copy and paste 32 to 4th block						blocks: [10, 3, 32, [32]], register: nil
MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoO # add 15 to 4th block				blocks: [10, 3, 32, [47]], register: nil
MMMMOOmoOMoOMoOMOOmoOMoOmOoMOomoomOoMOomooMMM # add 2 to 6th block 47 times			blocks: [10, 3, 32, [47], 0, 94], register: nil
moOmoOMMMmOoMMM	      # copy and paste 94 to 5th block						blocks: [10, 3, 32, 47, [94], 94], register: nil
MoO		      # add 1 to 5th block							blocks: [10, 3, 32, 47, [95], 94], register: nil
mOomOomOoMMMMOOmoOmoOmoOMoomOomOomOoMOomooMMM # print ASCII character 95 (underscore) n times	blocks: [10, [3], 32, 47, 95, 94], register: nil
mOoMoo		      # print ASCII character 10 (newline)					blocks: [[10], 3, 32, 47, 95, 94], register: nil
moOmoOmoOMoo	      # print ASCII character 47 (forward slash)				blocks: [10, 3, 32, [47], 95, 94], register: nil
mOomOoMMMMOOmoOMoomOoMOomoo # print n spaces							blocks: [10, [0], 32, 47, 95, 94], register: 3
moOmoOmoOMOoMOoMOo    # subtract 3 from 5th block						blocks: [10, 0, 32, 47, [92], 94], register: 3
Moo		      # print ASCII character 92 (backslash)					blocks: [10, 0, 32, 47, [92], 94], register: 3
mOomOomOomOoMoo	      # print newline								blocks: [[10], 0, 32, 47, 92, 94], register: 3
moOMMMmoOMMMMOOmoOmoOMoOmOomOoMOomooMMM # add 32 to 5th block					blocks: [10, 3, [32], 47, 124, 94], register: nil
moOmoOMMM             # copy 124 to register							blocks: [10, 3, 32, 47, [124], 94], register: 124
Moo	              # print ASCII character 124 (pipe)					blocks: [10, 3, 32, 47, [124], 94], register: 124
mOomOomOoMOOmoOMoomOoMOomoo # print n spaces							blocks: [10, [0], 32, 47, 124, 94], register: 124
MMMMoo	              # paste 124 to 2nd block and print as ASCII character			blocks: [10, [124], 32, 47, 124, 94], register: nil

```
> 3 votes

# Answer
# Ruby, 36 bytes

```
->n{" #{?_*n}
/#{a=" "*n}\\
|#{a}|"}

```

Try it online!
> 2 votes

# Answer
# C (gcc), ~~109~~ 91 bytes

Saved a whopping 18 bytes thanks to ceilingcat!!!

```
#define p printf(L"| |\\ / _ "+i)
i;j;f(n){for(i=9;i--;i--,p,puts(""))for(i-=p,j=n;j--;)p;}

```

Try it online!
> 2 votes

# Answer
# Scala, 47 bytes

```
n=>print(s" ${"_"*n}\n/${" "*n}\\\n|${" "*n}|")

```

## Longer version, 94 bytes

```
n=>print(Seq((' ',' ',"_"),('/','\\'," "),('|','|'," "))map(t=>t._1+t._3*n+t._2)mkString "\n")

```

Try them in Scastie
> 2 votes

# Answer
# Haskell, 58 bytes

```
f n|x<-' '<$[1..n]=' ':('_'<$x)++"\n/"++x++"\\\n|"++x++"|"

```

Try it online!
> 2 votes

# Answer
# Perl 5 `-p`, 40 bytes

```
say$"._ x$_,$/,$_='/'.$"x$_.'\\';y/ /|/c

```

Try it online!
> 2 votes

# Answer
# MATLAB/Octave, ~~36~~ 32 bytes

```
@(n)[' /|';'_  '+~(1:n)';' \|']'

```

Try it online!

Simple anonymous function that stitches together the first column ( `/|`), `n` middle columns (`_` ), and the final column ( `\|`), then returns the result.

Because the strings are rows rather than columns, everything is stitched together vertically, and then the result is transposed to get the desired orientation.

This works as trailing spaces are allowed, so a fully populated matrix can be formed. If trailing spaces were disallowed, the code would be 6 bytes longer by wrapping the result in `trim(...)`.

---

* Saved 4 bytes by duplicating the string literal using array expansion rather than with `repmat`. Thanks @LuisMendo.
> 2 votes

# Answer
# Husk, 17 bytes

```
TJR⁰"_  "½" /| ¦|

```

Try it online!

## Explanation

```
TJR⁰"_  "½" /| ¦|   Input is a number, say n = 3, accessed via ⁰.
          " /| ¦|   String literal " /| \|".
                    The parser replaces ¦ by \ and the closing " is implicit.
         ½          Split in half: x = [" /|", " \|"]
    "_  "           String literal.
  R⁰                Repeat n times: y = ["_  ", "_  ", "_  "]
 J                  Join x by this list: [" /|", "_  ", "_  ", "_  ", " \|"]
                    Since x and y are lists of strings, y is inserted between
                    each pair of elements in x and the result is flattened
                    to keep the types consistent.
T                   Transpose: [" ___ ", "/   \", "|   |"]
                    Implicitly print, separated by newlines.

```
> 2 votes

# Answer
# V (vim), 17 bytes

```
Àé_>>o/\Àé ÙÓÓ/|

```

```
Explain
À                  # @arg times
 é_                # <M-i>nsert a '_'
   >>              # indent by one space
     o/\           # insert '/\' on the next line (cursor stays at '\')
         Àé        # @arg times insert ' '
            Ù      # Duplicate this line down
             Ó /   # Find and replace ...
              Ó    # all Non-whitespace (\S == <M-S>)
                |  # with a '|'

```

Haven't done one of these in a while.

Try it online!
> 2 votes

# Answer
# MAWP v1.1, 92 bytes

```
%@_1A84W;[1A~25WWM~]%!![1A92W1M5W;]%67M;85W7M;[1A84W;]%45W3M4W;67M;65W1M4W;[1A84W;]65W1M4W;.

```

Try it!
> 2 votes

# Answer
# 1+, 174 bytes

```
."11+""*"**;1^<#[#(?|11##11+"1+""*""*+++;1+"\"/<1+1<1+#)]11+"""**+;11+"1+""""*++*+;1^<11++#(|?)[#(|11##11+""*"**;1+"\"/<1+1<1+#)]11+"1+"*""*++;11+"""**+;11+"*""1+""*+*+";()/;

```

Don't ask me how this work, I don't know at all!

I didn't yet try to golf it down (although I probably can offer a 50% discount on the bytecount when I have time), and there's still a lot of repetitions. But at least I made it.

1+ 174 vs 92 MAWP v1.1. Fiasco.
> 2 votes

# Answer
# Pepe, 118 bytes

```
REeEeEEEEErEeErREEeeeEReREEEEEEeRREeeEeeeeeReeereeEreeeEeEEEEREEEEeeEREEeeeEReeereeEeEEEeereeERrEeEEEEEeerreEeReeereEe

```

Try it online!
> 2 votes

# Answer
# Cinnamon Gum, 15 bytes

```
00000000: 70 05 1f 78 e5 2d 36 4e 0b 94 1d 5b d2 c7 fd

```

Try it online!
> 2 votes

# Answer
# Whispers v2, ~~148 135~~ 111 bytes

```
> Input
> "_"
> " "
> "/"
> "|"
> "\\"
>> 1⋅2
>> 3+7
>> 3⋅1
>> 4+9
>> 10+6
>> 5+9
>> 12+5
>> Output 8 11 13

```

Try it online!

This took much longer than expected to make.

-13 bytes from Michael Chatiskatzi.

-24 bytes from Leo.
> 2 votes

# Answer
# Whispers v2, 92 bytes

```
> 1
> Input
> " _\n/ \\\n| |"
>> Then 1 2 1 1 2 1 1 1 2 1
>> L⋅R
>> Each 5 4 3
>> Output 6

```

Try it online!

Sort of a run-length encoding.

Line 3 encodes the input without sequences of repeated characters. Line 4 builds the list of counts (1 is 1, 2 is the input). Line 6 combines them together repeating each character as many times as needed.
> 2 votes

# Answer
# Vyxal `j`, 18 bytes

```
\_2꘍f*` /|`vøṀ$¨vj

```

Try it online or verify all test cases.

## How?

```
\_2꘍f*` /|`vøṀ$¨vj
\_                 # Push "_"
  2꘍               # Append two spaces, making this "_  "
    f              # Convert to list of characters
     *             # Repeat each the input amount of times
      ` /|`        # Push string " /|"
          vøṀ      # For each (implicitly converting to a list), mirror it, flipping "/" to "\"
             $     # Swap
              ¨vj  # Join each in the other list by the corresponding value in the top list
                   # j flag joins on newlines

```
> 2 votes

# Answer
# Ruby, 57 bytes

```
n=gets.to_i
$><<' '+?_*n+" \n/"+' '*n+"\\\n|"+' '*n+'|'

```

Try It Online!
> 1 votes

# Answer
# Python 3, 57 bytes

```
lambda x:[print(z+y*x+a)for y,z,a in["_  "," /\\"," ||"]]

```

Try it online!
> 1 votes

# Answer
# C (gcc), 75 bytes

```
i;f(n){for(i=-1;n-i++;)putchar(i?95:32);printf("\n/%*c\n|%*c",i,92,i,124);}

```

Try it online!
> 1 votes

# Answer
# Perl 6, 49 bytes

Edit: -4 bytes

```
->$n {my$s=" "x$n;my$u="_"x$n;" $u\n/$s\\\n|$s|"}

```

Try it online!
> 1 votes

# Answer
# Io, 127 bytes

```
method(x,list(" _ ","/ \\","| |")map(i,list(i at(0)asCharacter,i at(1)asCharacter repeated(x),i at(2)asCharacter)join println))

```

Try it online!
> 1 votes

# Answer
# PHP, ~~63~~ ~~61~~ 60 bytes

```
$a=++$argn;printf("%-'_{$a}s
/%{$a}s
|%{$a}s",' ','\\','|');

```

Try it online!

`printf` seemed the optimal way, but I may be wrong..

EDIT: saved 2 bytes with a multiline string

EDIT 2: saved another one by init `$a` before
> 1 votes

# Answer
# Perl 5 `-p`, 32 bytes

```
$#_=$_;$_=$"._ x$_."
/@_\\
|@_|"

```

Try it online!

## Explanation

Pretty straightforward, but the first part of this sets the last index of the undefined list `@_` to the (implicit from `-p`) input (`$_`). `$_` is then set to `$"` (space) followed by `$_` `_`s, a literal newline, then `/`, and the interpolated empty list `@_` that has a length of `$_`+1 which, when interpolated in a double quoted string places `$"` between each (empty) entry, resulting in `$_` spaces, then `\`, a literal newline, then the same mechanism for the final line but using `|`.
> 1 votes

# Answer
# Retina, 22 bytes

```
.+
 $0*_¶/$0* \¶|$0* |

```

Try it online or verify a few more test cases.

Pretty straight-forward: convert the input to unary, using that amount of '\_' (`$0*_`) and two times that amount of spaces (`$0*` ) respectively, surrounded with the rest of the output (leading space on the first line; surrounded with `/\` on the second line; and surrounded with `||` on the third line).
> 1 votes

# Answer
# Whitespace, 243 bytes

```
[S S S T    S T T   T   S S N
_Push_92_|][S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][N
S S N
_Create_Label_LOOP1][S N
S _Duplicate][N
T   S S N
_If_0_Jump_to_Label_DONE_WITH_LOOP1][S S S T    N
_Push_1][T  S S T   _Subtract][S S S N
_Push_0_space][S N
T   _Swap_top_two][N
S N
N
_Jump_to_Label_LOOP1][N
S S S N
_Create_Label_DONE_WITH_LOOP1][S N
N
_Discard_top][S S S T   S T T   T   S S N
_Push_92_|][S S T   T   S T T   S N
_Push_-22_newline][S S S T  T   T   T   S S N
_Push_60_\][S S S N
_Push_0][T  T   T   _Retrieve_input][N
S S T   N
_Create_Label_LOOP2][S N
S _Duplicate][N
T   S S S N
_If_0_Jump_to_Label_DONE_WITH_LOOP2][S S S T    N
_Push_1][T  S S T   _Subtract][S S S N
_Push_0_space][S N
T   _Swap_top_two][N
S N
T   N
_Jump_to_Label_LOOP2][N
S S S S N
_Create_Label_DONE_WITH_LOOP2][S N
N
_Discard_top][S S S T   T   T   T   N
_Push_15_/][S S T   T   S T T   S N
_Push_-22_newline][S S S N
_Push_0][T  T   T   _Retrieve_input][N
S S S T N
_Create_Label_LOOP3][S N
S _Duplicate][N
T   S T S N
_If_0_Jump_to_Label_PRINT_LOOP][S S S T N
_Push_1][T  S S T   _Subtract][S S S T  T   T   T   T   T   N
_Push_63__][S N
T   _Swap_top_two][N
S N
S T N
_Jump_to_Label_LOOP3][N
S S T   S N
_Create_Label_DONE_WITH_LOOP3][S S S T  S S S S S N
_Push_32][T S S S _Add][T   N
S S _Print_as_character][N
S N
T   S N
_Jump_to_Label_PRINT_LOOP]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Push the codepoint of "|", minus the constant 32
Integer n = STDIN as integer
Integer t = n
LOOP1:
  If(t == 0):
    Jump to DONE_WITH_LOOP1
  t = t - 1
  Push codepoint of " ", minus the constant 32
DONE_WITH_LOOP1:
  Discard t
  Push "|\n\", minus the constant 32
  Integer t = n
LOOP2:
  If(t == 0):
    Jump to DONE_WITH_LOOP2
  t = t - 1
  Push codepoint of " ", minus the constant 32
DONE_WITH_LOOP2:
  Discard t
  Push "/\n"
  Integer t = n
LOOP3:
  If(t == 0):
    Jump to PRINT_LOOP
  t = t - 1
  Push codepoint of "_", minus the constant 32
PRINT_LOOP:
  (note, we don't discard t this time, since we need the codepoint of " " minus 32
   for the trailing character, which is just like t also 0)
  Print the top value + constant 32 as character to STDOUT
  Go to the next iteration of PRINT_LOOP

```

Uses this Whitespace tip of mine to print the output after pushing the characters in reversed order minus a certain constant, which will exit the program with an error as soon as we're done with printing and the stack is empty. The optimal constant `32` is generated by this Java program (based on \\$n=1\\$).
> 1 votes

# Answer
# brainfuck, 174 bytes

only works with input from 0 to 9, didn't think about this problem while writing the program

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

```

Try it online!

## comments

```
++++[>++++<-]>  store 16 in cell 0
[               while cell 0 != 0
    -           cell 0 remove 1   total 0
    >++++++++   cell 1 add    8   total 128
    >+++        cell 2 add    3   total 48
    >++         cell 3 add    2   total 32
    >>          leave 2 empty cells
    >++++++     cell 6 add    6   total 96
    >++++++     cell 7 add    6   total 96
    >+          cell 8 add    1   total 16
    >+++        cell 9 add    3   total 48
    <<<<<<<<<   return to cell 0
]
>---->->>>,>->---->------ ajust cells to 0 124 47 32 0 0 92 95 10 48
                                            |   / space   \  _ \n  0
                          and take input into cell 5
>[-<<<<->>>>]             remove 48 from cell 5
                          transforming the digit character into the numeric value
<<<<<<.                   print a space
>>[->.<<+>]               print n times _
>>>.                      print a new line
<<<<<<.                   print /
>>[-<.>>+<]               print n spaces
>>>.                      print \
>.                        print a new line
<<<<<<<.                  print |
>>>>[-<+<.>>]             print n spaces
<<<<.                     print |

```

# brainfuck, 359 bytes, with input up to 255

input must take 3 characters, e.g. `42` must be inputted as `042`

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

```

Try it online!

```
Create characters

++++[>++++<-]>  store 16 in cell 0
[               while cell 0 != 0
    -           cell 0 remove 1   total 0
    >++++++++   cell 1 add    8   total 128
    >+++        cell 2 add    3   total 48
    >++         cell 3 add    2   total 32
    >>          leave 2 empty cells
    >++++++     cell 6 add    6   total 96
    >++++++     cell 7 add    6   total 96
    >+          cell 8 add    1   total 16
    <<<<<<<<   return to cell 0
]
>---->->>>>->---->------  ajust cells to 0 124 47 32 0 0 92 95 10
                                            |   / space   \  _ \n

Input

>++++++++[->++++++<]>>-[>++<-----]>--<,>>,>++++++++++>,
    set cells :
        10 to 48
        11 to input 1
        12 to 100
        13 to input 2
        14 to 10
        15 to input 3
<<<<<                                move to cell 10
[->->>->>-<<<<<]                     remove 48 to cells 10 11 13 and 15
                                     getting digits from the characters
>[->[-<<+<+>>>]<<<[->>>+<<<]>>]      set cell 10 to cell 11 times cell 12
>[-]>[-<<+>>]>[-<<+>>]>[-<<+>>]<<<<< move cells 13 14 and 15 to cells 11 12 and 13
>[->[-<<+<+>>>]<<<[->>>+<<<]>>]      add cell 11 times cell 12 to cell 10
>>[-<<<+>>>]<<<                      add cell 13 to cell 10
[-<<<<<+>>>>>]                       move cell 10 to cell 5

Actual drawings

<<<<<<<.                  print a space
>>[->.<<+>]               print n times _
>>>.                      print a new line
<<<<<<.                   print /
>>[-<.>>+<]               print n spaces
>>>.                      print \
>.                        print a new line
<<<<<<<.                  print |
>>>>[-<+<.>>]             print n spaces
<<<<.                     print |

```

# brainfuck, 155 bytes, With input as brainfuck byte

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

```

Try it online!

++++[>++++<-]>  store 16 in cell 0
[               while cell 0 != 0
    -           cell 0 remove 1   total 0
    >++++++++   cell 1 add    8   total 128
    >+++        cell 2 add    3   total 48
    >++         cell 3 add    2   total 32
    >>          leave 2 empty cells
    >++++++     cell 6 add    6   total 96
    >++++++     cell 7 add    6   total 96
    >+          cell 8 add    1   total 16
    <<<<<<<<    return to cell 0
]
>---->->>>,>->---->------ ajust cells to 0 124 47 32 0 0 92 95 10
                                            |   / space   \  _ \n
                          and take input into cell 5

<<<<<.                    print a space
>>[->.<<+>]               print n times _
>>>.                      print a new line
<<<<<<.                   print /
>>[-<.>>+<]               print n spaces
>>>.                      print \
>.                        print a new line
<<<<<<<.                  print |
>>>>[-<+<.>>]             print n spaces
<<<<.                     print |
```
</code></pre>
> 1 votes

# Answer
# Python 3, 50 bytes

```
lambda x:print(f" {'_'*x}\n/{' '*x}\\\n|{' '*x}|")

```

---

if returning the string is acceptable instead of printing it it'd be 43 bytes

```
lambda x:f" {'_'*x}\n/{' '*x}\\\n|{' '*x}|"

```
> 1 votes

# Answer
# C#, 97 bytes

```
string X(int n)=>$@" {R(n,'_')}
/{R(n)}\
|{R(n)}|";string R(int n,char c=' ')=>new string(c,n);

```

Try it online!
> 1 votes

# Answer
# , 74 bytes

```
cat(" ",rep("_",n<-scan()),"\n","/",s<-rep(" ",n),"\\\n","|",s,"|",sep="")

```

Try it online!

I hit a dead end trying to golf this at 77 bytes (or even this).
> 1 votes

# Answer
# MAWP 2.0, ~~43~~ 41 bytes

```
32;@!"_"*:10;47;!" "*:92;10;"|":" "*:"|":

```

Try it!
> 1 votes

# Answer
# CJam, 25 bytes

```
S'_qi:A*N'/' A*:Z'\N'|Z'|

```

Try it online!

Explanation:

```
S                           Push a space
 '_                         Push an underscore
   qi:A                     Push input and assign it to the variable A
       *                    Repeat underscores A times
        N                   Push a newline
         '/                 Push a slash
           ' A*:Z           Push a space repeated A times ad assign that to variable Z
                 '\N'|      Push a backslash, newline and |
                      Z     Push variable Z
                       '|   Push a |

```
> 1 votes

# Answer
# Excel, 58 bytes

```
=" "&REPT("_",A1)&"
/"&REPT(" ",A1)&"\
|"&REPT(" ",A1)&"|"

```

Straightforward implementation. The line breaks are inside strings to they'll print.

Once the input is large enough, it is difficult to display the entire thing.
> 1 votes

# Answer
# \>\<\>, 97 bytes

```
<vo" "::+1
o>"_"$1-:@?!v
/\  v~ooa"/"<
!^o:>~" "$1-:@?
" "$1-:@?!vo:>~
\"|"a"\"oo o~^
     ;o"|"/

```

Takes input on the stack.

Could probably be golfed further.
> 1 votes

# Answer
# Canvas, 12 bytes

```
½Ｕ_× ¶\¶|＋↔│

```

Try it here!
> 1 votes

# Answer
# Forth (gforth), <sup>~~97~~</sup> 89 bytes

```
: e emit ; : b space dup 0 ?do 95 e loop cr 47 e dup spaces 92 e cr 124 e spaces 124 e ;

```

Try it online!

-8 bytes from Bubbler.

~~Forth goes into infinite loops when given 0 for a `do loop`, since every loop must run atleast once. So a for loop with an if statement is used.~~  Otherwise, this function is pretty straightforward.
> 1 votes

# Answer
# Batch ~~154~~ ~~151~~ ~~143~~ ~~133~~ 123 bytes

**Notes:**

* start from `cmd.exe`'s command line with arg `%1` as integer
* Output will be line wrapped unless console is resized to a number of columns that supports `%1`
* line `1` has a trailing `Space`
* Requires windows 10 / virtual terminal support
* **`ESC`** is a stand in for the ansii escape character 0x027
* Raw code including the character can be found here
    + Or the character can be generated by opening the command prompt and typing:
        - `>"%TEMP%\escape.chr" Echo(``ALT`+`027` then pressing `ENTER`
    + Or output using a for loop with `Echo off`:
        - `(For /F "skip=4 DELIMS=" %a in ('Echo(prompt $E^|cmd')Do Echo(%a) >"%TEMP%\escape.chr"`

```
@Set o=@^<nul set/P
@Set "f=&@(for /l %%p in (1 1 %1)do %o%"
%o%=ESCB %f%=_)&%o%=ESC[1E/%f%=ESC[s )&%o%=\ESC[1E^|%f%=ESC7 )&%o%=^|

```

How:

* virtual teminal positioning codes to position cursor for wall pieces and to effect new lines (`ESC[1E`) where needed.
* a for loop macro outputs the crest and whitespace between wall sides -'`ESC7``Space`' is used to allow leading whitespace to be output using `<nul set /p =string`
* Cursor positioning is enacted relative to the initial cursor position
> 1 votes

# Answer
# Pyth, 28 bytes

```
%" %s\n/%s\\\n|%s|"m*dQ(\_dd

```

Port of @xnor's Python 2 solution.

Try it online!
> 1 votes

# Answer
# JavaScript, 59 bytes

```
f=n=>n?f(n-1).replace(/.\n/g,c=>' _'[c<1|0]+c):`
/\\
||
`

```

Try it online!

A recursive function. Uses how JS coerces whitespace to 0, and punctuation to NaN.

Not as competitive as Arnauld's JS answers, but I think it's still interesting.
> 1 votes

# Answer
# Python 3, 58 55 bytes

```
lambda n:f" {'_'*n if n else''}\n/{' '*n}\\\n|{' '*n}|"

```

Try it online!

Simple f-string
> 1 votes

# Answer
# Ly, ~~42~~ 31 bytes

```
"| |\ / - "nsp[ol[f:of,]ppo9`o]

```

Try it online!

This version is shorter using a completely different algorithm. It pushes 3 characters that define what each output line should look like. The leading char, the repeated char, and the closing char. After pushing those triplets to the stack, the code loops until the stack is empty. Each time through the loop prints one line, with an inner loop to generate the repeating characters.

```
"| |\ \ - "                     - Push 3-char loop instructions
           nsp                  - Read the number, store and delete
              [               ] - Loop once per output line
               o                - print the leading char
                l[     ]p       - load the number, loop that many times
                  f             - pull the char to print forward
                   :o           - duplicate and print
                     f          - pull the iterator number forward
                      ,         - decrement
                         p      - delete the char
                          o     - print closing char
                           9`o  - push a LF and print it

```
> 1 votes

# Answer
# Bash, 53 bytes

```
printf -v v %$1s;echo -e " ${v// /_} \n/$v\\\\\n|$v|"

```

Try it online!
> 0 votes

# Answer
# Factor, + `sequences.repeating` 56 bytes

```
[ "_"over cycle " "rot cycle dup [I  ${}
/${}\
|${}|I] ]

```

Attempt This Online!

```
       ! 5
"_"    ! 5 "_"
over   ! 5 "_" 5
cycle  ! 5 "_____"
" "    ! 5 "_____" " "
rot    ! "_____" " " 5
cycle  ! "_____" "     "
dup    ! "_____" "     " "     "

```

And the rest just interpolates the strings on the data stack into the `${}` and prints it out.
> 0 votes

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


title: Sierpinski Carpets

text:
# Question
Title: Sierpinski Carpets
Who doesn't love a good fractal? The Sierpinski Carpet is a classic example of a fractal.

To complete this task, you will be required to generate a carpet of type \\$n\\$ and print the resulting image to the `stdout` (see example below for formatting) \\$n\\$, representing the level carpet. Steps can be found on this Wikipedia article.

This value will be taken from `stdin` or equivalent.

For example, an input of 4 would produce a level 4 carpet:

```
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■   ■ ■   ■ ■   ■ ■   ■ ■   ■ ■   ■ ■   ■ ■   ■ ■   ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■       ■ ■ ■ ■ ■ ■       ■ ■ ■ ■ ■ ■       ■ ■ ■
■   ■       ■   ■ ■   ■       ■   ■ ■   ■       ■   ■
■ ■ ■       ■ ■ ■ ■ ■ ■       ■ ■ ■ ■ ■ ■       ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■   ■ ■   ■ ■   ■ ■   ■ ■   ■ ■   ■ ■   ■ ■   ■ ■   ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■                   ■ ■ ■ ■ ■ ■ ■ ■ ■
■   ■ ■   ■ ■   ■                   ■   ■ ■   ■ ■   ■
■ ■ ■ ■ ■ ■ ■ ■ ■                   ■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■       ■ ■ ■                   ■ ■ ■       ■ ■ ■
■   ■       ■   ■                   ■   ■       ■   ■
■ ■ ■       ■ ■ ■                   ■ ■ ■       ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■                   ■ ■ ■ ■ ■ ■ ■ ■ ■
■   ■ ■   ■ ■   ■                   ■   ■ ■   ■ ■   ■
■ ■ ■ ■ ■ ■ ■ ■ ■                   ■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■   ■ ■   ■ ■   ■ ■   ■ ■   ■ ■   ■ ■   ■ ■   ■ ■   ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■       ■ ■ ■ ■ ■ ■       ■ ■ ■ ■ ■ ■       ■ ■ ■
■   ■       ■   ■ ■   ■       ■   ■ ■   ■       ■   ■
■ ■ ■       ■ ■ ■ ■ ■ ■       ■ ■ ■ ■ ■ ■       ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■   ■ ■   ■ ■   ■ ■   ■ ■   ■ ■   ■ ■   ■ ■   ■ ■   ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■

```

An input of 3 would produce a level 3 carpet:

```
■ ■ ■ ■ ■ ■ ■ ■ ■
■   ■ ■   ■ ■   ■
■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■       ■ ■ ■
■   ■       ■   ■
■ ■ ■       ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■
■   ■ ■   ■ ■   ■
■ ■ ■ ■ ■ ■ ■ ■ ■

```

An input of 2 would produce a level 2 carpet:

```
■ ■ ■
■   ■
■ ■ ■

```

And a input of 1 would produce a level 1 carpet (just a square):

Note the spaces between the columns.

The idea is to use the ■ character for blocks and space for gaps

The line starts with the ■ character.

As always, the smallest solution wins by character count (due to non-standard characters).

Alternatively, # can be used instead of the ■ character in languages that do not support Unicode.

# Answer
> 16 votes
## CJam, ~~38~~ ~~37~~ ~~31~~ ~~30~~ 28 characters

Oh well, we're counting by characters, so let's do some Unicode unpacking:

```
"B胷맋풽巓뱖ᮨ㣙¬䙧੥墱륋청"2G#b129b:c~

```

Test it here. Just put the desired level into the input field.

### Explanation

After base conversion, this is

```
3li(#,{3b1f&2b}%_f{f{&S9632c?S}N}

```

which is the same as the following, just with the Unicode character written as `9632c`:

```
3li(#,{3b1f&2b}%_f{f{&S'■?S}N}

```

This code is based on the following observation: if we look at the coordinates *(x,y)* of each cell, then we get an empty cell, whenever both *x* and *y* have a `1` at the same position in their base-3 representation. If you think about it, the small-scale repeating pattern is the significant base-3 digit, then the next more significant digit governs the next larger-scale repetition and so on.

```
3                                      "Push a 3 on the stack.";
 li(                                   "Read input, convert to integer, decrement.";
    #                                  "Raise to that power. This yields the dimensions.";
     ,                                 "Turn into a range array.";
      {       }%                       "Map the block onto the array.";
       3b                              "Convert to base 3.";
         1f&                           "Bit-wise AND each digit with 1.";
            2b                         "Convert to base 2.";
                _                      "Duplicate this list.";
                 f{          }         "Map this block onto one list, with the second list
                                        as an additional parameter.";
                   f{      }           "Map this block onto the second list, with the first
                                        list's current element as an additional parameter.";
                                       "I.e. this iterates over all coordinate pairs.";
                     &                 "Bitwise AND to check that the base-3 representations
                                        had a 1 in the same position.";
                      S'■?             "Select the right character.";
                          S            "Push a space.";
                            N          "Push a newline";

```

The contents of the resulting array are printed automatically.

Thanks to Dennis for shaving off three bytes.

# Answer
> 7 votes
# Matlab (113)(110)(99)(85)

You can try it here (You'll have to replace `input('')` with your desired input.)

Now 99 thanks to feersum! And now down to 85 thanks to RTL!

Golfed:

```
a=ones(3);a(5)=0;c=1;for i=2:input('');c=kron(c,a);end;disp(char(kron(c,[1,0])*3+32))

```

Ungolfed:

```
a=ones(3);a(5)=0;c=1;  %creating the template / anchor
for i=2:input('');
    c=kron(c,a);       %recursive iterations
end;
disp(char(kron(c,[1,0])*3+32))

```

```
d=[c,c]*0;  %this is all just for adding the additional spaces
d(:,1:2:end)=c;
disp(char(d*3+32));    %converting to spaces (32) and # (35)

```

Explanation:

I am abusing the kronecker product for this task. (It is a special product defined for two each arbitrary sized matrices. Example:

```
A = [1,2] is a 3x2 matrix, B is a nxm matrix.
    [3,4]
    [5,6]

```

Then

```
kron(A,B) = [1*B , 2*B] is a 2n x 2m matrix.
            [3*B , 4*B]
            [5*B , 6*B]

```

So heres an example for n=5 (In the old counting method it's 4);

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

```

# Answer
> 6 votes
# Haskell, ~~114~~ 108

```
s 1=["# "]
s n=k j++k(map(>>" ")j)++k j where j=s$n-1;k i=j%i%j
(%)=zipWith(++)
main=interact$unlines.s.read

```

# Answer
> 6 votes
# Perl 5: 68 characters

*n* on stdin.

```
#!/usr/bin/perl -l
//,print map/2/?"  ":"■ ",map$_+$',@,for@,=grep!/[24-9]/,0..3x<>/10

```

A decimal coded ternary representation of the list of coordinates is first generated in `@,` (name chosen so there is no need for space between `@,` and `for`) using digits 0, 1, and 3. Now adding x and y coordinates in the decimal domain will have a 2 in the result if and only if there were two ones at matching positions. `//` is used to propagate the default variable `$_` from the outer loop (`for`) to the postmatch variable `$'` when it is shadowed by the default `map` variable in the inner loop.

# Answer
> 5 votes
# Python – 100

```
r=range(3**~-input())
for i in r:print" ".join("# "[any(i/3**k%3==j/3**k%3==1for k in r)]for j in r)

```

# Answer
> 4 votes
# Racket ~~230~~ ~~229~~ ~~225~~ 220

Not Racket's finest hour for golfing.

Golfed:

```
(define(s n)(letrec([t(λ(x y)(if(or(= x 0)(= y 0))"■"(if(=(modulo x 3)(modulo y 3)1)" "(t(floor(/ x 3))(floor(/ y 3))))))][i(expt 3(- n 1))])(for-each displayln(for/list([r i])(string-join(for/list([c i])(t r c))" ")))))

```

Ungolfed:

```
(define (s n)
  (letrec ([t (λ (x y)
                (if (or (= x 0) (= y 0))
                    "■"
                    (if (= (modulo x 3) (modulo y 3) 1)
                        " "
                        (t (floor (/ x 3)) (floor (/ y 3))))))]
           [i (expt 3 (- n 1))])
    (for-each displayln
              (for/list ([r i])
                (string-join
                 (for/list ([c i])
                   (t r c)) " ")))))

```

# Answer
> 4 votes
# C: 123 118 111 104 characters

Based on a similar idea as my perl solution. After adding some spaces:

```
m=0x55555555;
x;
main(n){
  scanf("%d",&n);
  n=1<<2*--n;
  for(x=n*n;x--;)
    printf(x&x/2&m?"":"%c%c",x&x/n&m?32:35,x&n-1?32:10);
}

```

Uses ternary system coding each digit with 2 bits. Illegal values (having two ones in odd-even position) are filtered with `x & (x>>1) & 0b01010101`. Both coordinates are stored in one value, so checking the pixel color is down to `x & (x >> 2 * n) & 0b01010101`. `n` is stored as a power of 2 for convenience.

## Edit

Replaced `define` with a simple constant `m`.

## Edit 2

`0x5555555` mask can be represented with `(1LL<<32)/3`, but we only need `n` of those bits so `n/3` is sufficient.

```
x;
main(n){
  scanf("%d",&n);
  n=1<<2*--n;
  for(x=n*n;x--;)
    printf(x&x/2&n*n/3?"":"%c%c",x&x/n&n/3?32:35,x&n-1?32:10);
}

```

## Edit 3

Minor tweaks. One 2 char gain relying on scanf being executed before the loading value of `n` for the execution of `--n`. The eol can only follow `#`, duh.

```
x;
main(n){
  n=scanf("%d",&n)<<2*--n;
  for(x=n*n;x--;)
    x&x/2&n*n/3||printf(x&x/n&n/3?"  ":x&n-1?"# ":"#\n");
}

```

# Answer
> 4 votes
# Mathematica, 71 bytes

```
Grid@Nest[ArrayFlatten@ArrayPad[{{0}},1,{{#}}]&,1,#]/.{0->"",1->"■"}&

```

**input**

> 3

**output**

# Answer
> 3 votes
# HTML/JavaScript, 205 Chars

## Obfuscatweet, 205 Chars

```
document.write(unescape(escape('').replace(/uD./g,'')))

```

## HTML/JS, 298 Chars

Due to how HTML plays with whitespace, a few characters had to be dedicated to the nbsp char. In addition, the default font of most browsers is not Courier, so I had to set it to that, too. About 20 characters worth of styling. If this requires a direct input method, I can add it, but changing the input currently is setting n to a different value.

Demo

```
<script>s=' ';n=4;m=Math.pow(3,n-1);for(i=0;i<m;i++,d('<br>')){for(j=0;j<m;)if(c(i,j++))d('#');else d(s)}function c(x,y){while(x||y){if(x%3==1&&y%3==1)return 0;x=f(x);y=f(y)}return 1}function f(a){return Math.floor(a/3)}function d(a){document.write(s+a)}</script><style>*{font-family:"Courier"

```

## Readable HTML/JS

```
<script>
    s=' ';
    n=4;
    m=Math.pow(3,n-1);
    for(i=0;i<m;i++,d('<br>')){
        for(j=0;j<m;)
            if(c(i,j++))
                d('#');
            else d(s)
    }
    function c(x,y){
        while(x||y){
            if(x%3==1&&y%3==1)
                return 0;
            x=f(x);
            y=f(y)
        }
        return 1
    }
    function f(a){
        return Math.floor(a/3)
    }
    function d(a){
        document.write(s+a)
        }
</script>
<style>
*{font-family:"Courier"

```

# Answer
> 3 votes
# CJam, ~~38~~ ~~35~~ ~~32~~ 31 characters

```
"■ ""՛ୗ䁎뽔휼ꆩ闳⾿➺⥧槲㩡郊"6e4b128b:c~

```

Try it online.

### Example run

```
$ cjam <(echo '"■ ""՛ୗ䁎뽔휼ꆩ闳⾿➺⥧槲㩡郊"6e4b128b:c~') <<< 3; echo
■ ■ ■ ■ ■ ■ ■ ■ ■
■   ■ ■   ■ ■   ■
■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■       ■ ■ ■
■   ■       ■   ■
■ ■ ■       ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■
■   ■ ■   ■ ■   ■
■ ■ ■ ■ ■ ■ ■ ■ ■

```

### How it works

```
"՛ୗ䁎뽔휼ꆩ闳⾿➺⥧槲㩡郊"6e4b128b:c~

```

converts the Unicode string from base 60,000 (`6e4b`) to base 128 (`128b`), casts to Character (`:c`) and evaluates the resulting string (`~`).

As a result, the following code gets executed:

```
"■ "                                " C := '■ '                                           ";
    li(                             " J := int(input()) - 1                               ";
       {                      }*    " for I in range(J):                                  ";
        z]A*                        "   T := [zip(C)] * 10                                ";
            ):,                     "   U := pop(T)                                       ";
               Sf*                  "   V := [ ' ' * len(u) : u ∊ U ]                     ";
                  4\t               "   U[4] := V                                         ";
                     3/{:+z~}%      "   C := { c : c ∊ zip(concat(u)), u ∊ U.split(3) }   ";
                              zN*  " print '\n'.join(zip(C))                              ";

```

# Answer
> 3 votes
# Python 3 – ~~116~~ 113 characters

**EDIT:** Well, used the trick I don't like too much myself and compressed the code by 3 bytes. Dunno if that's the best possible way, but I'll go with it.

```
exec(bytes('ⱴ㵬❛離₠崧氬浡摢㩺癥污稨✫潦⁲湩琠❝਩潦⁲湩爠湡敧椨瑮椨灮瑵⤨⴩⤱爺瀬氽✨㍛✪Ⱙ⡬嬢⭫‧✠⠪⨳椪⬩⤢琻爽瀫爫昊牯椠椠㩴牰湩⡴⥩','utf-16')[2:].decode('utf-8'))

```

It may contain some unprintable characters, so here's a printable version of the string.

```
'ⱴ㵬❛離₠崧氬浡摢\u2061㩺癥污稨✫\u206b潦\u2072\u206b湩琠❝\u0a29潦\u2072\u2069湩爠湡敧椨瑮椨灮瑵⤨\u2d29⤱爺瀬氽✨㍛✪Ⱙ⡬嬢\u2b6b‧✠⠪⨳椪⬩⤢琻爽瀫爫昊牯椠椠\u206e㩴牰湩⡴⥩'

```

Not too great, but at least beats some languages.

What it expands to:

```
t=['■ ']
for i in range(int(input())-1):r,p=[k*3for k in t],[k+'  '*(3**i)+k for k in t];t=r+p+r
for i in t:print(i)

```

Somewhat ungolfed in case someone can't see how it works:

```
t=['■ ']                                     # iteration 1
for i in range(int(input()) - 1):            # do n-1 more iterations
    r = [k * 3 for k in t]                   # first & last rows are the last carpet x3
    p = [k + '  ' * (3 ** i) + k for k in t] # middle row: last carpet, space, last carpet
    t = r + p + r                            # and put them to the new carpet
for i in t:                                  # print final iteration
    print(i)

```

# Answer
> 2 votes
## CJam, 76 characters

```
3ri(#:M_*,{_M/:I\M%:J;;{I3%1=J3%1=&0X?:X;I3/:I0>J3/:J0>|}gX'■S?1:X;}%M/Sf*N*

```

This is a direct translation of the formula given here

Try it here

# Answer
> 2 votes
# C - 154

Input from stdin. I tried to find a good way to avoid an extra function, but couldn't come up with any.

The character count includes only necessary spaces.

```
p(l,x,y){
    return l?x/l&y/l&1||p(l/3,x%l,y%l):0;
}
x,y;
main(v){
    scanf("%d",&v);
    v=pow(3,--v);
    for(;y<v;y++,puts(""))
        for(x=0;x<v;)
            printf("%c ",p(v,x++,y)?32:35);
}

```

# Answer
> 2 votes
# Bash+coreutils, 105 unicode characters

Since we're counting characters and not bytes:

```
eval `iconv -tunicode<<<潦⡲眨㌽⨪␨ⴱ⤱琬〽琻眼眪琻⬫⤩笻戠ꂖ昻牯⠨㵸╴ⱷ㵹⽴㭷㹸簰祼〾砻㴯ⰳ⽹㌽⤩笻⠠砨㌥ㄭ籼╹ⴳ⤱簩扼尽簠硼〽紻瀻楲瑮␢㬢⠨╴⵷⭷⤱簩敼档㭯੽|cut -b3-`

```

---

In its decoded form:

# Pure Bash, 143 bytes

```
for((w=3**($1-1),t=0;t<w*w;t++));{
b=■
for((x=t%w,y=t/w;x>0||y>0;x/=3,y/=3));{
((x%3-1||y%3-1))||b=\ ||x=0
}
printf "$b "
((t%w-w+1))||echo
}

```

Input is taken from command-line args:

### Output:

```
$ ./sierpinskicarpet.sh 3
■ ■ ■ ■ ■ ■ ■ ■ ■
■   ■ ■   ■ ■   ■
■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■       ■ ■ ■
■   ■       ■   ■
■ ■ ■       ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■
■   ■ ■   ■ ■   ■
■ ■ ■ ■ ■ ■ ■ ■ ■
$

```

# Answer
> 2 votes
# oK, ~~40~~ 45 bytes

```
`0:" "/'" #"{(x-1)(,'//3 3#111101111b*9#,)/1}

```

Try it online.

It starts with `1`, and then draws it in a grid `(1 1 1;1 0 1;1 1 1)`, which it then draws in a grid the same way, etc. repeated the necessary number of times.

# Answer
> 2 votes
# Python 2, 91 bytes

```
r=input()-1
for i in range(3**r):x,s='# ','  ';exec"x+=[x,s][i%3%2]+x;s*=3;i/=3;"*r;print x

```

Try it online!

# Answer
> 2 votes
# Jelly, 17 bytes

```
’3*Ḷb3ḂḄ&þ`¬ị⁾# G

```

**Try it online!**

### How?

```
’3*Ḷb3ḂḄ&þ`¬ị⁾# G - Link: integer, n
’                 - decrement -> n-1
 3*               - three raised to (that)
   Ḷ              - lowered range -> [0,1,...,3^(n-1)-1]
    b3            - convert to base three (vectorises)
      Ḃ           - least significant bit (vectorises) -> i.e. make 2 trits become 0s
       Ḅ          - convert from base two (vectorises)
          `       - use that as both arguments of:
         þ        -   outer product with:
        &         -     bitwise AND
           ¬      - logical NOT (vectorises)
            ị     - index into:
             ⁾#   -   list of characters ['#', ' ']
                G - format as a grid

```

# Answer
> 2 votes
# Haskell, 77 characters

```
f n|a<-mapM(:[0,1])[2..n]=[do x<-a;"■ "!!(0^product(zipWith(+)x y)):" "|y<-a]

```

Try it online!

# Answer
> 1 votes
# PHP, 194 characters

The `n` received as first argument in command line.

```
<?php
function d(&$a,$n,$e,$x,$y){if(--$n)for(;$i<9;)$p=pow(3,$n)|d($a,$n,$e|$i==4,$x+$p*$j,$y+$p*($i-$j)/3)|$j=++$i%3;else$a[$x][$y]=$e?" ":■;}@d($a,$argv[1]);foreach($a as$s)echo join($s),"
";

```

## Readable

```
<?php

function draw(&$array, $n, $empty, $x, $y) {
    $n--;
    if ($n != 0) {
        for ($i = 0; $i < 9; $i++) {
            $j = $i % 3;
            $p = pow(3, $n);
            draw($array, $n, $empty || $i == 4, $x + $p * $j, $y + $p * ($i - $j) / 3);
        }
    } else {
        $array[$x][$y] = $empty ? " " : "#";
    }
}

$array = array();
draw($array, $argv[1], false, 0, 0);
foreach ($array as $line) {
    echo join($line), "\n";
}

```

# Answer
> 1 votes
**Scala 230 characters**

Golfed code:

```
object T extends App {def m=math.pow(3,args(0).toInt-1).toInt-1;def p=print _;val x=0 to m;x.map{n=>x.map{j=>if(q(n,j)==1)p(" #");else p("  ")};p("\n");};def q(n:Int,j:Int):Int={if(n>0|j>0)if((n%3&j%3)==1)0 else q(n/3,j/3)else 1}}

```

Ungolfed code:

```
object T extends App {
  def m = math.pow(3, args(0).toInt - 1).toInt - 1;

  def p = print _;
  val x = 0 to m;
  x.map { n => x.map { j => if (q(n, j) == 1) p(" #"); else p("  ")}; p("\n");};

  def q(n: Int, j: Int): Int = {
    if (n > 0 | j > 0) if ((n % 3 & j % 3) == 1) 0 else q(n / 3, j / 3) else 1
  }
}

```

Only necessary spaces are included.

# Answer
> 1 votes
# SOGL V0.12, 27 bytes

```
 ■¹.H{³³┼┼≥: ■@ŗ;┼┼⁴++}{@∑P

```

Try it Here!

# Answer
> 1 votes
# C# (.NET Core), 162 bytes

```
n=>{var f="";int s=(int)Math.Pow(3,n),z=0;while(z<s*s){int x=z%s,y=z/s,h=1;for(;x>0|y>0;y/=3,x/=3)if(y%3==1&x%3==1)h=0;f+=" #"[h]+(z++%s<s-1?" ":"\n");}return f;}

```

Try it online!

### Degolfed

```
n=>{
    var f="";
    int s=(int)Math.Pow(3,n),z=0;

    while(z<s*s)
    {
        int x=z%s, y=z/s, h=1;
        for(; x>0 | y>0; y/=3, x/=3)
            if(y%3==1 & x%3==1)
                h=0;

        f += " #"[h] + (z++%s<s-1? " " : "\n");
    }

    return f;
}

```

# Answer
> 1 votes
## Canvas, ~~17~~ ~~16~~ 17 characters

```
■；╷［⌐ ＋２×；┌∔∔；３＊＋

```

Try it here!

-1: *Used  instead of  to delete the first  inside the loop.*
+1: *Fixed errenous behavior:  now corresponds to level 1, as specified in the original post.*

# Answer
> 1 votes
# K (ngn/k), ~~50~~ 49 bytes

thanks @DLosc for reminding me I should output spaces between the columns

thanks @coltim for -1 byte

```
1@"\n"/("# "1_,/1,'+/')'a*/:\:a:+2!!1_(. 0:"")#3;

```

Try it online!

# Answer
> 1 votes
# Pip `-S`, 30 characters

```
"■■ "@MX{{aTB3R2i}MSg}MC3**a/3

```

Try it online!

The basic idea: consider a coordinate grid in base 3. The holes in the carpet occur where 1) a trit in the x-coordinate is `1`, and 2) the trit in the same position in the y-coordinate is also `1`.

```
"■■ "@MX{{aTB3R2i}MSg}MC3**a/3
                                i is 0; a is 1st cmdline arg (implicit)
                        3**a/3  Width/height of the carpet
                      MC        Make a coordinate grid that size and map this function
                                to the coordinate pairs:
                    g            Take each [x y] pair
                  MS             Map this function to each coord and add the results:
         {aTB3   }                Convert to base 3
              R2i                 Replace 2's with 0's
                                  E.g. 15 -> 120 -> 100 and 16 -> 121 -> 101
                                 When we add the results, we get [15 16] -> 201
      MX{            }           Take the max of that list (0, 1, or 2)
"■■ "@                           Use that to index into this string (resulting in a space
                                 iff two 1's coincided to make a 2, or ■ otherwise)
                                Print the resulting nested list with each sublist on its
                                own line and space-delimited (implicit, -S flag)

```

Similar solution, same number of characters but -2 bytes: `{2N({aTB3R2i}MSg)?s'■}MC3**a/3`

# Answer
> 1 votes
# Vyxal, 19 bytes

```
‛ #3?‹eʁ3τ∷vB:v⋏†İ⁋

```

Try it Online!

## How?

```
‛ #3?‹eʁ3τ∷vB:v⋏†İ⁋
    ?‹              # Push input - 1
   3  e             # Push 3 to the power of it
       ʁ            # Get range [0, that)
        3τ          # Convert each to base 3 (ternary)
          ∷         # Modulo each by two to convert twos to zeros
           vB       # Convert each from binary to integers
             :v⋏    # Outer product bitwise AND with itself
                †   # Logical NOT for each
‛ #              İ  # Index each into " #"
                  ⁋ # Join each by spaces, and then join on newlines

```

# Answer
> 0 votes
# , 92 characters

94 bytes with the special character.

```
write(c(" ","■")[1+Reduce("%x%",rep(list(matrix(c(1,1,1,1,0,1),3,3)),n<-scan()-1),1)],1,3^n)

```

Try it online!

# Answer
> 0 votes
# , <sup>35</sup> 50 bytes

```
' #'{~1|:@}.[:,/0,:"1]9&([:,/_3,./\0"+4}(#,:)),:@1

```

Try it online!

*+15 thanks to DLosc for pointing out there had to be spaces between columns.*

This was a quick fix to satisfy the spec and could likely be re-golfed further.

## , original answer, cleaner, 35 bytes

```
' #'{~]9&([:,/_3,./\0"+4}(#,:)),:@1

```

Try it online!

# Answer
> 0 votes
# Husk, 27 bytes

```
mJ' ´Ṫȯ!"□ "¬nmḋ†%2mB3ŀ`^3←

```

Try it online!

Translation of Jonathan Allan's program.

uses the '□' character.

# Answer
> 0 votes
# 05AB1E, 21 bytes

```
„# 3I<mÝ¨3δвÉJCDδ&Āè»

```

Port of *@JonathanAllan*'s Jelly answer, so make sure to upvote him as well!

Try it online or verify all test cases.

**Explanation:**

```
    I<                # Push the input-1
   3  m               # Take 3 to the power this input-1
       Ý              # Pop and push a list in the range [0,3**(input-1)]
        ¨             # Remove the last item to lower the range to: [0,3**(input-1))
          δ           # Map over each integer:
         3 в          #  Convert it to a base-3 list
            É         # Check for each trigit if it's odd, converting the 2s to 0s
             J        # Join the inner bit-lists together to strings
              C       # Convert each from a binary-string to an integer
               D      # Using a copy of itself,
                δ     # apply double-vectorized over this list of integer:
                 &    #  Bitwise-AND the integers together
                  Ā   # Check for each integer whether it's NOT 0 (0 if 0; 1 otherwise)
„#                 è  # 0-based index it into the string "# "
                    » # Join each inner list by spaces, and then each string by newlines
                      # (after which the result is output implicitly)

```

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