title: Enlarge ASCII art

text:
# Question
Title: Enlarge ASCII art
In this challenge, you must take multiline ASCII art as input, such as:

```
 OOOOOO  OOOOOO  OOOOOO  OOOOOOO      OOOOOO   OOOOOO  OO      OOOOOOO
OO      OO    OO OO   OO OO          OO       OO    OO OO      OO
OO      OO    OO OO   OO OOOOO       OO   OOO OO    OO OO      OOOOO
OO      OO    OO OO   OO OO          OO    OO OO    OO OO      OO
 OOOOOO  OOOOOO  OOOOOO  OOOOOOO      OOOOOO   OOOOOO  OOOOOOO OO

```

And you will also take an integer as input. You must output the ASCII art enlarged by the amount specified with the integer. For example, if you used a second argument of `3`, the output would be

```
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO                  OOOOOOOOOOOOOOOOOO         OOOOOOOOOOOOOOOOOO      OOOOOO                  OOOOOOOOOOOOOOOOOOOOO
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO                  OOOOOOOOOOOOOOOOOO         OOOOOOOOOOOOOOOOOO      OOOOOO                  OOOOOOOOOOOOOOOOOOOOO
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO                  OOOOOOOOOOOOOOOOOO         OOOOOOOOOOOOOOOOOO      OOOOOO                  OOOOOOOOOOOOOOOOOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO                              OOOOOO                     OOOOOO            OOOOOO   OOOOOO                  OOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO                              OOOOOO                     OOOOOO            OOOOOO   OOOOOO                  OOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO                              OOOOOO                     OOOOOO            OOOOOO   OOOOOO                  OOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOOOOOOOOOOO                     OOOOOO         OOOOOOOOO   OOOOOO            OOOOOO   OOOOOO                  OOOOOOOOOOOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOOOOOOOOOOO                     OOOOOO         OOOOOOOOO   OOOOOO            OOOOOO   OOOOOO                  OOOOOOOOOOOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOOOOOOOOOOO                     OOOOOO         OOOOOOOOO   OOOOOO            OOOOOO   OOOOOO                  OOOOOOOOOOOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO                              OOOOOO            OOOOOO   OOOOOO            OOOOOO   OOOOOO                  OOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO                              OOOOOO            OOOOOO   OOOOOO            OOOOOO   OOOOOO                  OOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO                              OOOOOO            OOOOOO   OOOOOO            OOOOOO   OOOOOO                  OOOOOO
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO                  OOOOOOOOOOOOOOOOOO         OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO   OOOOOO
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO                  OOOOOOOOOOOOOOOOOO         OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO   OOOOOO
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO                  OOOOOOOOOOOOOOOOOO         OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO   OOOOOO

```

Specifically, each character must turn into an `n` by `n` box of that character, where `n` is the integer argument. For example, an input of

```
ab
cd

```

and 3 will result in

```
aaabbb
aaabbb
aaabbb
cccddd
cccddd
cccddd

```

This is , so the shortest code in bytes wins.

# Answer
# APL, 7 chars/bytes\*

```
{⍺/⍺⌿⍵}

```

Function that takes the number and input string as parameters and returns the result:

```
      a
abcde
fghij
      2 {⍺/⍺⌿⍵} a
aabbccddee
aabbccddee
ffgghhiijj
ffgghhiijj
      3 {⍺/⍺⌿⍵} a
aaabbbcccdddeee
aaabbbcccdddeee
aaabbbcccdddeee
fffggghhhiiijjj
fffggghhhiiijjj
fffggghhhiiijjj

```

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
\*: APL can be written in its own (legacy) single-byte charset that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of scoring, a program of N chars *that only uses ASCII characters and APL symbols* can be considered to be N bytes long.
> 38 votes

# Answer
### GolfScript, 20 characters

```
n%(~{.{*}+@1/%n+*}+/

```

Takes all input from STDIN, first line is the scaling factor, the rest the multiline-input. You can try the example online.

**Input**

```
3
ab
cd

```

**Output**

```
aaabbb
aaabbb
aaabbb
cccddd
cccddd
cccddd

```

**Code**

```
n%            # Split the input into separate lines
(~            # Take the first line and evaluate (factor)
{             # {...}+/ adds the factor to the code block and loops over
              # the remaining lines (i.e. the factor will be the top of stack
              # for each line of input
   .{         # Same thing, duplicate factor and add it to code block and
              # loop over each character (1/ splits the string into chars)
     *        # multiply single-char string with factor
   }+@1/%
   n+         # Join string by adding a newline
   *          # Multiply the line by the factor (left from the . operation)
}+/

```
> 35 votes

# Answer
## J, 20 17 characters

```
f=.([#&.|:#)];._2

```

Defines a verb `f` that does what is required. Usage:

```
   3 f a
aaaccc
aaaccc
aaaccc
bbbddd
bbbddd
bbbddd

```

where `a` is the input string.
On Windows an extra character is required to remove the `\r`:

```
f=.([#&.|:#)}:;._2

```

**Explanation**:

`];._2` chops the input string into chunks based on the last character of the string, which in this case will be a `\n`. Windows has `\r\n` so we need to use `}:` to chop an extra character off: `}:;._2`. Cut verb documentation

The rest of the code (with the exception of the assignment `f=.`) is a fork.
It breaks down like this: `[ #&.|: #`

If `a` is our input string the calculation will be `3 # a` (we'll call this result `x`), then `3 [ a` (we'll call this result `y`) then `y #&.|: x`.

`3 # a` just makes three copies of every member of `a`. Copy verb documentation
This turns

```
ab
cd

```

into

```
aaabbb
cccddd

```

`3 [ a` just returns 3. Left verb documentation

Finally `y #&.|: x` is `y` copy under transpose `x`. The `#` works as before, but the `&.|:` tells J to transpose the input first and then transpose it back when it's finished. Under conjunction documentation, transpose verb documentation.

The transpose turns

```
aaabbb
cccddd

```

into

```
ac
ac
ac
bd
bd
bd

```

then the copy changes it to

```
aaaccc
aaaccc
aaaccc
bbbddd
bbbddd
bbbddd

```

and transposing it back gives you

```
aaabbb
aaabbb
aaabbb
cccddd
cccddd
cccddd

```
> 20 votes

# Answer
## Haskell, 49 bytes

```
x=(=<<).replicate
e n=unlines.x n.map(x n).lines

```

The enlarge function is `e`, which takes a count and a string, and returns a string:

```
λ: putStrLn $ e 3 "ab\ncd\n"
aaabbb
aaabbb
aaabbb
cccddd
cccddd
cccddd

```
> 17 votes

# Answer
# APL, 11 chars

@Gareth did essentially the same thing first, in J, so this APL entry is just for exhibition, not competition - he's the winner.

```
      E←{⍉⍺/⍉⍺/⍵}

```

Usage: magnification in left arg (⍺), art in the form of a 2d character matrix in right arg (⍵).
⍺/⍵ will replicate elements across each row of a vector or matrix (2/'O O' becomes 'OO OO').
⍉⍺/⍉ will transpose that, replicate the elements, transpose that.

(If we were going for clarity instead of program length, the code could have been E←{⍺/\[1\]⍺/⍵} )

```
      I←5 32⍴' OOOOOO  OOOOOO  OOOOOO  OOOOOOOOO      OO    OO OO   OO OO     OO      OO    OO OO   OO OOOOO  OO      OO    OO OO   OO OO      OOOOOO  OOOOOO  OOOOOO  OOOOOOO'
      I
 OOOOOO  OOOOOO  OOOOOO  OOOOOOO
OO      OO    OO OO   OO OO
OO      OO    OO OO   OO OOOOO
OO      OO    OO OO   OO OO
 OOOOOO  OOOOOO  OOOOOO  OOOOOOO

      3 E I
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOOOOOOOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOOOOOOOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOOOOOOOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO

```
> 15 votes

# Answer
# Bash/sed script, 48 chars

```
printf -vr %$1s
sed -n s/./${r// /&}/g${r// /;p}

```

Save as a script, `chmod +x` and run:

```
$ ./asciiexpand 3 <<< $'ab\ncd'
aaabbb
aaabbb
aaabbb
cccddd
cccddd
cccddd
$

```

### How does it work?

The meat of it is in the `sed` command. For example, if n=3, then the sed command is expanded to something like:

```
sed -n 's/./&&&/g;p;p;p'

```

This compound `sed` command can be broken up into:

* `s/./&&&/g` \- this substitute command matches each character and replaces it with the character repeated 3 times
* 3x `p` commands - this just prints the whole pattern space (i.e. the current line) 3 times

We pass `-n` to sed to tell it not to print anything unless explicitly told to, so we have full control of what is printed and how many times.

I couldn't figure out a quick way to generate arbitrary-length repeating strings directly in `sed`, so I used some `bash` tricks instead:

```
printf -vr "%3s"

```

This prints a string (not specified, i.e. empty), with 3 leading spaces, and assigns the result to the `bash` variable `r`.

We then use `bash` parameter expansion to transform this string of spaces to what we need substituted into the `sed` expression:

```
$ echo ${r// /&}
&&&
$ echo ${r// /;p}
;p;p;p
$

```

I was able to get away with removing quotes around the `printf` format specifier and the `sed` expression, as none of the characters within need escaping in the `bash` shell.

### Character count:

```
$ submission='r=`printf %$1s`
> sed -n s/./${r// /&}/g${r// /;p}'
$ echo ${#submission}
48
$

```
> 14 votes

# Answer
# PERL,  41 39 25  22 chars

PERL, simple and effective - created right for the task. When invoked with `-pi3`, where `3` is the parameter `n`:

```
s/./$&x$^I/ge;$_ x=$^I

```

Classical solution (39 chars):

```
$n=<>;print map{s/./$&x$n/ge;"$_"x$n}<>

```

Classical solution needs the `n` is specified in the first line of input, e.g.

```
3
ab
cd

```

Thanks @manatwork for the `$&` trick.
> 9 votes

# Answer
# Ruby:  ~~64~~  49 characters

All data received on STDIN: first line the scaling factor, then the ASCII art.

```
BEGIN{n=gets.to_i}
$_=[$_.gsub(/./){$&*n}]*n*$/

```

Sample run:

```
bash-4.2$ ruby -lpe 'BEGIN{n=gets.to_i};$_=[$_.gsub(/./){$&*n}]*n*$/' <<< '3
> ab
> cd'
aaabbb
aaabbb
aaabbb
cccddd
cccddd
cccddd

```

# Ruby:  ~~44~~  41 characters

Assuming that every input line is terminated with line separator. Thanks to @Ventero.

```
$.<2?n=$_.to_i: $><<$_.gsub(/./){$&*n}*n

```

Sample run:

```
bash-4.2$ ruby -ne '$.<2?n=$_.to_i: $><<$_.gsub(/./){$&*n}*n' <<< '3
> ab
> cd'
aaabbb
aaabbb
aaabbb
cccddd
cccddd
cccddd

```
> 8 votes

# Answer
# Python 3 - 84

Not the shortest but a different answer nonetheless. An interesting one-liner.

```
n=int(input())
for i in eval(input()):print(((''.join(j*n for j in i)+'\n')*n)[:-1])

```

Put in a number first, then the ASCII art as a Python list, e.g.:

```
C:\Users\User4\Desktop>c:/python33/python.exe golf.py
3
["aabb","bbcc","ccdd"]
aaaaaabbbbbb
aaaaaabbbbbb
aaaaaabbbbbb
bbbbbbcccccc
bbbbbbcccccc
bbbbbbcccccc
ccccccdddddd
ccccccdddddd
ccccccdddddd

```
> 7 votes

# Answer
# GolfScript, 29 characters

```
{:i;n/{1/:c;{c{i*}/n}i*}/}:f;

```

This defines a block `f`, that when called will produce the desired output. It assumes arguments are on the stack (because that's basically how arguments are passed in GolfScript).

Ungolfed (does that even make sense? :P):

```
{:i;n/{ # for each line...
  1/:c; # save characters of string in c
  {     # i times...
    c{  # for each character...
      i*
    }/
    n
  }i*
}/}:f;

# Test run
"ab
cd" 3 f

```
> 5 votes

# Answer
# Python 3 - ~~109~~ ~~107~~ 93

```
i=input;n,s,a=int(i()),i(),[]
while s:a+=[''.join(c*n for c in s)]*n;s=i()
print('\n'.join(a))

```

First, input the number, then the string. Should be self-explanatory...

~~Thanks to Waleed Khan for suggesting removing the `[]`~~

Thanks to Volatility for suggesting having `a` be a list.
> 5 votes

# Answer
# Golfscript, 23 characters

```
~(:i;n/{{{.}i*}:c%c}%n*

```

I've decided to write an entire program because it has less overhead than even an anonymous function does:

* `~(:i;` \- eval the input, then decrement the multiplier, store it as `i` and discard.
* `n/{...}%n*` \- split by newlines, map each line, join by newlines
    + `{...}:c%c`, - take a block, apply it on map-each element, then apply it to the whole line.
        - `{.}i*` \- duplicate this element `i` times

Live demo: http://golfscript.apphb.com/?c=OyciYWJjCmRlZiIzJwp%2BKDppO24ve3t7Ln1pKn06YyVjfSVuKg%3D%3D

Example usage:

```
;'"abc
def"3'
~(:i;n/{{{.}i*}:c%c}%n*

```
> 5 votes

# Answer
# Java - 217

First try at golfing. Seems like Java isn't the language to do it in.

```
enum M{;public static void main(String[]a){int f=new Integer(a[0]),i=0,j,k;a=a[1].split("\n");for(;++i<a.length*f;System.out.println())for(j=0;++j<a[i/f].length();)for(k=0;k++<f;)System.out.print(a[i/f].charAt(j));}}

```

On Windows you need to replace "\n" with "\r\n".

```
java M 3 "ab
cd"
aaabbb
aaabbb
aaabbb
cccddd
cccddd
cccddd

```
> 5 votes

# Answer
(Edit: This solution is now invalid because the semantics of the  instruction has changed. I didn’t realise that I’d already made use of the instruction when I changed it. You can, however, fix ths program by simply changing it to the newer instruction .)

# ~~Sclipting, 19 characters~~

~~Expects the input to be separated by `\n` (no `\r`) and the first line to contain the multiplying factor.
```
겠坼銻標⑴가殲各標⓶各①復終겠併①復終

```
Explanation
```
겠坼 | split everything at \n
銻 | get first element (the factor)
標 | mark
⑴가殲 | bring list to front; remove first element (the factor)
各 | for each line...
    標⓶ | mark
    各①復終 | for each character, multiply it
    겠併 | add a newline and concatenate everything above the mark
    ①復 | multiply that
終 | end of loop

```
At the end, the stack will look like this:
```
[ factor, mark, line1, line2, line3, ... ]

```~~

~~Everything above the mark is automatically concatenated and output, the rest discarded.~~
> 5 votes

# Answer
**J, 7 chars**

```
([#"1#)

```

Exact same thing as in @Tobia's APL answer, but in ascii chars.

```
a =. ' 0 ',.'0 0',.' 0 '
a
 0
0 0
 0

2 ([#"1#) a
  00
  00
00  00
00  00
  00
  00

```
> 3 votes

# Answer
# Powershell (96)

```
function m($n,$s){$s.split("`n")|%{$l="";$_.ToCharArray()|%{$c=$_;1..$n|%{$l+=$c}};1..$n|%{$l}}}

```

Thought I'd give this a shot in PS. Using piping into foreach's (%) to keep it short here, but the `function` and `ToCharArray` are making it take a hit it brevity.

To use it, you call it from the command line like this:

```
PS C:\> m 3 "ab
>> cd"
>>
aaabbb
aaabbb
aaabbb
cccddd
cccddd
cccddd

```

Here's the non-minimised version:

```
function f($n, $s)
{
    $s.split("`n") | % {            # split input into separate lines
        $l=""                       # initialize an output line
        $_.ToCharArray() | % {      # split line into chars
            $c=$_ ; 1..$n | % {     # add n chars to the line
                $l+=$c
            }
        }
        1..$n | % {$l}              # output the line n times
    }
}

```
> 3 votes

# Answer
# Julia, 74 chars/bytes

```
julia> f(i,n)=print(prod([(prod(["$c"^n for c in l])*"\n")^3 for l in split(i)]))
f (generic function with 1 method)

julia> f("ab\ncd",3)
aaabbb
aaabbb
aaabbb
cccddd
cccddd
cccddd

```

7 less if I just return the string. `julia>` is the interactive prompt.
> 2 votes

# Answer
# Canvas, 2 bytes

```
：＊

```

Try it here!
> 2 votes

# Answer
# , 83/72 bytes

Alt approach using regexps

If we're allowed a trailing newline, 72 bytes:

```
function(s,n)cat(gsub("([^
]*
)",r,gsub("([^
])",r<-strrep("\\1",n),s)))

```

Try it online!

Otherwise, 83 bytes:

```
function(s,n)write(rep(el(strsplit(gsub("([^\n])",strrep("\\1",n),s),"\n")),e=n),1)

```

Try it online!
> 2 votes

# Answer
# Powershell, 54 bytes

```
param($s,$n)$s-replace'.',('$0'*$n)-split'
'|%{,$_*$n}

```

Test script:

```
$f = {

param($s,$n)$s-replace'.',('$0'*$n)-split'
'|%{,$_*$n}

}

@(
@"
ab
cd
"@
,
@"
 OOOOOO  OOOOOO  OOOOOO  OOOOOOO      OOOOOO   OOOOOO  OO      OOOOOOO
OO      OO    OO OO   OO OO          OO       OO    OO OO      OO
OO      OO    OO OO   OO OOOOO       OO   OOO OO    OO OO      OOOOO
OO      OO    OO OO   OO OO          OO    OO OO    OO OO      OO
 OOOOOO  OOOOOO  OOOOOO  OOOOOOO      OOOOOO   OOOOOO  OOOOOOO OO
"@
) | % {
    &$f $_ 3
}

```

Explanation:

* `$s-replace'.',('$0'*$n)` repeats each symbol exept new line.
* `-split'``n'` splits the wide string by new line
* `|%{,$_*$n}` repeats each line as an array element and returns array

The result is an array of wide and repeated strings.
> 2 votes

# Answer
# Vyxal `j`, 3 bytes

```
•εf

```

Try it Online!

I/O is as lists of lines. The `j` flag formats the output into ASCII art.

```
•   # Repeat each character of each line by the number
 ε  # Repeat each line by the number
  f # Flatten

```
> 2 votes

# Answer
# Rebol - ~~87~~ 79

```
r: do input while[d: input][forskip d r[insert/dup d d/1 r - 1]loop r[print d]]

```

Nicely formatted version:

```
r: do input

while [d: input] [
    forskip d r [insert/dup d d/1 r - 1]
    loop r [print d]
]

```

Usage example:

```
rebol -qw --do 'Rebol[]r: do input while[d: input][forskip d r[insert/dup d d/1 r - 1]loop r[print d]]' <<< "3
ab
cd"
aaabbb
aaabbb
aaabbb
cccddd
cccddd
cccddd

```

NB. This code only works in Rebol 2 at this moment (The **INPUT** function used is not fully implemented in Rebol 3 yet).
> 1 votes

# Answer
# K, 20

.....

```
{,/y#',:',/'y#'/:x}

```
> 1 votes

# Answer
# Extended BrainFuck : 158

```
{a<]<[->+}3>,>3+[->4+[-<<4->>]&a>+<<]<+[-<,[>10+[-<->>+<]<[[->>+<<]3>[->[->+&a&a#3<+>>]>>]<[-]<<]>>[>[-4<[<]>[.>]>>.>]4<[-]<[-]4>[-]]>>[->+<]>[-<+<+>>]4<+<]>]

```

It turns into:

# Brainfuck: 185

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

```

It requires an interpreter that either has 0 or no change as EOF marker. `beef`, available from Ubuntu repos, works swell:

```
$ ( echo -n 2
> cat <<eof
> BBBB  RRRR   AAA  IIII NN  NN FFFFF * * * KK  KK
> BB BB RR RR AA AA  II  NNN NN FF      *   KK  KK
> BBBB  RRRR  AAAAA  II  NNNNNN FFFF  ***** KKKKK
> BB BB RR RR AA AA  II  NN NNN FF      *   KK  KK
> BBBB  RR RR AA AA IIII NN  NN FF    * * * KK  KK
> eof
> ) | beef double.bf
BBBBBBBB    RRRRRRRR      AAAAAA    IIIIIIII  NNNN    NNNN  FFFFFFFFFF  **  **  **  KKKK    KKKK
BBBBBBBB    RRRRRRRR      AAAAAA    IIIIIIII  NNNN    NNNN  FFFFFFFFFF  **  **  **  KKKK    KKKK
BBBB  BBBB  RRRR  RRRR  AAAA  AAAA    IIII    NNNNNN  NNNN  FFFF            **      KKKK    KKKK
BBBB  BBBB  RRRR  RRRR  AAAA  AAAA    IIII    NNNNNN  NNNN  FFFF            **      KKKK    KKKK
BBBBBBBB    RRRRRRRR    AAAAAAAAAA    IIII    NNNNNNNNNNNN  FFFFFFFF    **********  KKKKKKKKKK
BBBBBBBB    RRRRRRRR    AAAAAAAAAA    IIII    NNNNNNNNNNNN  FFFFFFFF    **********  KKKKKKKKKK
BBBB  BBBB  RRRR  RRRR  AAAA  AAAA    IIII    NNNN  NNNNNN  FFFF            **      KKKK    KKKK
BBBB  BBBB  RRRR  RRRR  AAAA  AAAA    IIII    NNNN  NNNNNN  FFFF            **      KKKK    KKKK
BBBBBBBB    RRRR  RRRR  AAAA  AAAA  IIIIIIII  NNNN    NNNN  FFFF        **  **  **  KKKK    KKKK
BBBBBBBB    RRRR  RRRR  AAAA  AAAA  IIIIIIII  NNNN    NNNN  FFFF        **  **  **  KKKK    KKKK

```

Ungolfed EBF code:

```
;;;; Multiply
;;;; Takes a digit x and ASCII art on STDIN
;;;; Prints ASCI art scaled x times
;;;; Usage:
;;;; bf ebf.bf < multiply.ebf >multiply.bf
;;;; bf multiply.bf

;;; Memory map for this program
:zero
:str
:flag
:tmp
:dup
:num

;;; Macros

;; EOL support. Comment out the body of the two
;; macros below to only support 0 and no change
;; Some interpreters use -1
{eol_start
  +(-
}

{eol_end
   )
}

;; macro that reads a digit.
;; the actual number is one more than input
;; ^12 uses 3 cells from origin
{read_number
  ,                    ; read char
  ^1 3+(-^2 4+(-^ 4-)) ; reduce by 3*4*4=48
}

;; duplicate current element
;; to the left using the right as tmp
{copy_left
  (-^1+)^1(-^0+<+)
}

;; Duplicate char n times while
;; shifting to the right
{handle_char
  $str(-$tmp+)               ; copy the char to tmp
  $dup(-$num(->+)            ; for each dup move num
        $dup(-$num+)         ; and dup one step to the right
        $tmp(-$dup+$str+)    ; and copy the char back to str and to dup
        @flag)               ; which is the new tmp (it gets shifted to the right)
  $tmp(-)                    ; clear char when done
}

{handle_linefeed
  $dup(-                     ; for each dup
    $zero[<]>                ; go to beginnning of string
    [.>]@str                 ; print string
    $tmp.                    ; print newline
  )
  $zero[-]<[-]>@zero         ; clean last two chars
  $tmp(-)                    ; remove line feed
}

;;; Main program

;; read number
$tmp &read_number
$tmp (-$dup+$num+)
;$tmp,[-] ; uncomment to require a newline before asci art
$flag+(-
  $str = ,
  ( ;; NB! The line containing EOF will not be printed!
    &eol_start
    $flag 10+(-$str-$tmp+)
    if $str is not linefeed (
       &handle_char
    ) $tmp ( linefeed
       &handle_linefeed
    )
    $num &copy_left      ; we need two copies of the duplicate dupber
    $flag+               ; flag to
    &eol_end
  )
)

```
> 1 votes

# Answer
# , 125 bytes

```
function(s,n,x=utf8ToInt(s),m=matrix(x[u<-x!=10],,sum(!u)+1))for(i in 1:ncol(m))cat(rep(intToUtf8(rep(m[,i],e=n)),n),sep="
")

```

Try it online!

Converts string to UTF8, puts into a matrix whose columns are lines of text (removing newlines), and then repeats each char and the generated lines before printing separeated by newlines.
> 1 votes

# Answer
# R - 89

```
M=function(I,N) cat(paste(lapply(lapply(strsplit(I,""),rep,e=N),paste,collapse=""),"\n"))

I <- c("aa  aa  aa", "bbb bbb bbb", "c c c c c c")
N <- 3

I
# aa  aa  aa
# bbb bbb bbb
# c c c c c c"

M(I,N)

# aaaaaa      aaaaaa      aaaaaa
# bbbbbbbbb   bbbbbbbbb   bbbbbbbbb
# ccc   ccc   ccc   ccc   ccc   ccc

```
> 0 votes

# Answer
## MATLAB: 20 characters

```
['' imresize(ans,n)]

```

This solution assumes that the image is stored in a file called `startup.m` and that it is allowed to give the amount of replications to matlab when calling it, this can be done by means of: `!matlab -r "n=3"&`

## MATLAB, call without argument: 23 characters

```
load;['' imresize(s,n)]

```

Unlike the first solution, the latter two assume that the amount of replications may not be expected in the call. For these solutions the original string and number are expected in a file called `matlab.mat` in your current directory.

## MATLAB, mathematical alternative: 27 characters

```
load;['' kron(s,ones(1,n))]

```
> 0 votes

# Answer
**C# (177)**

```
public string e(string i,int x){return string.Join("",i.Split('\n').Select(a=>string.Join("",Enumerable.Repeat(string.Join("",a.ToCharArray().Select(c=>new string(c,x))),x))));}

```

Expects input string "i" containing new lines "\n" as the delimiter.

Formatted

```
public string e(string i, int x)
{
    return string.Join("", i.Split('\n').Select(a => string.Join("", Enumerable.Repeat( string.Join("", a.ToCharArray().Select(c => new string(c, x))), x))));
 }

```
> 0 votes

# Answer
# CJam, 14 bytes

CJam is newer than this challenge (and the main feature I'm using is actually very recent), so this answer wouldn't be eligible for being accepted - but it's not beating APL anyway, so...

```
l~qN/1$e*fe*N*

```

Test it here.

## Explanation

With the new `e*` which repeats each character in a string, this is really straightforward:

```
l~             e# Read and eval the scale factor.
  qN/          e# Read the rest of the input as the ASCII art and split into lines
     1$e*      e# Copy the scale factor and repeat each line by it.
         fe*   e# Repeat the characters in each line by the scale factor.
            N* e# Join with newlines.

```
> 0 votes

# Answer
# RProgN 100 Bytes (Windows) Non-Competing

```
'l' asoc
'i' asoc
i '[^
]' '%0' l rep replace '[^
]*' '%0
' l rep 'z' asoc z 1 z len 1 - sub replace

```

RProgN doesn't have character escapes as of writing, which makes any handling of new lines require a physical new line. As such, this answer (and any input) has to use CRLFs, instead of just LFs. :(

Also, the 'rep' function was only added after this challenge was issued, as such, this is non-competing.
> 0 votes

# Answer
# Vim, 39 keystrokes (excluding input, not competing)

the gotcha and the reason this is not competing is because the input has to be entered twice. Replace both `2` with your own input.

```
qayl2phxl@aquu:%norm @a<cr>gg0qbyy2P2jkddj@bq@b

```

### Explanation

* `qayl2phxl@aquu` records a macro that yanks a character, paste it and move to the next one, then replays itself. Then it undoes the changes. Because we want the loop not to be infinite, we don't delete the character, which means we have to delete the extraneous one but still finish with a movement that fails on the last char.
* `:%norm @a<cr>` runs the macro on every line
* `gg0` returns to the very beginning
* `qbyy2P2jkddj@bq@b` uses the same technique as `@a` to copy every line, but with a recursive macro.

I know this can be golfed more, e.g. by traversing backwards for line duplication but because of the multiple input entry requirement, I will stop there and mark this answer as non competing.

## Previous answer (32 keystrokes, only doubles)

```
qaylpl@aqu:%norm @a<cr>:%s/.*/&\r&<cr>

```

### Explanation

* `qaylpl@aqu` records a macro that yanks a character, paste it and move to the next one, then replays itself. Undo the change.
* `:%norm @a<cr>` runs the macro on every line
* `:%s/.*/&\r&<cr>` doubles every line

I wanted to do a nested macro, but the inner one (characters) stops the outer one (lines)... So I have to run two commands, adding quite a few keystrokes to an otherwise simple solution.
> 0 votes

# Answer
# C (gcc), 113 bytes

```
i,j;f(s,n)char*s;{char*p;for(;*s;s=*p?++p:p)for(i=n;i--;puts(""))for(p=s;*p&&*p^10;p++)for(j=n;j--;)putchar(*p);}

```

Try it online!
> 0 votes

# Answer
# Japt, 11 bytes

```
yW=_mpVÃmWR

```

Try it online!

### Unpacked & How it works

```
UyW=Z{ZmpV} mWR

Input: U = 2D string, V = magnification

Uy               map over columns of U...
    Z{ZmpV}        a function that repeats each char V times
  W=               assign this function to W
            m    and map again...
              R    over rows...
             W     the function W

```

JS's Assign-Anywhere™ trick in action.
> 0 votes

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

```
{,/+x#,+,/+x#,+y}

```

Try it online!
> 0 votes

# Answer
# Japt `-R`, ~~10~~ 9 bytes

```
·cÈVÇXmpV

```

Try it

```
·cÈVÇXmpV     :Implicit input of string U and integer V
·             :Split U on newlines
 c            :Flat map
  È           :By passing each X through the following function
   VÇ         :  Map the range [0,V)
     Xm       :    Map each character in X
       pV     :      Repeat V times
              :Implicit output joined with newlines

```
> 0 votes

# Answer
# 05AB1E, 12 bytes

```
U|εSX×JXи}˜»

```

Try it online.

**Explanation:**

```
U               # Take the integer input, and store it in variable `X`
                #  i.e. 3
 |              # Take the rest of the input-lines as list
                #  i.e. ["ab","cd"]
  ε      }      # Map each line to:
   S            #  Convert the line to a list of characters
                #   i.e. "ab" → ["a","b"]
    X×          #  And repeat each character `X` amount of times
                #   i.e. ["a","b"] and 3 → ["aaa","bbb"]
      J         #  Join the line back together
                #   i.e. ["aaa","bbb"] → "aaabbb"
       Xи       #  And repeat that line `X` amount of times
                #   i.e. "aaabbb" and 3 → ["aaabbb","aaabbb","aaabbb"]
          ˜     # Flatten the list of lists
                #  i.e. [["aaabbb","aaabbb","aaabbb"],["cccddd","cccddd","cccddd"]]
                #   → ["aaabbb","aaabbb","aaabbb","cccddd","cccddd","cccddd"]
           »    # And join by newline (which we implicitly output)
                #  i.e. ["aaabbb","aaabbb","aaabbb","cccddd","cccddd","cccddd"]
                #   → "aaabbb\naaabbb\naaabbb\ncccddd\ncccddd\ncccddd"

```
> 0 votes

# Answer
# PHP, 115 bytes

```
function f($s,$l){foreach(explode("
",$s)as$a)for($i=$l;$i--;)echo preg_replace('/./',str_repeat('$0',$l),$a)."
";}

```

Try it online!
> 0 votes

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

```
n=>k=>n.split`
`.map(e=>(e.replace(/./g,l=>l.repeat(k))+`
`).repeat(k)).join``

```

Try it online!

No JavaScript answer yet, so decided to try it out.
> 0 votes

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


title: Tips for golfing in Excel?

text:
# Question
Title: Tips for golfing in Excel?
It's strange that I haven't seen this, as Excel seems to be a valid language for code golfing (despite its 'compiler' not being free).

Excel is somewhat of a wildcard in golfing, being good at golfing challenges of medium complexity, and sometimes simpler challenges as well. More often than not, Excel is good at challenges with string manipulation and mixed string-number manipulation.

What general tips do you have for golfing in Excel? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Excel (NOT VBA). Please, one tip per answer.

# Answer
## Vectorization with Arrays

Whenever a function takes an array as an argument instead of a singleton, That function will also output an array with the result value to the corresponding indecies.

Example:
`=LEN(A1)+LEN(B2)+LEN(C3)`
could be replaced with
`=SUM(LEN({A1,B2,C3}))`
> 12 votes

# Answer
# Reference shorthand:

If your program is required to take multiple inputs, you may want to be able to scoop them all up at once. to read multiple cells as an array, one could do such as the example:

Example:
`=len(A1)+Len(B1)+LEN(C1)`
could be
`=SUM(LEN(A1:C1))`

`=SUM(LEN(A1:C1 A2:C2 A3:C3))`
could be
`=SUM(LEN(A1:C3))`

`=SUM(LEN(A1:A1024))`
could be
`=SUM(LEN(A:A))`

`=SUM(LEN(A:A B:B C:C))`
could be
`=SUM(LEN(A:C))`
> 12 votes

# Answer
## Concatenate shorthand:

The `CONCATENATE` function can be replaced with the `&` symbol 100% of the time, so long as the first argument is a string, or cell.

example:

```
CONCATENATE(A1,B1)

```

could be shortened to

```
A1&B1

```

In newer version of Excel (2016 or newer) the `CONCAT` function can be used for arrays and longer series of variables.

```
CONCAT(1:1)

```
> 11 votes

# Answer
# Boolean Logic Shortcuts

## Universal Set of Operators

`0` =\> `FALSE` and any other number =\> `TRUE`, so we can exploit this fact with some arithmetic operators

| Standard | Hacky | \# Saved |
| --- | --- | --- |
| `NOT(A1)` | `A1=0` | 3, 1 if parenthesized |
| `XOR(A1,B1)` | `A1<>B1` | 4 |
| `XOR(A1,B1,...)` | `A1=B1=...=0` | 3 |
| `NOT(XOR(A1,B1,...))` | `A1=B1=...` | 6 (XNOR) |
| `OR(A1,B1,...)` | `A1+B1+...` | 4 or 2 (see note) |
| `AND(A1,B1,...)` | `A1*B1*...` | 5 |

Note: This XOR only works if all argument values are the same nonzero number. You may have to "cast" a result (such as with `OR`) to a Boolean using `...>0`

## Operator precedence

You may have to add parentheses, depending on precedence.

1. Reference (`:`//`,`)
2. Negation (Prefix `-`)
3. Percent (`%`)
4. Exponentiation (`^`)
5. Multiplication/Division (`*`/`/`) (AND)
6. Addition/Subtraction (`+`/`-`) (OR)
7. Concatenation (`&`)
8. Comparison (`=`, `<`, `>`, `<=`, `>=`, `<>`) (XOR/NOT)

## Other Things

* A blank cell evaluates to `FALSE`.
> 5 votes

# Answer
# Converting a Number to Text:

This is a very simple tip, but it may be useful to some nonetheless...

* If you need to convert a number to text from within a formula, use the concatenation operator to join two parts of the number as a string (i.e. `1&23`).
* If you need to convert a number to text for use by cell reference (i.e. `A1`), change the **Number Format** of the cell to **Text** to eliminate the need for extra bytes.
* See the chart below for a comparison of number-to-text methods.

**Quick Reference Chart:**

```
+-------------------------------------------------------------------------------------+
|   | A               | B        | C         | D                | E                   |
|-------------------------------------------------------------------------------------|
| 1 | Formula         | Bytes    | Result    | ISTEXT(cell)¹    | ISTEXT(formula)²    |
|-------------------------------------------------------------------------------------|
| 2 | =TEXT(123,0)    | 12       | 123       | TRUE             | TRUE                |
| 3 | ="123"          | 6        | 123       | TRUE             | TRUE                |
| 4 | =1&23           | 5        | 123       | TRUE             | TRUE                |
| 5 | '123            | 4        | 123       | TRUE             | NOT VALID           |
| 6 | 123             | 3        | 123       | TRUE             | FALSE               |
| 7 | 123             | 3        | 123       | FALSE            | FALSE               |
+-------------------------------------------------------------------------------------+

Note: The result for cell C6 has been formatted as text, whereas the result for C7 has not.

¹ Denotes =ISTEXT(C2), =ISTEXT(C3), =ISTEXT(C4), etc.
² Denotes =ISTEXT(TEXT(123,0)), =ISTEXT("123"), =ISTEXT(1&23), etc.

```
> 3 votes

# Answer
# Boolean Shorthand:

Instead of using the `=TRUE()` and `=FALSE()` functions, use `=1=1` and `=1=2`.
> 3 votes

# Answer
# Vectorization of arrays of cells:

The tip Vectorization with arrays Shows how you can golf down a function with an array by using specific formatting within the array. It is possible to do the same thing with cells, and will save you many many bytes in the long run. Say you have the following sheet:

And we want to find the highest shelf life of a fruit.

Without Vectorization, one might use the two formulas like so:

And this does give a correct answer, but the Score for this golf is Unconventional, and will probably not be accepted as widely. On top of that, this uses a drag down function (Ew), which makes for a confusing answer.

Instead, We can place the function in column D right on in with the formula in E2. To do this, you replace (in this case B2 and C2) your variables with arrays for the range you want to test. Thus, your formula becomes:

This saves you a few bytes as well as making your entry properly score-able.
> 2 votes

# Answer
# Converting Types

## To Number

* Use a `--` prefix.
    + `--FALSE` = 0, `--TRUE` = 1
* Sometimes an arithmetic operator can be used to save steps later.
    + `"2"-2` = 0, which can be used as an equality check.

## To Boolean

* Since numbers are implicitly Boolean-like, you may be able to avoid this.
    + 0 =\> `FALSE`, Any other number =\> `TRUE`
    + Blank cell =\> `FALSE`
* If you need it, you can use comparison operators.
    + `A1<>0` =\> Non-zero to `TRUE`, `A1>0` =\> Positive to `TRUE`.

## To String

* Concatenate either a blank cell or `""` using the `&` operator.

## Using `BASE()` and `DECIMAL()`

`BASE` takes a decimal number and converts it to another base. For example, `=BASE(6873049,25)` becomes "HELLO". You can do the reverse of this with `=DECIMAL("HELLO",25)`. This is sometimes useful for restricted source problems, or can be used to compress a big number in a smaller base using a decimal number.
> 2 votes

# Answer
# LET Function

LET allows you to define names within a function. For example, `=LET(x,1,y,2,x+y)` returns 3. This allow you to define longer expressions with one character and reuse them within a formula. For example, `LET(q,ROW(1:19),if(q>10,19-q,q))` lists the numbers from 1 to 10 and then back down to 1.

This sounds like a simple function but it has allowed golfing answers that were not possible before this was added to Excel.

There are functions like `OFFSET` and `SUMIF` that do not work entirely correctly on names that are not tied directly to cell references.

More info on LET
> 2 votes

# Answer
# ISBLANK() Shorthand:

Instead of using `=ISBLANK(A1)`, use `=A1=0` to determine if a cell (i.e. `A1`) is empty.

***Note:** This shortcut will not work if cell* `A1` *contains* `0`. *In that case, you will need to use* `=A1=""`.
> 1 votes

---
Tags: code-golf, tips
---


title: List of paths to nested dictionary

text:
# Question
Title: List of paths to nested dictionary
Given a list of nested menu items,

```
items = [
    '3D/Axis',
    '3D/CameraTracker',

    'Color/Invert',
    'Color/Log2Lin',

    'Color/Math/Add',
    'Color/Math/Multiply',

    'Other/Group',
    'Other/NoOp',

    'Views/JoinViews',
    'Views/ShuffleViews',

    'Views/Stereo/Anaglyph',
    'Views/Stereo/ReConverge',
]

```

..and a dummy function to be triggered by each item:

```
def msg(path):
    """Dummy function used in menu
    """
    return path.lower()

```

Programatically create a hierarchal collection of dictionaries, which is equivalent to manually typing this:

```
menu = {
    '3D': {'Axis':                     lambda: msg('3D/Axis'),
           'CameraTracker':            lambda: msg("3D/CameraTracker")},

    'Color': {'Invert':                lambda: msg('Color/Invert'),
              'Log2Lin':               lambda: msg('Color/Log2Lin'),

              'Math': {'Add':          lambda: msg('Color/Add'),
                       'Multiply':     lambda: msg('Color/Multiply')}},

    'Other': {'Group':                 lambda: msg('Other/Group'),
              'NoOp':                  lambda: msg('Other/NoOp')},

    'Views': {'JoinViews':             lambda: msg('Views/JoinViews'),
              'ShuffleViews':          lambda: msg('Views/ShuffleViews'),
              'Stereo': {'Anaglyph':   lambda: msg('Views/Stereo/Anaglyph'),
                         'ReConverge': lambda: msg('Views/Stereo/ReConverge')}}},

```

..which could be tested as follows:

```
assert menu['3D']['Axis']() == '3d/axis'
assert menu['Color']['Invert']() == 'color/invert'
assert menu['Color']['Math']['Add']() == 'color/math/add'
assert menu['Views']['Stereo']['Anaglyph']() == 'views/stereo/anaglyph'

```

# Answer
> 2 votes
A simple recursion will do the work

```
def build_nested_helper(path, text, container):
    segs = path.split('/')
    head = segs[0]
    tail = segs[1:]
    if not tail:
        container[head] = lambda: msg(text)
    else:
        if head not in container:
            container[head] = {}
        build_nested_helper('/'.join(tail), text, container[head])

def build_nested(paths):
    container = {}
    for path in paths:
        build_nested_helper(path, path, container)
    return container

menu = build_nested(items)

```

squashed code: 159 chars

```
def f(p,t,c):
 s=p.split('/');a=s[0];b=s[1:]
 if b:
  if a not in c:c[a]={}
  f('/'.join(b),t,c[a])
 else:c[a]=lambda:msg(t)
menu={}
for i in items:f(i,i,menu)

```

# Answer
> 0 votes
```
#!/usr/bin/env python3

from itertools import groupby
from pprint import pprint

items = [
    '3D/Axis',
    '3D/CameraTracker',

    'Color/Invert',
    'Color/Log2Lin',

    'Color/Math/Add',
    'Color/Math/Multiply',

    'Other/Group',
    'Other/NoOp',

    'Views/JoinViews',
    'Views/ShuffleViews',

    'Views/Stereo/Anaglyph',
    'Views/Stereo/ReConverge',
]

def fun(group, items, path):
    sep = lambda i:i.split('/', 1)
    head = [i for i in items if len(sep(i))==2]
    tail = [i for i in items if len(sep(i))==1]
    gv = groupby(sorted(head), lambda i:sep(i)[0])
    return group, dict([(i, path+i) for i in tail] + [fun(g, [sep(i)[1] for i in v], path+g+'/') for g,v in gv])

menu = dict([fun('menu', items, '')])['menu']
pprint(menu)

```

---

```
{'3D': {'Axis': '3D/Axis', 'CameraTracker': '3D/CameraTracker'},
 'Color': {'Invert': 'Color/Invert',
           'Log2Lin': 'Color/Log2Lin',
           'Math': {'Add': 'Color/Math/Add',
                    'Multiply': 'Color/Math/Multiply'}},
 'Other': {'Group': 'Other/Group', 'NoOp': 'Other/NoOp'},
 'Views': {'JoinViews': 'Views/JoinViews',
           'ShuffleViews': 'Views/ShuffleViews',
           'Stereo': {'Anaglyph': 'Views/Stereo/Anaglyph',
                      'ReConverge': 'Views/Stereo/ReConverge'}}}

```

---

**`fun()` takes 6 lines**
Just change `path+i` to `(path+i).lower()` to get what you want.

# Answer
> 0 votes
# JavaScript (V8), 134 bytes

```
menu=items.reduce((a,x,_,$,c=a,s=x.split`/`)=>s.slice(0,-1).map(v=>c=c[v]?c[v]:c[v]={})&&(c[s[s.length-1]]=()=>x.toLowerCase())&&a,{})

```

Try it online!

# Answer
> -1 votes
As a starting point,

```
def populate_dict(item, existing_dict, fullpath = None):
    if len(item) == 1:
        existing_dict[item[0]] = lambda p=item[0]: msg(fullpath + "/" + item[0])
    else:
        head, tail = item[0], item[1:]
        existing_dict.setdefault(head, {})
        populate_dict(
            tail,
            existing_dict[head],
            fullpath = "/".join([x for x in (fullpath, head) if x is not None]))

menu = {}
for i in items:
    populate_dict(i.split("/"), menu)

```

..which can be squashed down to:

```
def p(i,e,fp=""):
 if len(i)<2:e[i[0]]=lambda p=i[0]:msg(fp+"/"+i[0])
 else:p(i[1:], e.setdefault(i[0], {}),"/".join([fp, i[0]]).lstrip("/"))
menu = {}
for i in items:p(i.split("/"),menu)

```

---
Tags: python, code-golf
---


title: Prime Factorization

text:
# Question
Title: Prime Factorization
Although there was a prime factors challenge posted ten years ago, it has tedious I/O and restricted time. In this challenge, your task is to write a program or function which takes an integer \\$n \ge 2\\$ as input, and returns its prime factors.

**Task:**

Input will consist of an integer, \\$n \ge 2\\$. Your program should theoretically work for arbitrarily large numbers, but can fail due to limits like integer overflow.

Your program should print/return the prime factors (in any order), in any reasonable representation. For example, `180` could be represented as `[2, 2, 3, 3, 5]`, or `"2 3 5 2 3"`, or through any other collection type or string representation.

**Test cases:**

```
2       [2]
3       [3]
6       [2, 3]
12      [2, 2, 3]
25      [5, 5]
180     [2, 2, 3, 3, 5]
181     [181]

```

**Other:**

Any trivial built-in answers should go in this community wiki.

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

# Answer
# Javascript, 43 bytes

```
f=(n,i=2)=>n%i?n-1?f(n,i+1):"":i+" "+f(n/i)

```

Outputs a space separated list with a trailing space. It dies pretty quickly due to recursion limits, partially because it restarts at 2 every time it finds a new prime.
> 3 votes

# Answer
# Trivial Answers (Community Wiki)

**Edit**: This challenge is closed. Please do not add solutions here; instead, consider creating a CW for trivial solutions on the dupe target, or just post your answer there as there are already many trivial solutions.

# Vyxal, 1 byte

```
ǐ

```

Try it Online!

# Jelly, 2 bytes

```
Æf

```

Try it online!

# Factor \+ `math.primes.factors`, 7 bytes

```
factors

```

Try it online!

# 05AB1E, 1 byte

```
Ò

```

Try it online!

# , 2 bytes

```
q:

```

Try it online!
> 1 votes

# Answer
# Vyxal, 16 bytes

```
ʀǎ:£$vǑ¥Zƛ÷w$ẋ;f

```

Try it Online at your own risk!

It is horrendously slow for large numbers, but it works

## Explained

```
ʀǎ:£$vǑ¥Zƛ÷w$ẋ;f
ʀǎ                  # nth prime for each item in the range [0 ... input - 1]
  :£                # put that into the register while leaving it on the stack
    $vǑ             # get the divisbilty of each prime into the input
       ¥Z           # and zip that with the register
        ƛ     ;     # for each item in that zipped list: (each item is: [divisbilty, prime factor])
         ÷w         #      push divisbilty, [prime_factor]
           $ẋ       #      and repeat [prime_factor] divisibility times
               f    # flatten the unholy mess that results from doing the above

```
> 1 votes

# Answer
**Matlab**, **17 bytes**

```
factor(input(''))

```
> 0 votes

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


title: It's fun to stay at the Y.M.C.A

text:
# Question
Title: It's fun to stay at the Y.M.C.A
"Y.M.C.A." is a popular disco song by the Village People that has a well-known dance. Write the shortest program to output the capital letters "Y", "M", "C", and "A" synchronized to the song's chorus.

Generally, one letter goes on each line sent to standard output. This primarily is to simplify programs subject to the output buffering of the C standard library (printing a newline flushes the output buffer), so you may omit any or all of these newlines if such omission would make your program shorter.

Your program, which is started at the same time as the music, must output the letter "Y" within 0.125 s of each of these times after starting (in seconds; I determined these from the music video posted on YouTube).

```
 45.766   49.611   60.889
 64.661  109.816  113.591
124.810  128.687  173.830
177.620  188.950  192.724
204.013  207.739  219.057

```

The letters "M", "C", and "A" respectively come 0.930 s, 1.395 s, and 1.628 s after each "Y". For testing purposes, these relative times are converted into absolute times by adding them to the time of the preceding "Y".

I have written a test program and corresponding example program in C that assume a newline follows each letter (although this is not a rule of competition). It is written for Linux and will not work on Windows without using Cygwin. If you cannot test your submission using the test program, at least check your submission against the YouTube video.

If your submission requires a special command-line option to behave properly, that command-line option counts when calculating your score. However, any interpreter startup time does not count against you, and the test program can be modified to accommodate that if necessary.

Although I doubt one exists, I must say that using a programming language function or library designed specifically for this task is prohibited.

# Answer
## C, 161 154 chars

```
#define P(d,x)w(d);puts(#x);
w(n){usleep(n<<16);}
y(d){P(d,Y)P(14,M)P(7,C)P(3,A)}
b(){y(664);y(35);y(147);y(35);}
main(){b(b(b(w(34))));y(148);y(33);y(148);}

```

The tester passes, but only if `fflush(stdout);` is added after each `puts`. Since the question clearly states that `fflush` is not required, I take it as a problem in the tester.

Logic:
`w` sleeps, the time is given in units of 16.384 65.536 ms. This resolution allows accurate enough timing and small constants (I should perhaps try 100ms).
`P` waits a while and prints a character.
`y` prints a YMCA sequence, after an initial delay.
`b` prints 4 YMCA sequences - this 4\*YMCA happens 3 times, with similar enough timing.
`main` prints the 3\*4\*YMCA sequences, plus the remaining 3.
> 3 votes

# Answer
## Ruby ~~180 135 124 118 108~~ 104

```
[458,k=22,*[97,k,435,k]*2,*[98,k]*2,98].flat_map{|e|[e,9,5,2]}.zip(%w(Y M C A)*15){|a,b|sleep a/1e1;p b}

```
> 4 votes

# Answer
## Python2.6 (~~82~~)(~~214~~)(~~219~~)(~~196~~)(~~185~~)(152)

Fixed. Ran against the video & seems accurate. Saved quiet a few characters by reducing the precision from 3 to 2 in most of the cases(thanks for the tip @JPvdMerwe).

The only problem is that the tester shows a huge discrepancy in the timings. It starts out of sync & tries to come back into sync. In the two test cases it was more than 175 seconds out of sync at the beginning and came back to within 0.342 and 0.451 seconds of being back in sync.

```
import time;s=time.sleep
for t in[45.8,2.1,9.5,2,43.4,2,9.5,2.1,43.4,2,9.6,2,9.5,2,9.6]*15:
 i=0;s(t)
 while i<4:s([.1,.9,.5,.2][i]);print'YMCA'[i];i+=1

```
> 0 votes

# Answer
### Mathematica, 157

```
p=Print[Pause@#;#2]&

(#~p~"Y";.93~p~"M";.465~p~"C";.233~p~"A")&/@{45.766,2.217,9.65,2.144,43.527,2.147,9.591,2.249,43.515,2.162,9.702,2.146,9.661,2.098,9.69}

```

I watched the entire video to confirm the timing. Y M C A.... Y M C A...

It could be shorter with less precision, but then I'd have to watch the video again to confirm that it was not off by more than .125 at the end. lol
> 0 votes

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

```
s=async t=>await new Promise(r=>setTimeout(r,t*1e3));(async _=>{for(t of[45.8,2.1,9.5,2,43.4,2,9.5,2.1,43.4,2,9.6,2,9.5,2,9.6])for(i=0,await s(t);i<4;)await s([.1,.9,.5,.2][i])||console.log('YMCA'[i++])})()

```

Try it online!

i tried out the tester program and it was within about half a second for each cue but not 0.125. i think the startup time just needs to be factored in and some of the deltas may need to be adjusted to account for accumulated rounding errors.

i'm curious if there may be a shorter solution without using \>ES5 `await`, and a shorter way to print to `STDOUT`.
> 0 votes

---
Tags: code-golf, music
---


title: Alternating Triangles

text:
# Question
Title: Alternating Triangles
Given a *strictly* positive integer `n` (therefore `0` isn't a valid test case), produce an approximate triangle of height `n`.

## A non-programmatic process of drawing the picture

Initially we start with the base of the triangle.

```
|

```

So, we want to draw a triangle of a height of 5. First we know that all the `|`'s align on a straight line, and there is a missing `|` on every even position.

```
|

|

|

```

Then, we insert the `/`'s onto these empty lines, where every `/` has 1 more preceding space than the next `/`. The lowest `/` starts at 1 space.

```
|
  /
|
 /
|

```

## More reference outputs + Sample program

Here's what the program should output for inputs `1` to `9`. A sample program is available if you still don't understand the specification.

For those that don't see that it's a triangle: Take a look at this. Scroll the picture really quickly. You will see the two sides of a triangle.

```
==== 1: ====
|
==== 2: ====
 /
|
==== 3: ====
|
 /
|
==== 4: ====
  /
|
 /
|
==== 5: ====
|
  /
|
 /
|
==== 6: ====
   /
|
  /
|
 /
|
==== 7: ====
|
   /
|
  /
|
 /
|
==== 8: ====
    /
|
   /
|
  /
|
 /
|
==== 9: ====
|
    /
|
   /
|
  /
|
 /
|

```

## Specification

* Leading/Trailing whitespace is allowed.
* The string *has* to be joined with newlines, outputting a string list is not allowed.

# Answer
# 05AB1E, ~~17~~ ~~14~~ ~~13~~ 11 bytes

```
L'/ú€'|I£R»

```

-3 bytes thanks to *@Grimmy*.
-1 byte after getting inspiration from *@MagicOctopusUrn*.

Try it online or verify all test cases.

**Explanation:**

```
L            # Push a list in the range [1, (implicit) input]
             #  i.e. 5 → [1,2,3,4,5]
 '/ú        '# Pad "/" with that many leading spaces
             #  → [" /","  /","   /","    /","     /"]
    €'|     '# Put a "|" in front of each item
             #  → ["|"," /","|","  /","|","   /","|","    /","|","     /"]
       I£    # Only leave the first input amount of items
             #  → ["|"," /","|","  /","|"]
         R   # Reverse it
             #  → ["|","  /","|"," /","|"]
          »  # And join it by newlines
             #  → "|\n  /\n|\n /\n|"
             # (after which the result is output implicitly)

```
> 3 votes

# Answer
# Husk, 12 bytes

```
↔↑ṁe"|"¡Θ" /

```

Try it online!

Builds the infinite triangle upside-down, then takes the required number of lines and reverses them before printing.

### Explanation

```
↔↑ṁe"|"¡Θ" /
       ¡        Repeat and accumulate results:
        Θ          prepend a space
         " /       starting from the string " /"
                   (this will create all the lines of the slanted side)
  ṁ             For each line:
   e"|"            put it in a list with a "|" line
  ṁ             and merge all these lists together
 ↑              Take the number of lines required by the input
↔               Reverse the result

```
> 10 votes

# Answer
# Python 2, 45 bytes

```
def f(n):print n%2*'|'or n/2%n*' '+'/';f(n-1)

```

Try it online!

A function that prints, terminating with error. The `%n` in `n/2%n` is just to give an error when `n` falls to 0, but is harmless otherwise.

---

As a program

**50 bytes**

```
n=input()
while n:print n%2*'|'or n/2*' '+'/';n-=1

```

Try it online!
> 8 votes

# Answer
# Haskell, 48 bytes

```
unlines.reverse.(`take`f" /")
f c="|":c:f(' ':c)

```

Try it online!

`f" /"` generates an infinite (reversed) approximate triangle, the first line is mostly formatting.
> 4 votes

# Answer
# C (gcc), ~~52~~ 51 bytes

```
f(n){for(;n--;)printf(n&1?"%*c\n":"|\n",n/2+2,47);}

```

Try it online!
> 3 votes

# Answer
# APL (Dyalog Unicode), ~~21~~ 20 bytesSBCS

```
⊖(0⌊-\∘⍳)⌽⊢↑⍤0⍴∘'|/'

```

Try it online!

**Edit**: Use `↑⍤0` instead of `↑¨` to avoid an extraneous use of .

An anonymous tacit function. This is an improvement over Graham's APL+WIN solution using modern APL.

I was about to post a 24-byter when `-\⍳n` randomly struck my brain. It is an expression that yields first `n` terms of `0 -1 1 -2 2 -3 3 ...`, so applying `0⌊` yields `0 -1 0 -2 0 -3 0 ...` which is perfect for row-wise rotation vector.

### How it works

```
⊖(0⌊-\∘⍳)⌽⊢↑⍤0⍴∘'|/'  ⍝ Input: n
              ⍴∘'|/'  ⍝ Repeat '|/' to length n
          ⊢↑⍤0        ⍝ Create a n-by-n matrix whose 1st column is the above
                      ⍝   and the rest is blank
         ⌽            ⍝ Rotate left each row:
 (  -\∘⍳)             ⍝   First n values of 0 -1 1 -2 2 -3 3 ...
  0⌊                  ⍝   Minimum with 0; 0 -1 0 -2 0 -3 ...
                      ⍝ (Negative rotate left is rotate right)
⊖                     ⍝ Reverse vertically

```
> 3 votes

# Answer
# brainfuck, 168 bytes

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

```

Try it online, with 10 as input. There is substantial room for improvement for sure. I should try different memory layouts for the constants, for example. My pointer walks around way too much.

The commented code:

```
Divide input by two and get the mod as well
Mem layout is
input | quotient | remainder | ifelse flag | 0
,[->>>+<[-<+>>-]>[<+>->]<<<<]
Mem: ^0 | quotient | remainder | 0 | 0
Build 32 which is the SPACE character
>>>>>>>++>++
Mem: 0 | quot | rem | 0 | 0 | 0 | 0 | 2 | ^2
[-<[-<++>]<[->++<]>>]
Mem: 0 | quot | rem | 0 | 0 | 0 | 0 | 32 | ^0
Build 124 and 47 for the vertical bar and the slash
<<
++++++[-<+++++++>]<[-<+<+++>>]++++++++++<+++++<--
Mem: 0 | quot | rem | ^124 | 47 | 10 | 0 | 32
If there is a remainder print the loose vertical bar
<[->.>>.<<<]<
Mem: 0 | ^quot | 0 | 124 | 47 | 10 | 0 | 32
while there is something in the quotient
[
  print those many spaces
[->+>>>>>.<<<<<<] print as many spaces as needed
  then a slash
>>>.
  then a newline
>.
  then a vertical bar
<<.
  then a newline
>>.<<<
reset the space counter and decrement it
[-<+>]<-
] (end while)

```

that you can try at a different interpreter and to which you can pass different input numbers more easily. For example, try typing `\10` in the input bar. Then pass the commented code over this Python script to remove the comments and get the byte count.
> 3 votes

# Answer
# Python 3, ~~66~~ ~~56~~ 55 bytes

Saved a byte thanks to kaya3!!!

```
def f(n):
 if n:print((-~n//2*' '+'/','|')[n&1]);f(n-1)

```

Try it online!
> 2 votes

# Answer
# , 24 bytes

```
>@}.&,i.;&'|'@{.&'/'@->:

```

Try it online!

*-4 bytes thanks to Bubbler*
> 2 votes

# Answer
# APL+WIN, ~~36 33~~ 30 bytes

3 bytes saved by incorporating bubbler's row rotation method

Prompts for integer:

```
    ⊖(0⌊-\⍳n)⌽(n,n)↑((n←⎕),1)⍴'|/'

```

Try it online! Courtesy of Dyalog Classic
> 2 votes

# Answer
# Jelly, ~~14~~ 13 bytes

```
H⁶ṁ;”/)”|ÐoṚY

```

Try it online!

A monadic link taking an integer and returning a list of Jelly strings. If a single newline-separates string is needed, append `Y` for a cost of a byte. Thanks to @JonathanAllan for saving a byte!
> 2 votes

# Answer
# PowerShell, 42 bytes

```
"$args"..1|%{((" "*($_/2)+"/"),"|")[$_%2]}

```

Try it online!

Loops from input `$args` down to `1`, each iteration choosing whether to output spaces and a `/`, or the `|` character based on a modulo-index into an array. Default output gives us newlines for free. Ho-hum.
> 2 votes

# Answer
# Java (OpenJDK 8), 88 84 bytes

```
x->{for(int i=x,j=i+2;i-->0;j--)System.out.printf((i%2<1?"|\n":"%"+j/2+"s\n"),"/");}

```

Try it online!

If Java's output methods weren't so long, I'd get close to John's `R` submission!

Edit:
-4 bytes thanks to @Kevin Cruijssen!
Also the link led to an older 91 bytes version, fixed that now...
> 2 votes

# Answer
# Charcoal, 18 bytes

```
Ｎθ↙⊘θＵＥ⁰¦¹Ｆ⊘⊕θ«↑↑¹

```

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

```
Ｎθ

```

Input `n`.

```
↙⊘θ

```

Print the diagonal line of the appropriate length.

```
ＵＥ⁰¦¹

```

Space the rows out.

```
Ｆ⊘⊕θ«↑↑¹

```

Fill in the vertical line on alternate lines.
> 1 votes

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

```
say$_%2?$"x(1+$_/2).'/':'|'while$_--

```

Try it online!
> 1 votes

# Answer
# Jelly, 23 bytes

```
HĊ”|ẋż³HḞR¤” ẋ$;€”/¤ẎṚY

```

Try it online!

It's been a while since I've golfed in Jelly, so this answer is probably embarrassingly long.
> 1 votes

# Answer
# PHP, ~~76~~ 57 bytes

```
for(;$a=$argn--;)echo$a%2?"|
":str_repeat(' ',$a/2)."/
";

```

Try it online!

I feel there should be much better but can't put my finger on it yet.. I also didn't find how to use recursive functions with PHP7 arrow notation.. well..

EDIT: Actually, a basic loop is still better for PHP than recursion
> 1 votes

# Answer
# , ~~75~~ 61 bytes

Thanks again, Giuseppe! Forgot that cat does pasting itself.

```
for(i in scan():1)cat(`if`(i%%2,'|',c(rep('',i/2),'/')),'\n')

```

Try it online!
> 1 votes

# Answer
# , 171 bytes

```
3.6006260132602476031061101612026401020000127908906554819090552999940099999079098993139912214131211599141161115815500503615009816317991281750111717119502503616009199991194

```

Try it online!

### Explanations

```
3.    start of code
60062 assign half ASCII of pipe
60132 space
60247 slash
60310 endl
61101 int one
61202 int two
64010 int ten
2000012 multiply half-pipe by two for a pipe
790 get input
890 while there's still input
65548 char zero
1909055 decrease input char by char zero to get result
2999940 multiply previous result by ten (to make way for current char input)
0999990 put current result
790 get input again
9 end of loop
======== At this point we already got the int n
899 while (n != 0)
3139912 2141312 1159914 mod by 2 (n-[[n/2]]*2)
1161115 check odd or even
815     if odd
500 503 61500 9 print pipe and endl
816     if even
3179912 get n/2
817 501 1171711 9 print spaces
502 503 61600 9 print slash and endl
1999911 9 get n-1, end of loop
4       end of code

```
> 1 votes

# Answer
# C (gcc), 50 bytes

```
f(n){for(;n;)printf(n--%2?"|\n":"%*s/\n",n/2,"");}

```

Takes as input an integer `n` and prints a triangle. It would look more realistic and save 2 bytes if `n` was not divided by 2.

Try it online!
> 1 votes

# Answer
# Japt `-R`, 16 bytes

```
Çg['|'/iSp°Zz]Ãw

```

Try it
> 0 votes

# Answer
# Python 2, 52 bytes

```
i=input()
while i:print(' '*(i/2)+'/','|')[i%2];i-=1

```

Try it online!
> 0 votes

# Answer
# MATL, 22 bytes

```
:2&\w~*"@:~'|/'X@)hXhP

```

Try it online!
> 0 votes

# Answer
# JavaScript (ES6), 48 bytes

```
f=n=>n?(n&1?`|
`:' '.repeat(n/2)+`/
`)+f(n-1):''

```

Try it online!
> 0 votes

# Answer
# Ruby, 44 bytes

```
->n{(1..n).map{[?|," "*(n/2)+?/][(n-=1)%2]}}

```

Try it online!
> 0 votes

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

```
f=(n,s=`/
`,v=`|
`)=>--n?f(n,v,s<v?' '+s:s)+v:v

```

Try it online!
> 0 votes

# Answer
# Bash, 68 bytes

```
f(){ for((i=$1;i-->0;)){((i%2))&&printf %$[2+i/2]s\\n /||echo \|;};}

```

Try it online!

Don't golf in bash that often, so tips appreciated.
> 0 votes

# Answer
# Go, 94 bytes

```
import."fmt"
func f(n int){for n!=0{if n%2==0{Printf("%*s/\n",n/2,"")}else{Println("|")}
n--}}

```

Port of my C answer.

Try it online!
> 0 votes

# Answer
# Vyxal `j`, 15 bytes

```
ɾ\/꘍\|?ẋf$Y?wiṘ

```

Try it Online!

An attempted port of the 05AB1E answer, but not really...
> 0 votes

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


title: ASCII art is ready for take-off

text:
# Question
Title: ASCII art is ready for take-off
# Task

Given a positive integer `n`, draw the corresponding rocket.

# Examples

From `n = 1` to `4` the rockets are below. For your program's output, the trailing newline after a rocket is optional.

```
  |
 / \
*---*
| o |
| o |
*---*
 /_\

   |
  / \
 /   \
*-----*
| o o |
| o o |
| o o |
| o o |
*-----*
 /___\

    |
   / \
  /   \
 /     \
*-------*
| o o o |
| o o o |
| o o o |
| o o o |
| o o o |
| o o o |
*-------*
 /_____\

     |
    / \
   /   \
  /     \
 /       \
*---------*
| o o o o |
| o o o o |
| o o o o |
| o o o o |
| o o o o |
| o o o o |
| o o o o |
| o o o o |
*---------*
 /_______\

```

You can check this reference implementation (ungolfed).

---

This is so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it... And happy golfing!

# Answer
# PowerShell, ~~131~~ 117 bytes

```
param($n)' '*$n+" |"
$n..1|%{" "*$_+"/$(' '*++$i)\";$x="*-$('-'*++$i)*"}
$x
,("| $('o '*$n)|")*$i
$x
" /$('_'*--$i)\"

```

Try it online!

Line breaks added for clarity, but they could just as easily be `;` (it's the same byte count either way).

We're basically brute-force building the rocket one line at a time. We start by taking input `$n`, then construct a string of `$n` spaces and the nose antenna. We then loop from `$n` down to `1`, using a triangular number trick with `$i` to get the appropriate number of middle spaces for the nose cone. Including the construction of the joiner into the loop allows us to re-use `++$i` to both create the joiner and increment for our triangular number, saved into `$x` for later use.

We then use array-multiplication with the comma operator to construct the body of the rocket, then `$x` onto the pipeline again for the bottom. Finally we output the engine part with the appropriate `_` in between.

All of those strings are left on the pipeline, and default implicit output gives us newlines for free.

*-14 bytes thanks to VisualMelon.*
> 14 votes

# Answer
# Charcoal, 38 bytes

```
ＮθＰ×θ_←↗¹Ｐθ←²↑*↑⊗θ↘*ＵＯ⊕θ⊗θo ↑Ｐ⊕θ↑↗θ|‖Ｂ

```

Try it online! Link is to verbose version of code. Works by drawing the left half of the rocket and reflecting it. Explanation:

```
Ｎθ

```

Input the size of the rocket.

```
Ｐ×θ_

```

Print the `_`s at the base of the rocket.

```
←↗¹

```

Move left and print the `/` at the left of the base.

```
Ｐθ←²

```

Print the `-`s on the second layer.

```
↑*↑⊗θ↘*

```

Print the left side of the rocket, and leave the cursor inside the body.

```
ＵＯ⊕θ⊗θo ↑

```

Fill the rocket with `o`s and move the cursor up.

```
Ｐ⊕θ↑

```

Print the top row of `-`s and move the cursor up.

```
↗θ|‖Ｂ

```

Print the nose cone and reflect to complete the rocket.

Alternate solution, also 38 bytes:

```
Ｎθ×θ_↖¹Ｐ←θ²↑*Ｆ⊗θ←⪫|¶… o⊕θＰ←⁺²θ↖*↖θ|‖Ｂ←

```

Try it online! Link is to verbose version of code. Works by drawing the right half of the rocket and reflecting it. Explanation:

```
Ｎθ

```

Input the size of the rocket.

```
×θ_↖¹

```

Print the base of the rocket.

```
Ｐ←θ²↑*

```

Print the second layer.

```
Ｆ⊗θ←⪫|¶… o

```

Print the body of the rocket.

```
⊕θＰ←⁺²θ↖*

```

Print the top of the rocket.

```
↖θ|‖Ｂ←

```

Print the nose cone and reflect to complete the rocket.
> 8 votes

# Answer
# Python 2, ~~165~~ 154 bytes

```
i=input()
m=["*-"+"--"*i+"*"]
print"\n".join([" "*i+" |"]+[" "*(i-x)+"/ "+"  "*x+"\\"for x in range(i)]+m+["|"+" o"*i+" |"]*2*i+m+[" /"+"_"*(i*2-1)+"\\"])

```

Try it online!

*-11 with thanks to @wilkben for some great hints*

Nothing very exciting here. Just builds each line in a list and then prints with `'\n'.join()`.
> 8 votes

# Answer
# T-SQL, 265 bytes

```
DECLARE @n INT=0,@o varchar(max)=''z:SELECT
@o+=space(@-@n)+'/'+replicate(' ',@n*2)+' \
',@n+=1IF @n<@ GOTO z
PRINT space(@)+' |
'+@o+stuff(replicate('*'+replicate('-',@*2+1)+'*
',2),5+2*@,0,replicate('|'+replicate(' o',@)+' |
',2*@))+' /'+replicate('_',@*2-1)+'\'

```

**Try it online**
> 8 votes

# Answer
# IBM/Lotus Notes Formula Language, ~~262~~ ~~246~~ 236 bytes

```
L:=@NewLine;M:="*"+@Repeat("-";i*2+1)+"*"+L;N:=@Repeat(" ";i+1)+"|"+L;
@For(x:=0;x<i;x:=x+1;@Set("N";N+@Repeat(" ";i-x)+"/"+@Repeat(" ";x*2+1)+"\\"+L));
@Set("N";N+M+@Repeat("|"+@Repeat(" o";i)+" |"+L;2*i)+M+" /"+@Repeat("_";i*2-1)+"\\");

```

Basically a port of my Python 2 answer. Newlines in the code added for readability. They are not required by the interpreter. The formula takes it's input from `i` which is a numeric field on the same form.

There is no online interpreter for Notes formula so here is a screen shot of the output from 1 to 4:
> 4 votes

# Answer
# 05AB1E, ~~52~~ ~~50~~ ~~47~~ ~~45~~ 43 bytes

```
'|'/ILúí`©„ oI>∍'|ìI·иI>'-×'*ì.ø`®ð'_:».º.c

```

-2 bytes thanks to *@Grimmy*.

Try it online or verify some more test cases.

**Explanation:**

```
'|           '# Push a "|"
  IL          # Push a list in the range [1,input]
'/  ú        '# Push a "/" with that many leading spaces
     í        # And reverse each string so the spaces become trailing
      `       # And push all strings in this list to the stack
       ©      # Store the last one in variable `®` (without popping)
„ o           # Push string "o "
   I>         # Push the input+1
     ∍        # Extend the string to that size
      '|ì    '# And prepend a "|"
         I·   # Push the input doubled
           и  # And repeat the string that many times as list
I>            # Push the input+1 again
  '-×        '# And create a string with that many "-"
     '*ì     '# And prepend a "*"
        .ø    # Then surround the earlier created list with this string
          `   # And push all separated to the stack
®             # Push the string from variable `®` again
 ð'_:        '# And replace all its spaces with "_"
»             # Now join every string on the stack by newlines
 .º           # Mirror it intersected horizontally
   .c         # And centralize each line (which adds leading spaces where necessary)
              # (after which the result is output implicitly)

```
> 3 votes

# Answer
# C (gcc), 248 bytes

```
i;f(n){char d[i=2*n+4],o[i];d[i]=o[--i]=!memset(d,45,i);o[--i]=*o='|';*d=d[i]=42;for(i=1+n;i;)printf(--i-n?"%*s/%2$*s\\\n":"%*s|\n",i,"",~i-2*~n-i);for(puts(d);i<=4*n;)i++<=2*n?o[i]="o "[i&1]:puts(o);printf("%s\n /%.*s\\",d,--n,memset(o,95,n+=n));}

```

This is surprisingly hard to get right, especially with off-by-one errors. I still might be overflowing the stack...

I fixed the bug I mentioned with `n=23` and onwards; turns out that `i` was being decremented in the wrong place, so `o` was being overwritten and one byte of it was left uninitialized. Luckily, fixing this didn't cost me anything.

I've added a testcase for `n=50` and a fun one for `n=0`.

*-11 bytes thanks to ceilingcat!*

Try it online!

Also, here's your rocket at `n=0`:

```
 |
*-*
*-*
 /| |\

```

Looks more like space junk to me... Ungolfed and an explanation (plus this weird corner case):

```
int i;
void f(int n)
{
    char d[i=2*n+4], // holds the *---* line; 2*n+1 dashes plus an extra 3 for the asterisks and the null byte
         o[i];       // holds the | o | line; 2*n+1 for the 'o ' and extra 3 for pipes and null byte

    d[i]=o[--i]=!memset(d,45,i); // null-terminate d and o; set d to dashes starting at d + 1 and ending at d+i-2

    o[--i]=*o='|'; // set the first and last bytes of o to the pipe
    *d=d[i]=42; // set the first and last bytes of d to asterisks

    for(i=1+n;i;) // print top of rocket
        printf(--i-n?"%*s/%2$*s\\\n":"%*s|\n",i,"",~i-2*~n-i); // on first iteration, print the tip and the correct number of spaces; the * before s pads the empty string with a variable number of spaces
// after that, print the cone; use 2$*s to use the second argument to save a byte

// if anyone can figure out how to remove the need for newlines, that would be appreciated

        // print the dashed line
    for(puts(d);i<=4*n;) // generate and print the tube
        i++<=2*n? // first half of loop
          o[i]="o "[i&1] // generate ' o '
          :puts(o); // print the line
    // n+=n here doubles n for the correct number of underscores
    printf("%s\n /%.*s\\",d,--n,memset(o,95,n+=n)); // print the last dashed line and then generate the underscores and print in one go
    // it's shorter doing a sized print than null-terminating o
}

```

And for the explanation of the corner case: the leading and terminating `|` are set as well as one character (the ) but never printed because there is only one iteration (as `0 <= 0` and `0 <= 2 * 0`). Because `n` is `0`, `d` is not set by `memset`, and is printed as `| |`. The rest should be pretty self-explanatory; the middle is not printed because the loop terminates before it can begin and neither is the cone for pretty much the same reason. There's only one `-` in `*-*` because `n` is `0` (in `2n+1`).
> 3 votes

# Answer
# Ruby, 130 bytes

```
->n{["%#{n+2}s"%?|,*(1..n).map{|x|"%#{n-x+2}s%#{x*2}s"%[?/,?\\]},k="*-"+"--"*n+?*,[[?|,*[?o]*n,?|]*" "]*n*2,k," /#{?_*n+=n-1}\\"]}

```

Try it online!
> 3 votes

# Answer
# Batch, ~~700~~ ~~614~~ ~~573~~ ~~538~~ ~~498~~ 452 bytes

Notes:

* **Must be started from `cmd.exe`'s command line using:** `Echo(rockets n|cmd /V:On`, where `n` is an integer.
* Program builds the Nth rocket on a line by line basis, incrementing the values used to repeat characters using the N value
* If the file is run without a parameter, it will output rocket n 1 by default.
* lines `1` and `7` have trailing spaces

**filename**: `rockets.bat`

```
@ECHO OFF&Set $=Set
!$!}=ECHO(&!$!F=For /L %%A in (1,1,&!$!D=)Do &!$!P=^|&!$!/A _=]=W=1,H=O=2,L=3
%F:1,1=2,1%,%1%D%!$!/A W+=1,O+=1,H+=2,_+=2,L+=2
!$!.=!P!&!$![=!W!&%F%!O!%D%!$!.= !.!
%}%!.!&%F%!W!%D%(!$!.=/
%F:A=B%![!%D%!$!.= !.!
%F:A=C%!]!%D%!$!.=!.!
!$!.=!.!\&%}%!.!&!$!/A [-=1,]+=2)
!$!*=*&%F%!L!%D%!$!*=!*!-
!$!*=!*!*&%}%!*!&!$!.=!P!
%F%!W!%D%!$!.=!.!o
!$!.=!.!!P!&%F%!H!%D%%}%!.!
%}%!*!&!$!.= /&%F%!_!%D%!$!.=!.!_
!$!.=!.!\&%}%!.!

```

The ungolfed version \[1131 bytes\]
> 3 votes

# Answer
# JavaScript (ES6),  ~~158~~  156 bytes

This implements the straightforward *repeat everything* approach.

```
n=>` `[N=n*2,R='repeat'](n+1)+`|
${(g=k=>k?` `[R](k)+`/${' '[R](N-k---k)}\\
`+g(k):s=`*${'-'[R](N+1)}*
`)(n)+`|${' o'[R](n)} |
`[R](N)+s} /${'_'[R](N-1)}\\`

```

Try it online!

---

# JavaScript (ES6),  ~~164~~  162 bytes

This one builds the rocket recursively.

```
f=(n,x=y=0,w=2*++n)=>y<w+n?`/\\ |*-o
`[(x>w?x=~!++y:(y?y-n&&~y+3*n?y>n?x&1?2:x%w?6:3:x+y-n&&x-y-n&&2:x%w?5:4:x-n?2:3)||x>n)&7]+f(n,x+1,w):` /${'_'.repeat(w-3)}\\`

```

Try it online!

### Commented

```
f = (                            // f is a recursive function taking:
  n,                             //   n = size of the rocket
  x = y = 0,                     //   (x, y) = current coordinates
  w = 2 * ++n                    //   w = width of the rocket - 1; increment n
) =>                             //
  y < w + n ?                    // if this is not the last row:
    `/\\ |*-o\n`[                //   pick the next character from this string
      ( x > w ?                  //     if this is the end of the row:
          x = ~!++y              //       increment y and set x to -1
        :                        //     else:
          ( y ?                  //       if this is not the first row:
              y - n &&           //         if this is neither the top
              ~y + 3 * n ?       //         nor the bottom of the tank:
                y > n ?          //           if this is not the fairing:
                  x & 1 ?        //             if x is odd:
                    2            //               append a space
                  :              //             else:
                    x % w ? 6    //               append either a 'o'
                          : 3    //               or a '|' on the borders
                :                //           else (fairing):
                  x + y - n &&   //             append a '/' if we're located on
                  x - y - n && 2 //             a border, or a space otherwise
              :                  //         else (top or bottom of the tank):
                x % w ? 5        //           append either a '-'
                      : 4        //           or a '*' on the borders
            :                    //       else (first row):
              x - n ? 2          //         append either a space
                    : 3          //         or a '|' in the middle
          )                      //
          || x > n               //       turn '/' into '\' if we're in the right side
      ) & 7                      //     turn -1 into 7, false into 0, true into 1
    ] + f(n, x + 1, w)           //   end of character lookup; recursive call with x+1
  :                              // else:
    ` /${'_'.repeat(w - 3)}\\`   //   append the nozzle and stop the recursion

```
> 2 votes

# Answer
# Wren, 156 bytes

I am very surprised that Arnauld is so easy to outgolf ...

```
Fn.new{|n|" "*(n+1)+"|
"+(n..1).map{|i|" "*i+"/%(" "*(1+2*(n-i)))\\
"}.join()+"*%("-"*(1+2*n))*
"+"| %("o "*n)|
"*2*n+"*%("-"*(1+2*n))*
 /%("_"*(2*n-1))\\"}

```

Try it online!
> 2 votes

# Answer
# Python 2, 126 bytes

```
p=n=input()
s="_ |"+"  \/"*n+"--**"+" o||"*2*n+"--**__\/"
while s:p+=s>"^";print' '*p+s[3]+s[:2]*(n-p)+s[:4:2];s=s[4:];p-=p>0

```

Try it online!

Includes some trailing whitespace, which I hope is allowed. One of them is the first character of `s`, a `DEL` character.

The main idea is to store the design of each line of the rocket in a big template string `s`. It's a bit easier to see in this slightly less golfed version, where the template for each line is given in a list:

**134 bytes**

```
n=input()
p=n+2
w="*--*"
for a,b,c,d in["|   "]+["/  \\"]*n+[w]+["| o|"]*2*n+[w,"/__\\"]:p-=p>0;p+=c=="_";print' '*p+a+(b+c)*(n-p)+b+d

```

Try it online!

Each line of the rocket is drawn from a template like this with four characters `a,b,c,d` specified for each line:

```
  abcbcbcbcbd

```

It's an `a` followed by alternating `b`'s and `c`'s followed by a `d`. The number of leading spaces, which also governs the number of repetitions of `bc`, is given by `p`, and is updated with each new line.

I'm aware that Python 3's f-strings and walrus operator could probably shorten many things, but I like Python 2 for golfing ASCII art because it means finding hacks to do things like that instead.
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~292~~ ~~289~~ 257 bytes

Thanks to @mypronounismonicareinstate **-32B**

```
n=>{dynamic r="",t="*",i=n,j;for(;i-->0;)r+=" ";r+=" |\n";for(;++i<n;){for(j=0;j<n+i+2;++j)r+=n-i-j==0?"/":" ";r+=@"\
";}for(;i-->0;)t+="--";t+="-*\n";r+=t;for(;++i<n*2;){r+="|";for(j=0;j++<n;)r+=" o";r+=" |\n";};r+=t+" /";for(;i-->1;)r+="_";return r+"\\";}

```

Try it online!
> 1 votes

# Answer
# Perl 5, 150 +1 (-p) = 151 bytes

```
$x=($n=$_)*2;map{$r.=$"x($n-$_).'/'.$"x(2*$_+1).'\
'}0..$n-1;$s='*'.'-'x$x."-*
";$l='|'.' o'x$n." |
";$_=$"x$n.$"."|
$r$s".$l x$x."$s /".'_'x--$x.'\
'

```

Run with `-p`, provide input to stdin. Started with basically the reference implementation, and just golfed it down, though there might be better ways. I could save a byte by leaving off the final newline, but I like it better with it in.

Try it online!
> 1 votes

# Answer
# GolfScript, 95 bytes

v1.0.2, my goal is to get this sub-60, which I think is actually doable.

```
:i)" ":s*"|"n i,{:j i\-s*"/ "2s*j*"l"n}%"*-""--"i*"*"n+++:q{"| ""o "i*"|"n}2i**q" /""__"i*);"l"

```

This program uses miniscule L instead of backslash since I spent like four hours today trying to find a way for GS to print ONE backslash and couldn't get it to work. It's ridiculous. Temporary patchfix, looks acceptable in TIO.

WANNA SEE A GROSS PROGRAM?

Okay, so this is obviously a disaster, so we're going to need to go through it *very* carefully to see why it works. Let's break this into chunks.

```
:i)" ":s*"|"n                 #Top Needle
i,{:j i\-s*"/ "2s*j*"l"n}%    #Roof
"*-""--"i*"*"n+++:q           #First star-dash line
{"| ""o "i*"|"n}2i**          #Cabin
q                             #Second star-dash line
" /""__"i*);"l"               #Rocket cone

```

So, that's mildly more digestible for my format. Work is slow today, so enjoy this overly arduous explanation.

Before we start this, I'm clarifying one thing. Input is from the header, slotted right into the stack, and our output is let on the stack, printed out when the program finishes.

```
:i)" ":s*"|"n     #Print the top needle
:i                #Set our input to i; we'll call it INDEX.
  )               #Increment the INDEX on the stack by 1 (not the variable)
   " ":s          #Put a space on the stack, and make s remember it. We'll call it SPACE.
        *         #Multiply this space by INPUT+1
         "|"      #Needle!
            n     #Newline

```

So, our stack now looks something like `" ""|""/n"`, which is concatenated all together on output. Every future chunk ends with n characters, and we never back up further in the stack, so we never touch this again.

```
i,{:j i\-s*"/ "2s*j*"l"n}%    #Print the roof
i,                            #Make an array of size INDEX, from 0 to i-1
  {                     }%    #Block notation. On every element in this array, perform this
  {:j                   }%    #Remember our index as J
  {   i\-               }%    #Subtract J from INDEX
  {      s*             }%    #Make that many spaces
  {        "/ "         }%    #Make a slash then a space
  {            2s*j*    }%    #Make 2*j spaces
  {                 "l" }%    #lmao backslash no work
  {                    n}%    #Add a newline

```

Which is for what we're looking, for every line. Done INDEX times, we have our roof!. Next!

```
"*-""--"i*"*"n+++:q   #Print the star-line.
"*-"                  #First two characters.
    "--"              #Next two.
        i*            #We want a number of those double-dashes equal to INDEX.
          "*"         #Last asterisk
             n        #Newline
              +++     #Concatenate that all together. We haven't done this before, but...
                 :q   #We're remembering this entire line in Q, which saves us a TON

```

Next we have the o-cabin. Surprisingly the easiest part of the program.

```
{"| ""o "i*"|"n}2i**   #Build the cabin
                2i*    #Double INDEX
{              }   *   #Perform the block 2*INDEX times
{"| "          }   *   #First two characters
{    "o "      }   *   #You know the drill. Combination of the two prev tactics.
{        i*    }   *   #Make that many windows this row
{          "|" }   *   #East wall
{             n}   *   #Newline, as always.

```

Now comes the trickiest part of the entire program

```
q      #Print the second star line
q      #Print Q, as established above

```

And the bottom of the rocket.

```
" /""__"i*);"l"     #Bottom of the rocket
" /"                #So, how's your day been? Mine's been pretty slow.
    "__"            #Slow enough that I had time to write this whole post.
        i*          #Boss isn't even watching. Maybe I'll do another later.
          );        #Remove the last _, since we've one too many.
            "l"     #lmao backslashes

```

And that's everything! Why don't you check my work by trying it out online? 78 is the max size you can get before it starts to linebreak on TIO on my monitor, try to find yours!
> 1 votes

# Answer
# Clojure (307 bytes)

Great challenge, because it let me crank up Def Leppard's "Rocket" and Elton John's "Rocket Man" while coding. Always a plus! :-)

Golfed:

```
(defn r[n s](apply str(repeat n s)))(defn b[n](r n \ ))(defn p[s](println s))(defn k[n](let[t(str \*(r(inc (* n 2))\-)\*)](p(str(b(inc n))\|))(doseq[l(range 0 n)](p(str(b(- n l))\/(b(inc(* 2 l)))\\)))(p t)(doseq[l(range 1 (inc(* n 2)))](p(str "| "(r n "o ")\|)))(p t)(p(str " /"(r(inc(* 2(dec n)))\_)\\))))

```

Try it online!

Ungolfed:

```
(defn repeat-str [n s]
  (apply str (repeat n s)))

(defn blanks [n]
   (repeat-str n \ ))

(defn rocket [n]
  (let [ top-bottom  (str \* (repeat-str (inc (* n 2)) \-) \*) ]
    (println (str (blanks (inc n)) \|))
    (doseq [ l  (range 0 n) ]
      (println (str (blanks (- n l)) \/ (blanks (inc (* 2 l))) \\)))
    (println top-bottom)
    (doseq [ l  (range 1 (inc (* n 2))) ]
      (println (str "| " (repeat-str n "o ") "|")))
    (println top-bottom)
    (println (str " /"  (repeat-str (inc (* 2 (dec n))) \_) \\))))

```

GUITAR..! DRUMS..!
> 1 votes

# Answer
# Vyxal, 65 bytes

```
›ð*\|+,(⁰nε\/꘍nd›\\꘍+,)×⁰d›-×+:,⁰d(\|‛ o⁰*ð\|+++,),‛ /\_⁰d‹*\\++,

```

Try it Online!

Slowly constructs the string bit by bit.
> 0 votes

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