title: Maximizing output from minimal input

text:
# Question
Title: Maximizing output from minimal input
Obviously, code golfing is all about making the most of the least code. Who really cares what the actual output is?

While we have had a challenge for highest input-to-output *ratio*, this is a call for **most finite and deterministic** output with given code lengths. Ironically, this challenge is then not .

**Rules:**

1. Write three independent snippets (not full programs/functions).
2. The snippets must be in the same language.
3. Score is total number of outputted bytes.
4. Outputs may be in the form of a result, STDOUT, etc.
5. The snippets may not cause any error.
6. The snippets may cause different forms of output.
7. Trailing newline characters are not counted.
8. The first snippet must be 1 byte or the minimum length that produces at least 1 byte of output.
9. The second snippet must be one byte longer than that.
10. The third snippet must be two bytes longer than the first.

# Answer
> 26 votes
# gs2, 412 + 5.37 * 10902 \+ 1010903.1 bytes

1. `f` pushes `1\n2\nFizz\n4\nBuzz\n...\nFizzBuzz` as a `412`-byte string.
2. prints all of its permutations, so `412! * 412` characters.
3. `fôô` prints all permutations of that 412!-element list, where each element is 412 characters long, so `412 * (412!)!` bytes.

EDIT: To put things into perspective, this is at least

> 101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

bytes, dwarfing all of the other answers here so far.

# Answer
> 9 votes
# Pyth, 26 + 1140850688 + (\>4.37 × 1020201781)

I have no idea if it is possible to calculate the exact length of the output for the third program. I can only give boundaries. It'll print something between `4.37 × 10^20201781` and `1.25 × 10^20201790` characters.

```
G
yG
yyG

```

This prints:

```
abcdefghijklmnopqrstuvwxyz
['', 'a', 'b', ..., 'abcdefghijklmnopqrstuvwxyz']
[[], [''], ['a'], ['b'], ['c'], ..., ['', 'a', 'b', ..., 'abcdefghijklmnopqrstuvwxyz']]

```

The first one prints the alphabet, the second one all subsets of the alphabet, and the third one the subsets of the subsets of the alphabet, which is a list of length `2^(2^26) ~= 1.09 × 10^20201781`.

Obviously no computer ever will be able to compute this large list and output it.

# Answer
> 7 votes
## CJam, 17 + 34 + 72987060245299200000 = 72987060245299200051 bytes of output

For easier comparison, this is approximately 7.3 * 1019.

```
P
PP
Ke!

```

Prints:

```
3.141592653589793
3.1415926535897933.141592653589793
012345678910111213141516171819012345678910111213141516171918012...

```

Well, the last one consists of all permutations of `[0 1 2 ... 19]` with the numbers squished together. I wouldn't recommend trying it out... (Try it as `4e!` though to get a taste.)

Test it here: Program 1, Program 2, Sane version of program 3.

# Answer
> 4 votes
# Jelly, 1.2 × 102568 bytes of output

```
ȷ
ȷ*
ȷ*!

```

Calculates **1000**, **10001000** and **10001000!**.

Try it online: first program | second program | third program (modified)

For byte counting purposes, `ȷ` can be encoded as the byte 0xa0 in the current version of Jelly.

### How it works

In Jelly, `ȷ` can be used inside number literals as Python's `e` (scientific notation). For example, `3ȷ4` returns **30000**. In Jelly's scientific notation, the coefficient defaults to **1** and the exponent defaults to **3**, so `ȷ`, `1ȷ3` and `1000` all return the same number.

```
ȷ      Return 1000.

```

```
ȷ      Return 1000.
       Parse the remaining code as a program with input 1000.
 *     Hook; compute 1000 ** 1000.

```

```
ȷ      Return 1000.
       Parse the remaining code as a program with input 1000.
  !    Return 1000!.
 *     Fork; compute 1000 ** 1000!.

```

# Answer
> 4 votes
## Hexagony, 1 + 3 + 6 = 10 bytes of output

Well... not a very impressive score, but at least I can assert that it's optimal. With a single bytes it's impossible to print something *and* terminate, so we start with two bytes:

```
!@

```

The unfolded code is

```
 ! @
. . .
 . .

```

This prints a byte and terminates.

For three bytes of code, we can print three bytes of output. For instance:

```
o!@

```

or unfolded:

```
 o !
@ . .
 . .

```

prints `111`. Any lower-case letter from `d` to `z` works and prints its character code. Those are the only 23 ways to print 3 bytes with 3 bytes of code.

Finally, for four bytes, there are 169 ways to print 6 bytes. Since none of them do anything more interesting (except for odd control flow) than the straight-forward solution, I'll present that:

```
o!!@

```

Unfolded:

```
 o !
! @ .
 . .

```

You guessed it. It prints `111111`.

How do I know these are optimal? I adapted the brute forcer I wrote for the truth machine catalogue to look for maximum finite output in 7000 cycles (I don't think you can write a busy beaver with 4 bytes, that runs for 7000 cycles but still terminates later.)

# Answer
> 3 votes
# Python 3, 1 + 22 + 23 = 56

```
9
id
abs

```

Output

```
9
<built-in function id>
<built-in function abs>

```

Print 9 and then the definition for `id` and `abs`.

# Answer
> 3 votes
## Labyrinth, 1 + 2 + 4 = 7 bytes

Another low score, which I'm mainly posting because I've proven it to be optimal for the language.

Like Hexagony, Labyrinth can't print and terminate with a single byte, so we start with two bytes:

```
!@

```

Prints a zero and terminates.

For three bytes, we can't beat the naive solution:

```
!!@

```

This prints two bytes before terminating. There are a few other options, like printing `-1` with `(!@` or `~!@` or `,!@`. There is one pretty cool solution though which uses source code rotation:

```
!>@

```

This prints a zero, then shifts the source to become `@!>`. At that point it hits a dead end, turns around, and executes the `!` again on the way back, before terminating.

For four bytes, it's a bit more fun, because the *only* way to print 4 characters is to use the above trick:

```
!!>@

```

Print two zeroes, shift to `@!!>`, print another two zeroes.

In all of these cases I'm ignoring that you can also print a byte with `\` or `.`, because those will always print exactly one byte, whereas `!` will print at least one and potentially several.

# Answer
> 3 votes
## Seriously, 2025409 bytes

1 byte:

```
N

```

(produces 11,756 bytes of output)

2 bytes:

Produces 153,717 bytes of output

3 bytes:

```
9!!

```

Produces 1,859,936 bytes of output

Seriously does not yet feature things like "all subsets" or "all combinations", so scores relatively low on this.

# Answer
> 2 votes
# MATL, 313

The current version of the language (3.1.0) is used, which is earlier than this challenge.

1. Code (predefined literal: produces number 2, which is implicitly printed):

```
H

```

Output (1 byte):

```
2

```
2. Code (produces number pi, which is implicitly printed with 15 decimals):

```
YP

```

Output (17 bytes):

```
3.141592653589793

```
3. Code (numbers from 1 to 99, which are printed by default with spaces in between):

```
 99:

```

Output (295 bytes):

```
1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

```

# Answer
> 2 votes
# Processing, 39 bytes

### Deterministic

**1 byte**:

```
print(X);

```

Outputs `0`.

**9 bytes**:

```
print(PI);

```

Outputs `3.1415927`

**29 bytes**:

```
print(P3D);

```

Outputs `processing.opengl.PGraphics3D`

## Non-deterministic, \>= 129 bytes

**\>= 32 bytes:**

```
print(g);

```

Outputs `processing.awt.PGraphicsJava2D@ + [mem-address]`

**\>= 32 bytes:**

```
print( g);

```

Outputs `processing.awt.PGraphicsJava2D@ + [mem-address]`

**\>= 65 bytes:** (Thank you to @anOKsquirrel for this suggestion.)

```
print(g,g);

```

Outputs

```
processing.awt.PGraphicsJava2D@ + [mem-address]
processing.awt.PGraphicsJava2D@ + [mem-address]

```

# Answer
> 2 votes
# JavaScript, 1 + 3 + 18 = ~~18~~ 22

Not a very interesting answer but probably the best JavaScript is capable of.

```
alert(1)
alert(.1)
alert(1/9)

```

*Added 4 score thanks to @UndefinedFunction!*

Outputs as text:

```
1
0.1
0.1111111111111111

```

# Answer
> 2 votes
# Bash, 1726 bytes

(I fixed it now. Please consider upvoting.)

**1 byte**: `"`

Outputs:

```
>

```

**307 bytes:** `id`

Outputs:

```
uid=501(geokavel) gid=20(staff) groups=20(staff),701(com.apple.sharepoint.group.1),12(everyone),61(localaccounts),79(_appserverusr),80(admin),81(_appserveradm),98(_lpadmin),33(_appstore),100(_lpoperator),204(_developer),395(com.apple.access_ftp),398(com.apple.access_screensharing),399(com.apple.access_ssh)

```

**1418 bytes:** `zip` (Prints to STDOUT)

```
Copyright (c) 1990-2008 Info-ZIP - Type 'zip "-L"' for software license.
Zip 3.0 (July 5th 2008). Usage:
zip [-options] [-b path] [-t mmddyyyy] [-n suffixes] [zipfile list] [-xi list]
  The default action is to add or replace zipfile entries from list, which
  can include the special name - to compress standard input.
  If zipfile and list are omitted, zip compresses stdin to stdout.
  -f   freshen: only changed files  -u   update: only changed or new files
  -d   delete entries in zipfile    -m   move into zipfile (delete OS files)
  -r   recurse into directories     -j   junk (don't record) directory names
  -0   store only                   -l   convert LF to CR LF (-ll CR LF to LF)
  -1   compress faster              -9   compress better
  -q   quiet operation              -v   verbose operation/print version info
  -c   add one-line comments        -z   add zipfile comment
  -@   read names from stdin        -o   make zipfile as old as latest entry
  -x   exclude the following names  -i   include only the following names
  -F   fix zipfile (-FF try harder) -D   do not add directory entries
  -A   adjust self-extracting exe   -J   junk zipfile prefix (unzipsfx)
  -T   test zipfile integrity       -X   eXclude eXtra file attributes
  -y   store symbolic links as the link instead of the referenced file
  -e   encrypt                      -n   don't compress these suffixes
  -h2  show more help
```

# Answer
> 2 votes
# Befunge, 2 + 4 + 6 = 12

```
.@
..@
...@

```

Any snippet shorter than length 2 either cannot output, or cannot terminate its output.

In Befunge, `.` outputs the top value of the stack as an integer, followed by a space. A space is not a newline, so it is included in the count. Additionally, the stack is "infinitely" filled up with 0's, so the programs output (respectively):

```
0
0 0
0 0 0

```

# Answer
> 2 votes
# SmileBASIC, 1+4+10= 15 bytes

### Program 1:

The shortest way to print something is with ? (PRINT) and a single character. This can be either a number or a variable name, and it doesn't matter since they're all the same length.

```
?1
1

```

### Program 2:

Now we have access to a few more things. The longest expression which can be made would be one of the constants #Y, #L, or #R, which have values 128, 256, and 512, respectively. However, instead of that, I use a comma so that (in this case) 3 extra spaces are printed.

```
?1,
1

```

### Program 3:

With 3 characters, you can write E-notation numbers:

```
?1E9
1000000000

```

# Answer
> 2 votes
# Japt `-Q`, Outputs `1.0123378918474279e+150` bytes

The full number is

```
1,012,337,891,847,427,807,734,770,805,740,683,255,348,979,141,331,502,541,182,800,555,980,960,810,784,280,906,237,433,006,787,771,597,919,201,659,212,694,207,520,340,705,280,000,000,000,000,000,000,568

```

bytes.

## \# 1

```
M

```

Outputs

```
{"P":3.141592653589793,"Q":1.618033988749895,"T":6.283185307179586}

```

For 67 bytes. (Credit to Shaggy)

## \# 2

Outputs

```
[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null]

```

which is 501 bytes.

(Credit to @Shaggy)

## \# 3

```
;Eá

```

Outputs all permutations of the 95 printable ASCII characters in the format `["...","...","..."...]`, which is

\\$1,012,337,891,847,427,807,734,770,805,740,683,255,348,979,141,331,502,541,182,800,555,980,960,810,784,280,906,237,433,006,787,771,597,919,201,659,212,694,207,520,340,705,280,000,000,000,000,000,000,001\\$ bytes of output.

---

You can get an infinite amount of output bytes if you use the `-F` flag in Japt. What it does is that if the last expression of the program evaluates to false, it outputs the value specified in the flag instead. So I guess the score for Japt`-F"Insert Super Long String Here"` is infinity.

# Answer
> 2 votes
# HQ9+, 71304

```
9

```

Prints the 11,884-character lyrics of "99 bottles of beer"

```
99

```

Prints "99 bottles of beer" twice

```
999

```

Prints "99 bottles of beer" three times

# Answer
> 2 votes
# Malbolge, 1 + 2 + 3 = 6 bytes

```
(=aN
(&a`M
(=a`_L

```

Try it online: first, second, third

Outputs:

```
r
ll
xxx

```

Brute forced. Assumes `\0` is not a valid output character

With `\0`:

```
cP
cbO
cbaN

```

Outputs:

```
\0
\0\0
\0\0\0

```

# Answer
> 1 votes
# scg, 1 + 27 + 188 = 216

First one:

```
1

```

Just prints 1, as the stack is outputted at the end of program.

Second:

```
.d

```

Prints debug info, which should look like this:

```
Stack: []
Array Markers: []

```

Third:

```
99r

```

adds 99 to stack, then uses range function. Outputs 01234567891011.... (this is one of those times I wish I implemented the factorial function. I haven't)

# Answer
> 1 votes
## Marbelous 1 + 1 + 2 = 4 bytes of output

Marbelous is hamstrung here by having two-byte instructions. Pointless comments or unnecessary whitespace are the only ways to get an odd byte count.

print "A" and terminate:

```
`A

```

print "B" and terminate, with an empty EOL comment

```
`B#

```

print "CD" and terminate:

```
`C`D

```

# Answer
> 1 votes
## Mathematica, 6 + 461 + 763 = 1230 ~~1225~~ ~~618~~ ~~163~~ bytes of output

```
%  (* -> Out[0] *)

?D  (* ->

D[f, x] gives the partial derivative ∂ f/∂ x.
                                              n        n
D[f, {x, n}] gives the multiple derivative ∂  f/∂ x .
D[f, x, y, …] differentiates f successively with respect to x, y, ….
D[f, {{x , x , …}}] for a scalar f
        1   2
     gives the vector derivative (∂ f/∂ x , ∂ f/∂ x , …).
                                             1             2
D[f, {array}] gives a tensor derivative.

*)

?Do (* ->

Do[expr, {i   }] evaluates expr i    times.
           max                   max
Do[expr, {i, i   }] evaluates expr with the variable i successively taking on the values 1 through i    (in steps of 1).
              max                                                                                max
Do[expr, {i, i   , i   }] starts with i = i   .
              min   max                    min
Do[expr, {i, i   , i   , di}] uses steps di.
              min   max
Do[expr, {i, {i , i , …}}] uses the successive values i , i , ….
               1   2                                     1   2
Do[expr, {i, i   , i   }, {j, j   , j   }, …] evaluates expr looping over different values of j, etc. for each i.
              min   max        min   max

*)

```

Currently, the last two use `Information` to get documentation about the symbols, which can output many bytes. Note that this was run on the 10.1 command-line `MathKernel`.

# Answer
> 1 votes
# Javascript, 72 bytes

This works in the Mozilla JSShell Javascript command line interpreter.

**1 byte:** `1`

Outputs `1`

**35 bytes:** `gc`

Outputs

```
function gc() {
    [native code]
}

```

**36 bytes:** `run`

Outputs

```
function run() {
    [native code]
}

```

# Answer
> 1 votes
# Octave, 2818417 bytes

```
e

```

14 bytes for `ans = 2.7183\n`

```
pi

```

14 bytes for `ans = 3.1416\n`

```
doc

```

Display the entire documentation. 2818389 bytes, counted with `dd` Try it online! because `evalc` didn't work.

# Answer
> 1 votes
# SmileBASIC 4, 1 + 13 + 15 = 29 bytes

This is going to be similar to 12Me21's SmileBASIC 3 answer, with a couple adjustments.

## 1

As before, the shortest amount of code to produce some output is 2 bytes: `?` (`PRINT`) and some single-byte expression. The consensus is that `PRINT` does *not* produce a newline when it advances to the next line, due to the way the text screen works. So this results in one byte of output.

```
?1
1

```

## 2

With 3 bytes, we can do something different. SB4 introduces `INSPECT`, aliased as `??`, which prints info about a single value. If we give it an empty string, for example, this can produce much more output than SB3 could. This gets us 13 bytes.

```
??"
STRING: (0)""

```

## 3

We have 4 bytes to work with, so we have to decide what we should do to maximize our output. Going with `??` is a safe bet; we only have 2 bytes to use on our expression, but the additional output of `INSPECT` is basically free. So I use it to print a label string. This is 15 bytes.

```
??@A
STRING: (2)"@A"

```

The total is 29 bytes.

# Answer
> 1 votes
# \[Julia 0.6\] REPL, 94354 bytes

```
9[enter] # output 9, 1 byte
[tab][tab] # output all possible auto completes for the empty string, 31451 bytes
[tab][tab][tab] # output all possible auto completes for the empty string twice, 62902 bytes

```

There is nothing special about 0.6 here, I just don't have 1.0 installed locally. Not counting command prompts as output, or `[enter]` as input, and requiring each to be independent of the previous.

# Julia 1.0 program, 562 bytes

```
dump(!)
dump(!!)
dump(!!!)

```

Optimizing output to `STDOUT` here. I'm not sure how to even calculate the byte size for results, eg `!` returns a function with 3 methods... there are multiple reasonable interpretations for how many bytes that represents, and most of them aren't easy to count. I'm not sure if this is optimal, it just builds up an anonymous function with a long name and prints the name. Try it online!

# Answer
> 0 votes
# Microscript II, 23+47+71=141 bytes

1: `C`

The stringification of continuations is not strictly defined by the specs, but in the reference implementation this, run on its own, yields a 23 byte string.

`<Continuation @t=\d\d\dus>` (`\d` represents a digit, which digits varies).

On my computer, at least, this does, in fact, always take between about 180 and about 400 microseconds to run.

The first use I've ever actually had for this instruction.

2: `CP`

47 bytes of output- the output from the first one twice with a newline in between.

3: `CPP`

Fairly straightforward. 71 bytes of output- the output from the first one three times with newlines in between.

# Answer
> 0 votes
## PowerShell, ~4300 bytes

Approximate output length, given the system that it's run on. All the snippets below are deterministic, in that if given the same initial state of the computer will output the same text, just that in practice the output could change from execution to execution.

### Length 1, 107 bytes

```
?

```

This is an alias for `Where-Object`. It will output a user prompt asking for additional information:

```
cmdlet Where-Object at command pipeline position 1
Supply values for the following parameters:
Property:

```

### Length 2, 113 bytes

```
rp

```

This is an alias for `Remove-ItemProperty`. It will output a user prompt asking for additional information:

```
cmdlet Remove-ItemProperty at command pipeline position 1
Supply values for the following parameters:
Path[0]:

```

Just barely longer than the length 1 snippet.

### Length 3, ~4100 bytes

```
gps

```

This is an alias for `Get-Process` which will output a formatted table of all running processes on the system:

```
Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
     85       8     1232       4452    46     0.14    544 armsvc
    151      10     6800       9888    39     0.58   5116 audiodg
    480      25     6060      17200   124     0.84   4536 AuthManSvr
...

```

# Answer
> 0 votes
## Javascript, 312 + 318 + 624 = 1254 bytes of output

```
$
$$
$+$

```

The two functions `$` and `$$` are available in all major browsers' consoles, as shortcuts for `document.querySelector` and `document.querySelectorAll` respectively. Different browsers have native code coerced to strings somewhat differently from each other, and IE uses plain JS in each function resulting in much longer representation.

For the byte count, I'm taking the length of the string representation of each rather than the sometimes-modified console display, so the total bytes are, for each of the following browsers:

* Chrome: 56 + 57 + 112 = 225 bytes
* IE: 312 + 318 + 624 = 1254
* Firefox: 33 + 33 + 66 = 132

(I'm considering the IE result to be the "official" count because it's the longest.)

For non-console browser environments, the largest outputs come from the following:

```
1
!1 // Or '{}' if being fed to a function instead of beginning a statement
Map

```

Results length by browser:

* Chrome: 1 + 5 (or 15 if `{}` is usable) + 32 = 38 (or 48) bytes
* IE: 1 + 5 (or 15 if `{}` is usable) + 38 = 44 (or 54)
* Firefox: 1 + 5 (or 15 if `{}` is usable) + 36 = 42 (or 52)

These two sets of input produce the largest output possible in all of these browsers and consoles. To prove this, let's check all alternatives:

* Existing variables: We can find all native available variables with maximum three characters with `Object.getOwnPropertyNames(window).filter(x=>x.length<=3)`, and then `map` them to their string outputs to determine the larger ones. (Note that in some browsers such as Firefox, certain special console variables cannot be accessed this way as they're not a property of the window.)
* JS has a limited number of types of literals that can be created with so few characters:
    + Per the spec, decimal numbers must be a decimal digit (`1234567890`) optionally followed by `.` and more decimal digits and/or an exponent part, or be a `.` followed by one or more decimal digits and optionally an exponent part. Other kinds of numbers must be either `0o`, `0x`, or `0b` (or uppercase forms), followed by one or more digits. For our purposes, we can deduce the following:
        - There are only ten single-character numbers, which are the integers 0 through 9. The only two-character numbers are integers 0-99 (0-9 by adding a decimal after), and the numbers 0.1 through 0.9 by omitting the initial zero. The only three-character numbers are 0-999, including 0x0-0xf, 0o0-0o7, 0b0, and 0b1, the exponential 1e1 through 9e9 (10 characters), and the numbers 0.1-9.9 and .01 through .99. While not technically a number literal, NaN can also be referenced in three characters.
    + Strings, arrays, and regexps, each of which can take at max only a single character of content. An array could be filled with `$`, a comma, or a single-digit number. Arrays with only one element are coerced to strings as the element itself. Empty arrays become empty strings.
    + Depending on environment, it may or may not be possible to create simple objects with three characters. Normally, `{}` alone at the beginning of a script would be treated as an enclosure rather than creating an object. `eval({})` returns undefined, `eval({$})` returns the `$` function. There are insufficient characters to surround the `{}` in `()`.
* There are no keywords that are short enough to use. The keywords `if`, `in`, `do`, `new`, `for`, `try`, `var`, and `let` would all require a minimum of two other characters to use, exceeding the limit.
* Available unary operators include `~`, `+`, `-`, `!`, `++`, and `--`. The two-character operators can only be used with a single character variable, of which there is only one (`$`), which yields `NaN`. The other four operators can be used with any one- or two- character value, of which there are:
    + Several variables. (On some consoles `$`, `$_`, `$0`, `$1`, `$2`, `$3`, `$4`, `$`, `$$`, `$x` ). When used with these operators, the results are limited to `-1`, `true`, `false`, and `NaN`.
    + 109 numbers. Results: Integers -100 through 99, -0.9 through -0.1, `true`, `false`.
    + Empty strings. Results: `-1`, `0` (`-0` becomes `0` on toString), `true`.
    + The results of any of the one-character values above associated with a one-character unary operator. New results: None.
* Usable binary operators (which must be a single character to have room left for both operands) are `+`, `-`, `*`, `/`, `%`, `<`, `>`, `&`, `|`, `^`. They can only be used with a single-character value on each side. Options for values include `$` and integers 0-9. Results of all combinations of these include `Infinity`, some numbers and binary values mentioned above, and numerous fractions which are coerced to strings of 19 characters or less (`1/7` is 19 characters, unlike `1/9` suggested above which is only 18), and the text representation of `$` preceded or followed by a single-digit integer or itself.
* Finally, all remaining operators and expressions: The member operator `.` requires an existing variable and a identifier referring to a property. All uses of this here result in `undefined`. Surrounding a value in `(` `)` returns the value, as does assigning it with `=`. Using `()` or \`\` to call a value as a function results in undefined or errors with all available values.

Adding all this up, there are a grand total of 1651 possible outputs when using a Chrome console. The longest outputs for one, two, and three characters are from `$`, `$$`, and `$+$` respectively.

# Answer
> 0 votes
# dc, 2+5+18=25 bytes

1: `Ff` yields (Try it online!):

```
15

```

2: `Fdf` yields (Try it online!):

```
15
15

```

3: `Fd^f` yields (Try it online!)

```
437893890380859375

```

None of which are particularly interesting, but `dc` isn't really great for spitting out piles of output. I do like that each answer builds on the previous. Anyway, `F` is just the number 15; `f` prints the entire stack; `d` duplicates top-of-stack; `^` raises next-to-top-of-stack to the power of top-of-stack (in this case, 15^15). I don't believe this can be topped in `dc`.

# Answer
> 0 votes
# Ruby, 3+14+28 = 45 bytes

Why did I do this.

```
p

```

Prints `nil`.

```
$>

```

Prints `#<IO:<STDOUT>>`.

```
dup

```

Prints something along the lines of `#<Object:0x0000000003610988>`.

```
irb

```

Launches an instance of Interactive Ruby. Upon exiting, the returned object is `#<IRB::Irb: @context=#<IRB::Context:0x0000000003643040>, @signal_status=:IN_EVAL, @scanner=#<RubyLex:0x00000000038900a0>>` for 121, but since it requires you to press `^D` or something to actually exit the irb instance, I wasn't sure if it'd actually count as a solution in "3 bytes" so I'm not actually including it in the score unless it gets an OK.

# Answer
> 0 votes
# Perl 6, 53 (17 + 18 + 18) bytes

```
e
-e
e*e

```
1. `e` outputs \\$e\\$ to 15 decimal places
2. `-e` outputs \\$-e\\$ to 15 decimal places
3. `e*e` outputs \\$e^2\\$, but oddly, it gives one more decimal place

# Answer
> 0 votes
# Runic Enchantments, 4,000,000 bytes of output

The first program is:

```
a@

```

Takes 2 bytes to: push a value to the stack, print a value from the stack, and terminate. In this case it prints `10` (though any integer value from 0 to 16 are also just as valid)

For 3 bytes:

```
aY@

```

Prints `10000`, Again, `a` could be 1 through 16 inclusive (in order to generate more output than the original program, 0 is potentially valid under other operators) and there aren't a whole lot of operators that take a single input and produce any output, much less *longer* output. `XCYZ:E` are the only real options. `aY@` is just the one that results in the *most* output.

```
P$!;

```

According to language specification, this runs infinitely. However as the interpreter has a built in "ok, that's enough" maximum execution limit, this is the most output achievable in 4 characters (and TIO cuts off execution after ~130,000 bytes for exceeding 128kib) and as the interpreter defines the language, this works. And while I have raised that threshold once before (from 10k steps to 1 million), I don't plan on messing with it any time soon.

## Bigger?

If I invoke the three assumptions I made here, then sure.

```
`AA@

```

Which works out to `Ack(65,Ack(65,64))`, which aren't terribly large values to go shoving into the Ackerman function initially--certainly smaller than the 255 in the older post--but its ok, we can call Ack twice in 4 instructions.

And only god knows what it'll print.

Note: the `A` instruction has since then been made the `Math` meta-instruction, which consumes 3 objects on the stack: a char for what instruction to perform and then two inputs, x and y. As such this program doesn't actually do anything, both because neither `A` nor `@` map to a math function and because two subsequent calls results in a stack underflow.

# Answer
> 0 votes
# Ruby, 3 + 278 + 7827 = 8108

As in "Works on my machine - YMMV"

```
#

```

prints `nil` (3 bytes)

```
$:

```

prints the LOAD\_PATH variable, which is 278 bytes on my machine

```
p$"

```

prints all module names loaded by require. When running in irb, this is 7827 bytes.

---
Tags: code-challenge, restricted-source, busy-beaver, code-shuffleboard
---


# Question
Title: Implement Homestuck's Catenative Doomsday Dice Cascader
# Challenge

I'm under attack by the larcenous Midnight Crew and I need to summon the Catenative Doomsday Dice Cascader in order to defend myself. Since I'm low on space, I need the code to be as short as possible.

The algorithm for the Catenative Doomsday Dice Cascader is as follows:

First, the six sided die in the Prime Bubble is rolled, and the result will determine how many iterations of the next step take place.

Start with a six sided die. For as many times as the roll of the Prime Bubble die, multiply the number of sides on the next die by the result of the roll of the current die. For example, if on your first roll of the six-sided die your roll is 2, then your next die will have 6\*2 = 12 sides.

Your goal is to write a function or program that takes no input and outputs the final result of the last die rolled. Since this is , the lowest byte count in each language wins!

# Examples

Example #1 (Taken directly from the link above):

```
The Prime Bubble rolls a 6, meaning that the Cascader will iterate six times

#1: We always start with a 6 sided die, and it rolls a 2, so the next die has 6x2=12 sides
#2: The 12 sided die rolls an 8, meaning that the third die has 12x8=96 sides
#3: The 96 sided die rolls a 35, meaning that die 4 has 96x35=3360 sides
#4: The 3360 sided die rolls a 2922, so die 5 has 3360x2922 = 9,817,920 sides
#5: The 9.8 million sided die rolls a 5,101,894, so the final die has 50,089,987,140,480 sides
#6: The 50 trillion sided die rolls a one. Hooray.
Since the last die rolled gave a 1, your function or program should output 1.
```

Example #2

```
The Prime Bubble rolls a 2, meaning that the Cascader will iterate twice.

#1: We always start with a 6 sided die, and it rolls a 4, so the next die has 6x4 = 24 sides
#2: The 24 sided die rolls a 14

Since the last die rolled gave a 14, your function or program should output 14.

```

# Answer
> 8 votes
# Python 2, ~~76~~ 69 bytes

```
from random import*
R=randint
v=6;exec"p=R(1,v);v*=p;"*R(1,6)
print p

```

Try it online!

# Answer
> 8 votes
# Perl 6, ~~43~~ 37 bytes

*-6 bytes thanks to nwellnhof*

```
{(6,{roll 1..[*] @_:}...*)[1+6.rand]}

```

Try it online!

Anonymous code block that returns the doomsday dice result.

### Explanation:

```
{                                   }   # Anonymous code block
 (                       )[1+6.rand]    # Take a random number from
                     ...*               # The infinite list of
  6,{roll 1..[*] @_:}                   # Cascading dice values
  6,                                    # Starting from 6
    {roll          :}                   # And choosing a random value from
          1..                           # One to
             [*] @_                     # The product of every value so far

```

# Answer
> 7 votes
# Wolfram Language (Mathematica), 43 bytes

```
(r=RandomInteger)@{1,Nest[r@{1,#}#&,6,r@5]}

```

Try it online!

# Answer
> 5 votes
# , 21 bytes

```
1+[:?(*1+?)^:(?`])@6x

```

Try it online!

*+6 bytes thanks to a logic problem spotted by FrownyFrog*

NOTE: J has no niladic verbs. However, this verb will work the same no matter what argument you give it. In the TIO example, I'm calling it with `0`, but I could have used `99` or `''` just as well.

## how

* `1+` add one to...
* `[:?` a single roll of an n-sided die (sides reading `0` to `n-1`), where the number `n` is determined by...
* `(*1+?)` take the current argument `y` and roll `?` to produce a random number between `0` and `y-1`. `1+` makes that `1` to `y`, inclusive. Finally the `*` creates a J hook, which will multiply that by `y` again.
* `^:` do the above this many times...
* `(?`])` `?` roll the initial argument, which is `6`, to determine how many times to repeat. If we roll `0` (corresponding to a `1` on the Prime Bubble), the argument will pass through unchanged. The `]` indicates that `6`, unchanged, will be the starting value of repeated `(*1+?)` verb that determines the die value for the final roll.
* `@6x` attaches the constant verb `6`, so that we can call it with anything, and the `x` forces J to use extended integer computation which we need for the possibly huge numbers.

# Answer
> 4 votes
# K (oK), 32 bytes

**Solution:**

```
*|{x,1+1?x:(*).x}/[*a;6,a:1+1?6]

```

Try it online!

Start with 6 and "1 choose 6", iterate over "1 choose 6" times:

```
*|{x,1+1?x:(*).x}/[*a;6,a:1+1?6] / the solution
  {             }/[n;    c     ] / iterate over lambda n times with starting condition c
                            1?6  / 1 choose 6, between 0..5 (returns a list of 1 item)
                          1+     / add 1 (so between 1..6)
                        a:       / store as 'a'
                      6,         / prepend 6, the number of sides of the first dice
                   *a            / we are iterating between 0 and 5 times, take first (*)
           (*).x                 / multi-argument apply (.) multiply (*) to x, e.g. 6*2 => 12
         x:                      / save that as 'x'
       1?                        / 1 choose x, between 0..x-1
     1+                          / add 1 (so between 1..x)
   x,                            / prepend x
*|                               / reverse-first aka 'last'

```

You can see the iterations by switching the over for a scan, e.g.

```
(6 3        / 1 choose 6 => 3, so perform 3 iterations
 18 15      / 1 choose (6*3=18) => 15
 270 31     / 1 choose (18*15=270) => 31
 8370 5280) / 1 choose (270*31=8730) => 5280

```

# Answer
> 4 votes
# Jelly, 9 bytes

```
6X×$5Ð¡XX

```

A niladic Link which yields a positive integer.

**Try it online!**

Saving a byte over the more obvious `6X×$6X’¤¡X`

### How?

```
6X×$5Ð¡XX - Link: no arguments
6         - initialise left argument to 6
    5Ð¡   - repeat five times, collecting up as we go: -> a list of 6 possible dice sizes
   $      -   last two links as a monad = f(v):           e.g [6,18,288,4032,1382976,216315425088]
 X        -     random number in [1,v]                     or [6,6,6,6,6,6]
  ×       -     multiply (by v)                            or [6,36,1296,1679616,2821109907456,7958661109946400884391936]
       X  - random choice (since the input is now a list) -> faces (on final die)
        X - random number in [1,faces]

```

# Answer
> 3 votes
# 05AB1E, 10 bytes

```
X6DLΩF*DLΩ

```

The random choice builtin for large lists is pretty slow, so may result in a timeout if the Prime Bubble roll is for example a 6.

Try it online or try it online with added prints to see the rolls. (TIO uses the legacy version of 05AB1E, since it's slightly faster.)

**Explanation:**

```
X           # Push a 1 to the stack
 6          # Push a 6 to the stack
  D         # Push another 6 to the stack
   L        # Pop the top 6, and push a list [1,2,3,4,5,6] to the stack
    Ω       # Pop and push a random item from this list (this is out Prime Bubble roll)
     F      # Loop that many times:
      *     #  Multiply the top two values on the stack
            #  (which is why we had the initial 1 and duplicated 6 before the loop)
       D    #  Duplicate this result
        LΩ  #  Pop and push a random value from its ranged list again
            # (after the loop, output the top of the stack implicitly)

```

# Answer
> 3 votes
# Jelly, 9 bytes

```
6×X$X’$¡X

```

Try it online!

Jonathan Allan's answer claims that it's

> Saving a byte over the more obvious `6X×$6X’¤¡X`

. In fact, we don't need to make such a big modification. Therefore, this is an alternative approach to Jonathan Allan's answer, and, also, a resting place for my initial invalid 6-byter. :(

# Answer
> 2 votes
# Python 3, 76 bytes

```
from random import*
r=randint
a=6
for i in" "*r(0,5):a*=r(1,a)
print(r(1,a))

```

Try it online!

-2 bytes thanks to TFeld

# Answer
> 2 votes
# Perl 5, 54 bytes

```
$a=6;map$a*=$r=1+int rand$a,0..rand 6;say 1+int rand$r

```

Try it online!

# Answer
> 2 votes
# Charcoal, 16 bytes

```
⊞υ⁶Ｆ⊕‽⁶⊞υ⊕‽ΠυＩ⊟υ

```

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

```
⊞υ⁶

```

Push 6 to the predefined list.

```
Ｆ⊕‽⁶

```

Repeat a random number of times from 1 to 6...

```
⊞υ⊕‽Πυ

```

... push a random number between 1 and the product of the list to the list.

```
Ｉ⊟υ

```

Output the last number pushed to the list.

Alternative approach, also 16 bytes

```
≔⁶θＦ‽⁶≧×⊕‽θθＩ⊕‽θ

```

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

```
≔⁶θ

```

Set the number of sides to 6.

```
Ｆ‽⁶

```

Repeat a random number between 0 and 5 times...

```
≧×⊕‽θθ

```

... multiply the number of sides by a random number from 1 to the number of sides.

```
Ｉ⊕‽θ

```

Print a random number from 1 to the number of sides.

# Answer
> 2 votes
# , 43 bytes

```
s=sample
for(i in 1:s(k<-6))T=s(k<-k*T,1)
T

```

Try it online!

`k` keeps track of the current number of faces on the die. Uses the fact that `T` is initialized as `1`.

I tried a few other things, but couldn't beat this simple, straightforward approach.

# Answer
> 1 votes
# Jelly, 10 bytes

```
6×X$6X’¤¡X

```

Try it online!

### Explanation

```
       ¤   | Following as a nilad:
    6X     | - A random number between 1 and 6
      ’    | - Decrease by 1 (call this N)
6          | Now, start with 6
   $    ¡  | Repeat the following N times, as a monad
 ×         | - Multiply by:
  X        |   - A random number between 1 and the current total
         X | Finally, generate a random number between 1 and the output of the above loop

```

# Answer
> 1 votes
# Java 10, ~~214~~ ~~93~~ 86 bytes

```
v->{int r=6,n=0;for(var d=Math.random()*6;d-->0;n*=Math.random(),r*=++n)n=r;return n;}

```

Try it online or try it online with additional print-lines to see the steps.

-128 bytes by using `int` instead of `java.math.BigInteger`. \\$6^{32}\\$, the largest possible result, doesn't fit inside an `int` nor `long`, which is why `BigInteger` was used initially. OP allowed to use `int` and assuming it's infinitely large, so that saved more than 125 bytes here. :) (Here the previous **214 bytes** version using `BigIntegers`.)

**Explanation:**

```
v->{                        // Method with empty unused parameter & integer return-type
  int r=6,                  //  The range in which to roll, starting at 6
      n=0;                  //  The roll itself (which must be initialized, therefor is 0)
  for(var d=Math.random()*6;//  Roll the Prime Bubble Dice
      d-->0                 //  Loop that many times:
      ;                     //    After every iteration:
       n*=Math.random(),    //     Roll a random dice in the range [0, n)
       r*=++n)              //     Increase `n` by 1 first with `++n`, so the range is [1,n]
                            //     And then multiply `r` by `n` for the new range
    n=r;                    //   Set `n` to `r`
  return n;}                //  After the loop, return `n` as result

```

# Answer
> 1 votes
# Ruby, 41 bytes

```
r=6;rand(2..7).times{r*=$s=rand 1..r};p$s

```

Try it online!

**Explanation**

```
r=6                                 # Set dice number to 6

rand(2..7).times{               }   # Repeat X times, where X=dice roll+1
                 r*=$s=rand 1..r    # Multiply dice number by a dice roll
                                    # Save the most recent dice roll

p$s                                 # Print last dice roll (this is why
                                    #  we did the last step one extra time)

```

# Answer
> 0 votes
# PHP, 59 bytes

```
$r=$q=rand(1,$s=6);while($l++<$q)$r=rand(1,$s*=$r);print$r;

```

expanded:

```
$r=$q=rand(1,$s=6);
while($l++<$q)$
    r=rand(1,$s*=$r);
print$r;

```

Not sure if I'm supposed to include the open tag.

On my machine, it crashes if `$s*$r` is too large, so it doesn't print on `$q>=5` sometimes... because the numbers get so big. Not sure of a fix.

# Answer
> 0 votes
# C# (.NET Core), 136 bytes

```
class A{static void Main(){var r=new System.Random();int i=r.Next(6),j=6;while(i-->0)j*=1+r.Next(j);System.Console.Write(r.Next(j)+1);}}

```

Try it online!

I'm *pretty* sure this works, given the assumption of infinite integer length that we're fond of here. If I have to actually handle the overflow, I'd need to bust out an entirely different class.

# Answer
> 0 votes
# Pyth, 14 bytes

```
uhO=*|Z6GO6hO6

```

Try it online!

```
uhO=*|Z6GO6hO6
         O6      Random number in range [0-6)
u                Perform the following the above number of times...
           hO6   ... with starting value G a random number in range [1-6]:
    *   G          Multiply G with...
     |Z6           The value of Z, or 6 if it's the first time through (Z is 0 at program start)
   =  Z            Assign the above back into Z
  O                Random number in range [0-Z)
 h                 Increment
                 Implicit print result of final iteration

```

# Answer
> 0 votes
# Gaia, 13 bytes

```
:(ṛ×
6₅ṛ(↑ₓ(ṛ

```

Try it online!

# Answer
> 0 votes
# Julia 1.0, 60 bytes

```
g(b=big(6),r=rand)=(for i in 1:r(0:5) b=b*r(1:b) end;r(1:b))

```

`b=big(6)` makes it work with arbitrary sized integers Try it online!

---
Tags: code-golf, random
---


title: Take a break to make a snake!

text:
# Question
Title: Take a break to make a snake!
Our classic snake has developed an inbalance of growth hormones. To make matters worse, his tail is frozen in place! Given directional input as specified in `Figure 1`, write a program to determine where he will grow.

*Figure 1.* Directional input.

# Program specifications

* Read the **input** character by character on `STDIN`.
* After reading a character, **output** the snake to `STDOUT`. Please include a blank line in between each time you print a snake.
* The snake consists of `<>v^` and a head. The head of the snake may be any round character of your choosing, such as `o`, `0`, `O`, or .
* Any combination of `wasd` is valid for input.
* Your program should not assume the input is within a certain length.
* The snake can pile on top of itself, overwriting `<>v^`. See examples for snake growing mechanics.
* Trailing whitespace is okay, but your snake must look correct.

# Scoring

This is . Your score is the number of characters in your program. Lowest score wins!

# Example snakes:

**Input:** `ddddssaassdddddww`

**Output:**

```
>>>>v
    v
  v<<  ☺
  v    ^
  >>>>>^

```

---

**Input:** `dddsssaaawww`

**Output:**

```
☺>>v
^  v
^  v
^<<<

```

---

**Input:** `dddsssdddddasddddwww`

**Output:**

```
>>>v
   v       ☺
   v       ^
   >>>>v<  ^
       >>>>^

```

---

**Input:** `dddwwdddssssaaaaaaaaawww`

**Output:**

```
      >>>v
☺     ^  v
^  >>>^  v
^        v
^<<<<<<<<<

```

---

**Input:** `ddddssssaawwddddd`

**Output:**

```
>>>>v
    v
  >>>>>☺
  ^ v
  ^<<

```

---

**Input:** `dddddssaawwwwddddd`

**Output:**

```
   >>>>>☺
   ^
>>>^>v
   ^ v
   ^<<

```

---

**Input:**

```
ddddaaaasssssdddddddddddwwwwwaaaasssssdddddddddddwwwwwwwwwwsssssaaaasssssdddddddwwwwwddddssaaaasssddddaaaassssssssssdddwwwwwwwddddswaaaassssddaasssaaaaaaaaaawwwwddddssssaaaaaaaaaaawwwwddddsssssssssaaaa

```

**Output:**

```
                  v
                  v
                  v
                  v
                  v
v<<<<  v<<<<  v<<<<  >>>>v
v      v   ^  v   ^  ^   v
v      v   ^  v   ^  v<<<<
v      v   ^  v   ^  v
v      v   ^  v   ^  v
>>>>>>>>>>>>>>>>>>>>>v<<<<
                     v
                     v
                     v  v<<<<
                     v  v   ^
                     v  v
       >>>>v  >>>>v  v  v
       ^   v  ^   v  v  v<<
       ^   v  ^   v  v  v
       ^   v  ^   v  v  v
       ^<<<v<<<<<<<<<<<<<
           v
           v
           v
           v
       O<<<<

```

# Answer
# Ruby, 207 characters

```
b=[];x=y=0;gets.chars{|c|b[y]||=[];b[y][x]={?\n=>->{?0},?w=>->{y>0?y-=1:b=[[]]+b;?^},?a=>->{x>0?x-=1:b.map!{|r|[' ']+r};b[y][1]=?<},?s=>->{y+=1;?v},?d=>->{x+=1;?>}}[c][]};puts b.map{|r|r.map{|c|c||' '}.join}

```

Ungolfed:

```
b=[]  #board
x=y=0 #position
gets.each_char{|c|
  b[y] ||= []
  b[y][x] = {
    "\n" => lambda{0},
    "w"  => lambda{if y>0 then y-=1 else b=[[]]+b; "^"},
    "a"  => lambda{if x>0 then x-=1 else b.map!{|r|[' ']+r}; b[y][1]="<"},
    "s"  => lambda{y+=1; "v"},
    "d"  => lambda{x+=1; ">"}
  }[c].call}
puts b.map{|r|r.map{|c|c||' '}.join}

```

(the lambda for `a` writes back because the row the assignment above writes to is no longer on the board)
> 5 votes

# Answer
# ECMAScript 6 Javascript (399 ~~401~~ ~~431~~)

Has to be run in a browser supporting ECMAScript 6 due to the arrow functions.

Here are fiddles which have been altered to run in any (common) browser by not using arrow functions. They also print to a `textarea` instead:

## Golfed Version

```
i=prompt(),v=[],c=0,x=[0],y=[0],s='unshift',k='slice',t='sort',h=[0,-1,0,1,0]
while(c<i.length){m='wasd'.indexOf(i[c++]);v[s]('^<v>'[m]);x[s](x[0]+h[m]);y[s](y[0]+h[m+1])}f=(a,b)=>a-b
q=x[k]()[t](f)[0],e=x[k]()[t]((a,b)=>b-a)[0],w=y[k]()[t](f)[0],o=[]
while((i=y.pop())!=null){i-=w;j=x.pop()-q;t=(o[i]||Array(e+1-q).join(" ")).split("");t.splice(j,1,v.pop()||"@");o[i]=t.join("")}alert(o.join("\n"))

```

## Animated GIF:

One of the OP's examples:

The example from Stretch Maniac:

## Ungolfed

Here is a (slightly) ungolfed version from sometime before I started *really* golfing it down:

```
var input = prompt(),
    values = [],
    c = 0,
    x = [0],
    y = [0],
    s = 'unshift';
while (c < input.length) {
    var mapped = 'wasd'.indexOf(input[c++]);
    values[s]('^<v>'[mapped]);
    x[s](x[0]+[0, -1, 0, 1][mapped]);
    y[s](y[0]+[-1, 0, 1, 0][mapped]);
}

var minX = x.slice().sort(function (a,b){return a-b})[0];
var maxX = x.slice().sort(function (a,b){return b-a})[0];
var minY = y.slice().sort(function (a,b){return a-b})[0];

var output = [];
while((i=y.pop())!=null) {
    i-=minY;
    j=x.pop()-minX;
    t=(output[i]||Array(maxX+1-minX).join(" ")).split("");
    t.splice(j,1,values.pop()||"@");
    output[i]=t.join("");
}

console.log(output.join("\n"));

```
> 11 votes

# Answer
# sed, 71

```
s/w/\^\x1B[D\x1B[A/g
s/a/<\x1B[2D/g
s/s/v\x1B[B\x1B[D/g
s/d/>/g
s/$/@/

```

# Golfscript, ~~165~~ 126

```
' '*"\33[":e{e'D'}:-{[e'C'+'<'--]]}:a{[-+'>']]}:d{[e'B'+'^'-e'A']]}:w{[e'A'+'v'-e'B']]}:s{][\[}:+7{;}*''\~[e'H'e'J']\'@'e'20H'

```

Same approach as my previous answer, but correctly positioning the cursor before and afterwards. I'm pretty proud of the approach to cursor positioning -- basically, it first runs the snake in reverse, without printing out characters.
> 8 votes

# Answer
# Java - 646

Might as well be the first one!

I bet you all can beat this.

un(sort of)golfed

```
import java.util.*;
public class Snake{
    public static void main(String[]a) {
        int x,y,minX,minY,maxX,maxY;
        x=y=minX=maxX=minY=maxY=0;
        List<Integer>xs,ys=new ArrayList<Integer>();
        xs=new ArrayList<Integer>();
        List<Character>p=new ArrayList<Character>();
        for(int b=0;b<a[0].length();b++){
            int newX=x,newY=y;
            switch(a[0].charAt(b)){
            case'a':newX--;p.add('<');break;
            case's':newY++;p.add('v');break;
            case'd':newX++;p.add('>');break;
            case'w':newY--;p.add('^');break;
            }
            xs.add(x);ys.add(y);
            x=newX;y=newY;
            if(x<minX){minX=x;}
            if(x>maxX){maxX=x;}
            if(y<minY){minY=y;}
            if(y>maxY){maxY=y;}
        }
        char[][]c=new char[maxY-minY+1][maxX-minX+1];
        for(int i=0;i<xs.size();i++)c[ys.get(i)-minY][xs.get(i)-minX]=p.get(i);
        c[y-minY][x-minX]='@';
        for(char[]k:c){for(char l:k){System.out.print(l);}System.out.println();}
    }
}

```

Smaller -

```
import java.util.*;class S{public static void main(String[]a){int x,y,o,z,s,u;x=y=o=s=z=u=0;List<Integer>j,t=new ArrayList<Integer>();j=new ArrayList<Integer>();List<Character>p=new ArrayList<Character>();for(int b=0;b<a[0].length();b++){int e=x,r=y;switch(a[0].charAt(b)){case'a':e--;p.add('<');break;case's':r++;p.add('v');break;case'd':e++;p.add('>');break;case'w':r--;p.add('^');break;}j.add(x);t.add(y);x=e;y=r;if(x<o)o=x;if(x>s)s=x;if(y<z)z=y;if(y>u)u=y;}char[][]c=new char[u-z+1][s-o+1];for(int i=0;i<j.size();i++)c[t.get(i)-z][j.get(i)-o]=p.get(i);c[y-z][x-o]='@';for(char[]k:c){for(char l:k){System.out.print(l);}System.out.println();}}}

```

input - dddsssdddwwwwaaaaaaaassssssssssddddddddddddddddd

```
v<<<<<<<<
v >>>v  ^
v    v  ^
v    v  ^
v    >>>^
v
v
v
v
v
>>>>>>>>>>>>>>>>>@

```

input - dddsssdddddasddddwww

```
>>>v
   v       @
   v       ^
   >>>>v<  ^
       >>>>^

```

my personal favorite - dwdwdwddaasassdddddwdwdwddsdswawaasassdddddddwdwdwddsdswawaasassddddwwwwwwwssssssdsdddwwwwddaassddaassddddsssdddwdwdwddaasasassddddwwwwssssssssasasaaawdwwdwddwwdddddddwdwdwddsdswawaasassddddddddddwwdwwwwaasssassdsdddddddwdwdwwwwasasssssssssssdwwwwwwwddd

```
                    v
                    v
                    v
                    v   v<<
   v<<   v<<     v<<v   v
  v<    v< ^<   v< ^v   v<<                        v<<     v<
 >v    >v   ^  >v   >v  v                          v ^    v<^
>^>>>>>^>>>>>>>^>>>>^>>>>>>>v    v<v               v ^    v ^
                            v   v< v       v<<    v< ^    v ^
                            v  v<  v      v< ^<   v >^    v>^
                            >>>v   v     >v   ^   >v^     v>>>@
                               >>>>>>>>>>^>>>>>>>>>>>>>>>>v^
                                  ^v                      v^
                                >>^v                      v^
                               >^  v                      v^
                               ^  v<                      v^
                              >^ v<                       v^
                              ^<<<                        >^

```
> 3 votes

# Answer
# C# 607

```
namespace System{using B=Text.StringBuilder;class P{static void Main(){var f=new Collections.Generic.List<B>(){new B("O")};int w=1,r=0,c=0;for(Action R=()=>f[r].Append(' ',w-f[r].Length+1);1>0;){var key=Console.ReadKey(1>0).KeyChar;if(key=='w'){f[r][c]='^';if(--r<0)f.Insert(r=0,new B());R();f[r][c]='O';}if(key=='a'){f[r][c]='<';if(--c<0){foreach(var s in f)s.Insert(c=0,' ');w++;}R();f[r][c]='O';}if(key=='s'){f[r][c]='v';if(++r>f.Count-1)f.Add(new B());R();f[r][c]='O';}if(key=='d'){f[r][c]='>';if(++c>w++)foreach(var s in f)s.Append(' ');R();f[r][c]='O';}Console.WriteLine(string.Join("\n",f)+"\n");}}}}

```

"Ungolfed" with whitespace (this will not be kept in sync with the golfed version):

```
namespace System
{
    using B = Text.StringBuilder;
    class P
    {
        static void Main()
        {
            var f = new Collections.Generic.List<B>() { new B("O") };
            int w = 1, r = 0, c = 0;
            Action R = () => f[r].Append(' ', w - f[r].Length + 1);
            while (true)
            {
                char key = Console.ReadKey(1>0).KeyChar;
                if (key == 'w')
                {
                    f[r][c] = '^';
                    if (--r < 0) { f.Insert(0, new B()); r = 0; }
                    R();
                    f[r][c] = 'O';
                }
                if (key == 'a')
                {
                    f[r][c] = '<';
                    if (--c < 0)
                    {
                        foreach (var s in f)
                            s.Insert(0, ' ');
                        w++;
                        c = 0;
                    }
                    R();
                    f[r][c] = 'O';
                }
                if (key == 's')
                {
                    f[r][c] = 'v';
                    if (++r > f.Count - 1) f.Add(new B());
                    R();
                    f[r][c] = 'O';
                }
                if (key == 'd')
                {
                    f[r][c] = '>';
                    if (++c > w++)
                    {
                        foreach (var s in f)
                            s.Append(' ');
                    }
                    R();
                    f[r][c] = 'O';
                }

                Console.WriteLine(string.Join("\n", f) + "\n");
            }
        }
    }
}

```
> 2 votes

# Answer
# Python 3: 259 Bytes

```
x=y=0
b,p,r={},(0,-1,0,1),range
while 1:
 d='wasd'.index(input());b[(x,y)]='^<v>'[d];x+=p[d];y-=p[~d];b[(x,y)]='☺';l,m=([k[i]for k in b]for i in(0,1))
 for j in r(min(m),max(m)+1):print(''.join(b[(i,j)]if(i,j)in b else' 'for i in r(min(l),max(l)+1)))
 print()

```

I decided to store the snake in a dict, with coordinates for the keys. Then find and iterate over the output range, substituting blank spaces.

```
x = y = 0
board = {}
while 1:
    d = 'wasd'.index(input())
    board[(x, y)] = '^<v>'[d] # body
    x += (0, -1, 0, 1)[d]
    y -= list(reversed((0, -1, 0, 1)))[d]
    board[(x,y)] = '☺' # head

    xs, ys= ([coord[dim] for coord in board] for dim in(0, 1))
    for j in range(min(ys), max(ys)+1):
        print(''.join(board[(i,j)] if (i,j) in board else ' '
                      for i in range(min(xs), max(xs)+1)))
    print()

```

PS. My first Golf :) Let me know if my answer is inappropriate
> 2 votes

# Answer
## Python 2.7 - 274 bytes

```
x,y,m,d,r=0,0,{},(0,-1,0,1),range
for c in raw_input():b='wasd'.index(c);m[(x,y)]='^<v>'[b];x+=d[b];y-=d[~b];m[(x,y)]='@';l,n=([k[h] for k in m] for h in (0, 1))
for j in range(min(n),max(n)+1):print(''.join(m[(i,j)] if (i,j) in m else ' 'for i in range(min(l),max(l)+1)))

```

## Ungolfed version

```
x,y,matrix,delta = 0,0,{},(0, -1, 0, 1)
for c in raw_input('Command: '):
    d = 'wasd'.index(c)
    matrix[(x, y)] = '^<v>'[d]
    x += delta[d]
    y -= list(reversed(delta))[d]
    matrix[(x, y)] = '@'
xs, ys = ([xy[i] for xy in matrix] for i in (0, 1))
for j in range(min(ys), max(ys)+1):
    print(''.join(matrix[(i, j)] if (i, j) in matrix else ' '
                  for i in range(min(xs), max(xs)+1)))

```
> 2 votes

# Answer
# 05AB1E, ~~35~~ ~~34~~ ~~30~~ 28 bytes

```
.•₃º•"<>v^"©‡0ªÐUĀ>sŽO^®XkèΛ

```

Uses `0` as head of the snake.

-4 bytes thanks to *@Grimy*.

Try it online (no test suite for all test cases at once, because there is no way to reset the Canvas, so outputs would overlap..).

**Explanation:**

```
.•₃º•          # Push compressed string "adsw"
     "<>v^"    # Push string "<>v^"
           ©   # Save it in variable `r` (without popping)
            ‡  # Transliterate the (implicit) input-string,
               # replacing all "adsw" with "<>v^" respectively
               #  i.e. "ddddssaassdddddww" → ">>>>vv<<vv>>>>>^^"
0ª             # Convert the string to a list of characters, and append a 0 (for the head)
               #  → [">",">",">",">","v","v","<","<","v","v",">",">",">",">",">","^","^","0"]
  Ð            # Triplicate this list of characters
   U           # Pop and store one of the three lists in variable `X`
   Ā           # Trutify each character ("0" remains 0; everything else becomes 1)
    >          # And then increase each integer by 1
               #  → [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1]
  s            # Swap the two lists on the stack
      ®Xk      # Get the index of each character of variable `X` in variable `r` ("<>v^")
               #  i.e. [">",">",">",">","v","v","<","<","v","v",">",">",">",">",">","^","^","0"]
               #   → [1,1,1,1,2,2,0,0,2,2,1,1,1,1,1,3,3,-1]
   ŽO^   è     # And use those to index into the compressed number 6240
               #  → [2,2,2,2,4,4,6,6,4,4,2,2,2,2,2,0,0,0]
Λ              # Use the Canvas builtin with these three lists

```

See this 05AB1E tip of mine (sections *How to compress strings not part of the dictionary?* and *How to compress large integers?*) to understand why `.•₃º•` is `"adsw"` and `ŽO^` is `6240`.

As for a brief explanation of the Canvas builtin `Λ` and its three arguments:

**First argument: length(s):** the sizes of the lines we want to draw. Since we have to keep in mind overlapping, we use size 2 for every character, and an additional 1 for the head of the snake.
**Second argument: string(s):** the characters we want to display. Which are the characters in this case, appended with the head-character of the snake.
**Third argument: direction(s):** the directions these character-lines of the given length should be drawn in. In general we have the directions `[0,7]` which map to these directions:

```
7   0   1
  ↖ ↑ ↗
6 ← X → 2
  ↙ ↓ ↘
5   4   3

```

Which is why we have the integer `6240` for the directions \\$\[←,→,↓,↑\]\\$ respectively.

See this 05AB1E tip of mine for a more detailed explanation about the Canvas builtin `Λ`.
> 2 votes

# Answer
# Perl - 394

Not the shortest, but it beats Javascript, C# and Java at least.

```
use List::Util qw(min max);sub c{()=$_[0]=~/$_[1]/g}%l=(a,['<',-1,0],d,['>',1,0],w,['^',0,-1],s=>['v',0,1]);($s,$x,$y,$w,$h)=($ARGV[0],0,0,max(c($s,a),c($s,d)),max(c($s,w),c($s,'s')));@s=split'',$s;map$x=min($x,$i+=$l{$_}[1]),@s;$i=0;map$y=min($y,$i+=$l{$_}[2]),@s;$x=abs $x;$y=abs $y;map{$m[$y][$x]=$l{$_}[0];$x+=$l{$_}[1];$y+=$l{$_}[2]}@s;$m[$y][$x]='o';map{map{print$_||' '}@$_;print"\n"}@m

```

Some tricks:

* Warnings and strict not turned on to allow barewords and not declaring variables before using them
* Thin commas instead of fat commas to save a few characters
* Not setting initial values for variables when not necessary
* Leaving out semi-colons when possible
* Defining arrays and hashes not as references to avoid having to use -\>
* Allowing width, height to be larger than necessary to avoid having to calculate them accurately (which would take extra code)

Things that hurt:

* No built-in way to count number of characters in a string (might have been longer anyway)
* No built-in min/max functions, thus need to waste 27 characters to import library that does it (less than defining our own)
> 1 votes

# Answer
# C - 273 bytes - with Interactive Input!

```
#define F for(i=w*w
*g,*G,x,i,j,w,W,u;main(w){putch(1);F;j=-~getch();g=G){if(!(x%w&&~-~x%w&&x/w&&x/w^~-w)){W=w+6;G=calloc(W*W,4);F-1;u=i%w+i/w*W-~W*3,i==x?x=u:8,i;)G[u]=g[i--];free(g);w=W;}G[x]="<^X>v"[j%=7];G[x+=1-G[x]%3+W*(!!j-j/2)]=1;F;i;)putch(i--%W?G[i]?G[i]:32:10);}}

```

The field is printed each time a character is entered and grows if the snake's head nears the edge. I don't know how portable it is--someone on the Internet said getch() doesn't work on non-Windows platforms. Hard to say whether ASCII 1 will look like a smiley face either.

The golfed version is quite annoying as there is no way to gracefully exit the program. Control-C doesn't work for me. On the other hand, the ungolfed version terminates if a character other than 'w', 'a', 's', or 'd' is entered.

So-called "ungolfed":

```
#define SMILEYFACE 1
int main()
{
    int o;
    int w = 1;
    int *g = 0, *g2;
    int c, n;
    int x = 0;
    for( putch(SMILEYFACE);c = getch(); ) {
        if(c!='w'&&c!='a'&&c!='s'&&c!='d')
            return 1;
        if(!(x%w) | !(~-~x%w) | !(x/w)  | !(x/w-~-w) ) {
            int wnew = w + 4;
            int off = 2;
            g2 = calloc(wnew*wnew,sizeof(int));
            for(n = w*w; --n; )
                g2[ n%w+off + (n/w+off)*wnew ] = g[n];
            free(g);
            g = g2;
            x = (x/w+off)*wnew + x%w + off;
            w = wnew;
        }
        int i = -~c%7;
        g[x] = "<^X>v"[i];
        int dx = 1-g[x]%3 + w * (!!i-i/2);
        x += dx;
        g[x] = SMILEYFACE;
        for(o = w*w; o; )
            putch(o--%w?g[o]?g[o]:32:10);

    }
    return 0;
}

```
> 1 votes

# Answer
# 05AB1E, 23 bytes

```
Ç7%DÉ+D"^>>v"ºsè0ªDĀ>rΛ

```

Try it online!

Explanation:

```
                      # implicit input (eg: "wasd")
Ç                     # codepoints (eg: [119, 97, 115, 100])
 7%                   # modulo 7 (eg: [0, 6, 3, 2])
   DÉ+                # plus itself modulo 2 (eg: [0, 6, 4, 2])
# This is the list of directions that will be passed to 05AB1E's canvas function, Λ.
# 0 means up, 6 left, 4 right, 2 down.

 "^>>v"º              # "^>>v", horizontally mirrored (namely "^>>vv<<^")
D       sè            # index into this with a copy of the list of directions
          0ª          # append "0"
# This is the list of strings that will be drawn.

D                     # duplicate the list of strings
 Ā                    # truthify (maps letters to 1, 0 stays 0)
  >                   # increment each
# This is the list of lengths to draw.

r                     # reverse the stack because Λ takes arguments in the opposite order
 Λ                    # draw!

```
> 1 votes

---
Tags: code-golf
---


title: Convert integer to balanced dozenal

text:
# Question
Title: Convert integer to balanced dozenal
Create a function which takes an integer and returns an array of integers representing the number in balanced base twelve. Specifically, the representation should follow these rules regarding 6 & -6 (from the above link):

> 1. If the last digit of a number could be written with either **6** or **ϑ**, we use the one whose sign is *opposite* the sign of the first digit. For example, we write decimal ***30*** as dozenal , but decimal ***-30*** as as dozenal **ε6**, not **ζϑ**.
> 2. If a **6** or **ϑ** occurs before the last digit of a number, we use the one whose sign is *opposite* the next digit after it. For example, we write decimal ***71*** as dozenal , but decimal ***73*** as as dozenal **1ϑ1**, not **61**.
> 3. If a **6** or **ϑ** is followed by a **0**, we keep looking to the right until we can apply one of the first two rules. For example, we write decimal ***-72*** as dozenal **τ60**, not **ϑ0**.

Otherwise, the only restrictions are to use only digits in \[-6..6\], and for the output, when interpreted as big-endian base twelve, to be equivalent to the input.

Example of use:

```
f(215) => [1,6,-1]
f(216) => [2,-6,0]
f(-82) => [-1,5,2]
f(0)   => [0]

```

Winner is the shortest, with upvotes being the tiebreaker.

# Answer
### GolfScript, 69 53 49 characters

```
[.0<\{.12:^%.3$5+>{^-\^+\}*@1$.0<@if@^/.}do;;]-1%

```

GolfScript expression which takes top of the stack and replaces it by the result. You can play with the code online.
> 1 votes

# Answer
## J, ~~74~~ 72 characters

Here's my J implementation (`f =.` not included in character count):

```
f =. **}.^:(*@#*0={.)@([:((12-~[),0>:@{.@]`[`]}])`,@.(6>[)/&.|.0,12&#.^:_1)@|

```

And some tests (each result is boxed, and underscore means negative):

```
   NB. Integers [-10..10]:
   (<@f"0)i:10
┌────┬────┬────┬────┬────┬──┬──┬──┬──┬──┬─┬─┬─┬─┬─┬─┬────┬────┬────┬────┬────┐
│_1 2│_1 3│_1 4│_1 5│_1 6│_5│_4│_3│_2│_1│0│1│2│3│4│5│1 _6│1 _5│1 _4│1 _3│1 _2│
└────┴────┴────┴────┴────┴──┴──┴──┴──┴──┴─┴─┴─┴─┴─┴─┴────┴────┴────┴────┴────┘
   NB. Some boundary values:
   (<@f"0)215 216 217 71 72 73
┌──────┬──────┬──────┬────┬──────┬──────┐
│1 6 _1│2 _6 0│2 _6 1│6 _1│1 _6 0│1 _6 1│
└──────┴──────┴──────┴────┴──────┴──────┘

```

Interestingly, the rules for 6 have no special place in the function. They work that way just by handling all digits \>= 6 together and only working on positive numbers.

I made another version, which doesn't rely on `#.^:_1`, but it's longer:

```
**_2&([:}.^:(0={.)+/\)@(((<.@%&12,(1,-&12)`(0,])@.(6>])@(12&|))@{.,}.)^:(0~:{.)^:_)@(,&0)@|

```
> 3 votes

# Answer
# APL(NARS), 71 chars, 142 bytes

```
{⍵=0:,0⋄⍵{⍵=0:⍬⋄((m+⍺×m=0)∇⌊12÷⍨⍵+q),m←t-q←12×(6<t)+(⍺>0)×6=t←12∣⍵}⍨×⍵}

```

test:

```
  z←{⍵=0:,0⋄⍵{⍵=0:⍬⋄((m+⍺×m=0)∇⌊12÷⍨⍵+q),m←t-q←12×(6<t)+(⍺>0)×6=t←12∣⍵}⍨×⍵}
  ⎕fmt z¨215 216 ¯82 0 30 ¯30 71 72 73 ¯72
┌10──────────────────────────────────────────────────────────────────────────────────────┐
│┌3──────┐ ┌3──────┐ ┌3──────┐ ┌1─┐ ┌2────┐ ┌2────┐ ┌2────┐ ┌3──────┐ ┌3──────┐ ┌3──────┐│
││ 1 6 ¯1│ │ 2 ¯6 0│ │ ¯1 5 2│ │ 0│ │ 3 ¯6│ │ ¯3 6│ │ 6 ¯1│ │ 1 ¯6 0│ │ 1 ¯6 1│ │ ¯1 6 0││
│└~──────┘ └~──────┘ └~──────┘ └~─┘ └~────┘ └~────┘ └~────┘ └~──────┘ └~──────┘ └~──────┘2
└∊───────────────────────────────────────────────────────────────────────────────────────┘

```
> 0 votes

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


title: Warped chessboard

text:
# Question
Title: Warped chessboard
This challenge is about building a chessboard in which the square size, instead of being constant across the board, follows a certain non-decreasing sequence, as described below.

The board is defined iteratively. A board of size \\$n \times n\\$ is enlarged to size \\$(n+k)\times(n+k)\\$ by extending it down and to the right by a "layer" of squares of size \\$k\\$, where \\$k\\$ is the greatest divisor of \\$n\\$ not exceeding \\$\sqrt{n}\\$. The squares in the diagonal are always of the same colour.

Specifically, consider the board with colours represented as `#` and `+`.

1. Initialize the chessboard to

```
#

```
2. The board so far has size \\$1\times 1\\$. The only divisor of \\$1\\$ is \\$1\\$, and it does not exceed \\$\sqrt{1}\\$. So we take \\$k=1\\$, and extend the board by adding a layer of squares of size \\$1\\$, with `#` in the diagonal:

```
#+
+#

```
3. The board built so far has size \\$2 \times 2\\$. The divisors of \\$2\\$ are \\$1,2\\$, and the maximum divisor not exceeding \\$\sqrt{2}\\$ is \\$1\\$. So again \\$k=1\\$, and the board is extended to

```
#+#
+#+
#+#

```
4. Size is \\$3 \times 3\\$. \\$k=1\\$. Extend to

```
#+#+
+#+#
#+#+
+#+#

```
5. Size is \\$4 \times 4\\$. Now \\$k=2\\$, because \\$2\\$ is the maximum divisor of \\$4\\$ not exceeding \\$\sqrt 4\\$. Extend with a layer of thickness \\$2\\$, formed by squares of size \\$2\times 2\\$, with colour `#` in the diagonal:

```
#+#+##
+#+###
#+#+++
+#+#++
##++##
##++##

```
6. Size is \\$6 \times 6\\$. Now \\$k=2\\$. Extend to size \\$8 \times 8\\$. Now \\$k=2\\$. Extend to size \\$10 \times 10\\$. Now \\$k=2\\$. Extend to size \\$12 \times 12\\$. Now \\$k=3\\$. Extend to size \\$15\\$:

```
#+#+##++##++###
+#+###++##++###
#+#+++##++#####
+#+#++##++##+++
##++##++##+++++
##++##++##+++++
++##++##++#####
++##++##++#####
##++##++##++###
##++##++##+++++
++##++##++##+++
++##++##++##+++
###+++###+++###
###+++###+++###
###+++###+++###

```

Note how the most recently added squares, of size \\$3 \times 3\\$, have sides that partially coincide with those of the previously added squares of size \\$ 2 \times 2 \\$.

The sequence formed by the values of \\$k\\$ is non-decreasing:

```
1 1 1 2 2 2 2 3 3 3 3 4 4 4 6 6 6 6 6 6 ...

```

and does not seem to be in OEIS. However, its cumulative version, which is the sequence of sizes of the board, is A139542 (thanks to @Arnauld for noticing).

# The challenge

**Input**: a positive integer \\$S\\$ representing the number of layers in the board. If you prefer, you may also get \\$S-1\\$ instead of \\$S\\$ as input (\\$0\\$-indexed); see below.

**Output**: an ASCII-art representation of a board with \\$S\\$ layers.

* Output may be through STDOUT or an argument returned by a function. In this case it may be a string with newlines, a 2D character array or an array of strings.
* You can consistently choose **any two characters** for representing the board.
* You can consistently choose the **direction** of growth. That is, instead of the above representations (which grow downward and rightward), you can produce any of its reflected or rotated versions.
* Trailing or leading **space** is allowed (if output is through STDOUT), as long as space is not one of the two characters used for the board.
* You can optionally use "**\\$0\\$-indexed**" input; that is, take as input \\$S-1\\$, which specifies a board with \\$S\\$ layers.

Shortest code in bytes wins.

# Test cases

`1`:

```
#

```

`3`:

```
#+#
+#+
#+#

```

`5`:

```
#+#+##
+#+###
#+#+++
+#+#++
##++##
##++##

```

`6`:

```
#+#+##++
+#+###++
#+#+++##
+#+#++##
##++##++
##++##++
++##++##
++##++##

```

`10`:

```
#+#+##++##++###+++
+#+###++##++###+++
#+#+++##++#####+++
+#+#++##++##+++###
##++##++##+++++###
##++##++##+++++###
++##++##++#####+++
++##++##++#####+++
##++##++##++###+++
##++##++##+++++###
++##++##++##+++###
++##++##++##+++###
###+++###+++###+++
###+++###+++###+++
###+++###+++###+++
+++###+++###+++###
+++###+++###+++###
+++###+++###+++###

```

`15`:

```
#+#+##++##++###+++###+++####++++####
+#+###++##++###+++###+++####++++####
#+#+++##++#####+++###+++####++++####
+#+#++##++##+++###+++#######++++####
##++##++##+++++###+++###++++####++++
##++##++##+++++###+++###++++####++++
++##++##++#####+++###+++++++####++++
++##++##++#####+++###+++++++####++++
##++##++##++###+++###+++####++++####
##++##++##+++++###+++#######++++####
++##++##++##+++###+++#######++++####
++##++##++##+++###+++#######++++####
###+++###+++###+++###+++++++####++++
###+++###+++###+++###+++++++####++++
###+++###+++###+++###+++++++####++++
+++###+++###+++###+++###++++####++++
+++###+++###+++###+++#######++++####
+++###+++###+++###+++#######++++####
###+++###+++###+++###+++####++++####
###+++###+++###+++###+++####++++####
###+++###+++###+++###+++++++####++++
+++###+++###+++###+++###++++####++++
+++###+++###+++###+++###++++####++++
+++###+++###+++###+++###++++####++++
####++++####++++####++++####++++####
####++++####++++####++++####++++####
####++++####++++####++++####++++####
####++++####++++####++++####++++####
++++####++++####++++####++++####++++
++++####++++####++++####++++####++++
++++####++++####++++####++++####++++
++++####++++####++++####++++####++++
####++++####++++####++++####++++####
####++++####++++####++++####++++####
####++++####++++####++++####++++####
####++++####++++####++++####++++####

```

`25`:

```
#+#+##++##++###+++###+++####++++##########++++++######++++++######++++++++++++++########++++++++########++++++++########
+#+###++##++###+++###+++####++++##########++++++######++++++######++++++++++++++########++++++++########++++++++########
#+#+++##++#####+++###+++####++++##########++++++######++++++######++++++++++++++########++++++++########++++++++########
+#+#++##++##+++###+++#######++++##########++++++######++++++######++++++++++++++########++++++++########++++++++########
##++##++##+++++###+++###++++####++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
##++##++##+++++###+++###++++####++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
++##++##++#####+++###+++++++####++++++++++######++++++######++++++######++++++++########++++++++########++++++++########
++##++##++#####+++###+++++++####++++++++++######++++++######++++++######++++++++########++++++++########++++++++########
##++##++##++###+++###+++####++++####++++++######++++++######++++++##############++++++++########++++++++########++++++++
##++##++##+++++###+++#######++++####++++++######++++++######++++++##############++++++++########++++++++########++++++++
++##++##++##+++###+++#######++++####++++++######++++++######++++++##############++++++++########++++++++########++++++++
++##++##++##+++###+++#######++++####++++++######++++++######++++++##############++++++++########++++++++########++++++++
###+++###+++###+++###+++++++####++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
###+++###+++###+++###+++++++####++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
###+++###+++###+++###+++++++####++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
+++###+++###+++###+++###++++####++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
+++###+++###+++###+++#######++++##########++++++######++++++######++++++++++++++########++++++++########++++++++########
+++###+++###+++###+++#######++++##########++++++######++++++######++++++++++++++########++++++++########++++++++########
###+++###+++###+++###+++####++++####++++++######++++++######++++++######++++++++########++++++++########++++++++########
###+++###+++###+++###+++####++++####++++++######++++++######++++++######++++++++########++++++++########++++++++########
###+++###+++###+++###+++++++####++++++++++######++++++######++++++######++++++++########++++++++########++++++++########
+++###+++###+++###+++###++++####++++++++++######++++++######++++++######++++++++########++++++++########++++++++########
+++###+++###+++###+++###++++####++++++++++######++++++######++++++######++++++++########++++++++########++++++++########
+++###+++###+++###+++###++++####++++++++++######++++++######++++++######++++++++########++++++++########++++++++########
####++++####++++####++++####++++##########++++++######++++++######++++++########++++++++########++++++++########++++++++
####++++####++++####++++####++++##########++++++######++++++######++++++########++++++++########++++++++########++++++++
####++++####++++####++++####++++##########++++++######++++++######++++++########++++++++########++++++++########++++++++
####++++####++++####++++####++++##########++++++######++++++######++++++########++++++++########++++++++########++++++++
++++####++++####++++####++++####++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
++++####++++####++++####++++####++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
++++####++++####++++####++++####++++++++++######++++++######++++++##############++++++++########++++++++########++++++++
++++####++++####++++####++++####++++++++++######++++++######++++++##############++++++++########++++++++########++++++++
####++++####++++####++++####++++####++++++######++++++######++++++######++++++++########++++++++########++++++++########
####++++####++++####++++####++++####++++++######++++++######++++++######++++++++########++++++++########++++++++########
####++++####++++####++++####++++####++++++######++++++######++++++######++++++++########++++++++########++++++++########
####++++####++++####++++####++++####++++++######++++++######++++++######++++++++########++++++++########++++++++########
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
######++++++######++++++######++++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
######++++++######++++++######++++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
++++++######++++++######++++++######++++++######++++++######++++++##############++++++++########++++++++########++++++++
++++++######++++++######++++++######++++++######++++++######++++++##############++++++++########++++++++########++++++++
++++++######++++++######++++++######++++++######++++++######++++++##############++++++++########++++++++########++++++++
++++++######++++++######++++++######++++++######++++++######++++++##############++++++++########++++++++########++++++++
++++++######++++++######++++++######++++++######++++++######++++++##############++++++++########++++++++########++++++++
++++++######++++++######++++++######++++++######++++++######++++++##############++++++++########++++++++########++++++++
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
++++++######++++++######++++++######++++++######++++++######++++++######++++++++########++++++++########++++++++########
++++++######++++++######++++++######++++++######++++++######++++++######++++++++########++++++++########++++++++########
++++++######++++++######++++++######++++++######++++++######++++++##############++++++++########++++++++########++++++++
++++++######++++++######++++++######++++++######++++++######++++++##############++++++++########++++++++########++++++++
++++++######++++++######++++++######++++++######++++++######++++++##############++++++++########++++++++########++++++++
++++++######++++++######++++++######++++++######++++++######++++++##############++++++++########++++++++########++++++++
######++++++######++++++######++++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
######++++++######++++++######++++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
######++++++######++++++######++++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
######++++++######++++++######++++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
++++++######++++++######++++++######++++++######++++++######++++++######++++++++########++++++++########++++++++########
++++++######++++++######++++++######++++++######++++++######++++++######++++++++########++++++++########++++++++########
++++++######++++++######++++++######++++++######++++++######++++++######++++++++########++++++++########++++++++########
++++++######++++++######++++++######++++++######++++++######++++++######++++++++########++++++++########++++++++########
++++++######++++++######++++++######++++++######++++++######++++++######++++++++########++++++++########++++++++########
++++++######++++++######++++++######++++++######++++++######++++++######++++++++########++++++++########++++++++########
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########

```

# Answer
> 3 votes
# Jelly, ~~40~~ 31 bytes

```
1SÆD>Ðḟ½ƊṀṭƲ³¡Äż$Ḷ:Ḃ^þ`ʋ/€ḷ""/Y

```

Try it online!

A full program taking the zero-indexed \\$S-1\\$ as input and writing to stdout ASCII art using 0 = #, 1 = +.

Without the trailing `Y`, this returns a list of lists of integers, but this is out of spec for this challenge.

### Explanation

This program works in three stages.

1. Generate a list of values of \\$k\\$ and the cumulative sum of \\$k\\$
2. Generate a checkerboard for each of these with the tile size of \\$k\\$ and the board size of the cumulative sum
3. Work through the list of checkerboards, each time replacing the top-left section of the next board with the existing board.

**Stage 1**

```
1                 | Start with 1
           Ʋ³¡    | Loop through the following the number of times indicated by the first argument to the program; this generates a list of values of k
 S                | - Sum
        Ɗ         | - Following three links as a monad
  ÆD              |   - List of divisors
    >Ðḟ½          |   - Exclude those greater than the square root
         Ṁ        |   - Maximum
          ṭ       | - Concatenate this to the end of the current list of values of k
              Äż$ | Zip the cumulative sum of the values of k with the values

```

**Stage 2**

```
      ʋ/€ | For each pair of k and cumulative sum, call the following as a dyad with the cumulative sum of k as the left argument and k as the right (e.g. 15, 3)
Ḷ         | - Lowered range [0, 1 ... , 13, 14]
 :        | - Integer division by k [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
  Ḃ       | - Mod 2 [0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0]
   ^þ`    | - Outer product using xor function and same argument to both side

```

**Stage 3**

```
   /  | Reduce using the following:
ḷ""   | - Replace the top left portion of the next matrix with the current one
    Y | Finally join by newlines

```

# Answer
> 6 votes
# Canvas, ~~34~~ 32 bytes

```
０#０⁸［#+¶+#ｘｘ＊ｙｘ＋ｍ⤢αｍ；ｎｌｗ√｛ｙ；％‽²Ｘ

```

Try it here!

# Answer
> 4 votes
# Python 2, ~~217~~ ~~215~~ 212 bytes

```
def f(x):
 b=['1'];n=1
 for i in range(x):P=max(j*(n%j<(j<=n**.5))for j in range(1,1+n));n+=P;b=[l+P*`j/P%2^i%2`for j,l in enumerate(b)];s=len(b[0]);b+=[((v*P+`1^int(v)`*P)*s)[:s]for v in b[0][len(b):]]
 return b

```

Try it online!

0-indexed, uses `0` and `1` as characters

# Answer
> 3 votes
# Python 2, ~~184~~ ~~178~~ ~~176~~ 169 bytes

```
def h(j,a=['1'],R=range):
 for i in R(j):L=len(a);k=max(x for x in R(1,L+1)if(x*x<=L)>L%x);a=[a[m]+k*`(i+m/k)%2`for m in R(L)]+[((`i%2`*k+`~i%2`*k)*L)[:L+k]]*k
 return a

```

Try it online!

Uses `1`, `0` for `#`, `-`; uses `0`-indexing.

# Answer
> 2 votes
# JavaScript (ES7), 164 bytes

Input is 0-indexed. Outputs a matrix with \\$0\\$ for `#` and \\$1\\$ for `+`.

```
n=>(b=[1],g=(a,w,d=w**.5|0)=>b[n]?a:w%d?g(a,w,d-1):g(a.concat(Array(d).fill(b.push(d)&&i++)),w+d))([0],i=1).map((_,y,a)=>a.map((_,x)=>(x/b[v=a[x>y?x:y]]^y/b[v])&1))

```

Try it online!

# Answer
> 2 votes
# Charcoal, 37 bytes

```
ＦＮ«≔⊕⌈Φ₂⊕Ｌυ¬﹪Ｌυ⊕κηＦη«ＰL⭆⊞Ｏυω§#+÷⁻κμη↙

```

Try it online! Link is to verbose version of code. 1-indexed. Output grows down and left (down and right costs an extra byte, but can grow up for the same byte count). Explanation:

```
ＦＮ«

```

Loop \\$S\\$ times.

```
≔⊕⌈Φ₂⊕Ｌυ¬﹪Ｌυ⊕κη

```

Calculate \\$k\leq\sqrt{n+1}\\$. This only makes a difference when \\$n=0\\$ in which case this formula allows \\$k=1\\$.

```
Ｆη«

```

Loop \\$k\\$ times, once for each new row and column.

```
ＰL⭆⊞Ｏυω§#+÷⁻κμη

```

Output the row and column, being sure to alternate between the `#` and `+` characters in such a way that `#` is always the first character but that there is a boundary at the end of the string (because we're drawing from the diagonal outwards). `⊞Ｏυω` makes each row one character longer each time, which also keeps track of \\$n\\$ as the length.

Move down and left ready for the next row.

# Answer
> 2 votes
# 05AB1E, ~~43~~ 42 bytes

```
$G©ÐX‚ˆÑʒ®>t‹}àDU+}¯εÝ`θ÷É¨Dδ^}RζεðKζðδK€θ

```

Inspired by *@NickKennedy*'s Jelly answer, and the trailing portion `ζεðKζðδK€θ` is a port from *@Emigna*'s 05AB1E answer here.

Returns a matrix of `0` instead of `#` and `1` instead of `+`.

Try it online or try it online by outputting the first \\$\[2,n\]\\$ results (`J,` in the footer and the `--no-lazy` flag are to pretty-print the resulting matrix).

**Explanation:**

```
$                # Push 1 and the input
 G               # Loop the input - 1 amount of times:
  ©              #  Store the top of the stack in variable `r` (without popping)
   Ð             #  And triplicate the top as well
    X‚           #  Pair it with variable `X` (which is 1 by default)
      ˆ          #  And pop and store this pair in the global array
    Ñ            #  Get the divisors of the integer we triplicated
     ʒ    }à     #  Get the highest divisor which is truthy for:
         ‹       #   Where the divisor integer is smaller than
      ®>t        #   the square root of `r+1`
            DU   #  Store a copy of this largest filtered divisor as new variable `X`
              +  #  And add it to the triplicated integer
 }¯              # After the loop: push the global array
   ε             # Map each pair to:
    Ý θ          #  Convert the first value in the pair to a list in the range [0,n]
     `           #  and push both this list and the second value to the stack
       ÷         # Integer-divide each value in the list by the second value
        É        # Check for each value if it's even (1 if even; 0 if odd)
         ¨       # Remove the last item
          Dδ     # Loop double vectorized over this list:
            ^    #  And XOR the values with each other
   }R            # After the map: reverse the list of digit-matrices
     ζ           # Zip/transpose; swapping rows and columns, with a space as filler
      ε          # map each matrix to:
       ðK        #  Remove all spaces from the current matrix
         ζ       #  Zip/transpose with a space as filler again
          ðδK    #  Deep remove all spaces
             €θ  #  Then only leave the last values of each row
                 # (after which the resulting matrix of 0s and 1s is output implicitly)

```

# Answer
> 1 votes
## Haskell, ~~149~~ 146 bytes

```
(iterate g["#"]!!)
g b|let e=(<$[1..d]);l=length b;d=last[i|i<-[1..l],i*i<=l,mod l i<1];m="+#"++m=(e$take(l+d)$e=<<'#':m)++zipWith(++)(e=<<e<$>m)b

```

This is 0 indexed, returns a list of strings and grows upwards and leftwards.

Try it online!

```
(iterate g["#"]!!)                    -- start with ["#"], repeatedly add a layer
                                      -- (via function 'g'), collect all results in
                                      -- a list and index it with the input number

g b | let                             -- add a single layer to chessboard 'b'

 l=length b                           -- let 'l' be the size of 'b'
 d=last[i|i<-[1..l],i*i<=l,mod l i<1] -- let 'd' be the size of the new layer
 e=(<$[1..d])                         -- let 'e' be a functions that makes 'd'
                                      --   copies of it's argument
 m="#+"++m                            -- let 'm' be an infinite string of "+#+#+..."

 =                                    -- return
              zipWith(++)             --   concatenate pairwise
                         (e=<<e<$>m)  --   a list of squares made by expanding each
                                      --   char in 'm' to size 'd'-by-'d'
                                    b --   and 'b' (zipWith truncates the infinite
                                      --   list of squares to the length of 'b')
                                      --
           ++                         --   and prepend
                                      --
(e$take(l+d)$e=<<'#':m)               --   the top layer, i.e. a list of 'd' strings
                                      --   each with the pattern 'd' times '#'
                                      --   followed by 'd' times '+', etc., each
                                      --   shortened to the correct size of 'l'+'g'

```

# Answer
> 1 votes
# Perl 6, ~~156~~ ~~144~~ ~~155~~ 154 bytes

*+11 to fix a bug reported by nimi.*

```
{$!=-1;join "
",(1,{my \k=max grep $_%%*,1.. .sqrt;++$!;flat .kv.map(->\i,\l {l~($!+i/k)%2+|0 x k}),substr(($!%2 x k~1-$!%2 x k)x$_,0,$_+k)xx k}...*)[$_]}

```

Roughly based on Chas Brown's Python solution. Takes S zero-indexedly. Outputs `0` and `1`.

Try it online!

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