# Question
Title: The square root of the square root of the square root of the…
This challenge will give you an integer `n`, and ask you to count the number of positive integer sequences \\$S = (a\_1, a\_2, \dots, a\_t)\\$ such that

1. \\$a\_1 + a\_2 + \cdots + a\_t = n\\$, and
2. \\$\displaystyle \sqrt{a\_1+\sqrt{a\_2 + \cdots + \stackrel{\vdots}{\sqrt{a\_t}}}} \\$ is an integer.

### Example

If `n = 14`, then there are 8 such sequences:

* \\$\sqrt{2+\sqrt{2+\sqrt{2+\sqrt{2+\sqrt{2+\sqrt{3+\sqrt{1}}}}}}} = 2\\$
* \\$\sqrt{2+\sqrt{2+\sqrt{2+\sqrt{2+\sqrt{2+\sqrt{4}}}}}} = 2\\$
* \\$\sqrt{1+\sqrt{7+\sqrt{2+\sqrt{3+\sqrt{1}}}}} = 2\\$
* \\$\sqrt{2+\sqrt{1+\sqrt{7+\sqrt{3+\sqrt{1}}}}} = 2\\$
* \\$\sqrt{2+\sqrt{2+\sqrt{1+\sqrt{8+\sqrt{1}}}}} = 2\\$
* \\$\sqrt{1+\sqrt{7+\sqrt{2+\sqrt{4}}}} = 2\\$
* \\$\sqrt{2+\sqrt{1+\sqrt{7+\sqrt{4}}}} = 2\\$
* \\$\sqrt{2+\sqrt{2+\sqrt{1+\sqrt{9}}}} = 2\\$

(In this example, all of the nested square root expressions are equal to 2, but in general, this may not be the case.)

Pairs \\$(n,(a(n))\\$ for \\$n \leq 25\\$:

```
(1,1),(2,0),(3,0),(4,2),(5,0),(6,2),(7,0),(8,2),(9,2),(10,4),(11,2),(12,6),(13,2),(14,8),(15,4),(16,14),(17,6),(18,20),(19,8),(20,28),(21,14),(22,44),(23,20),(24,66),(25,30)

```

---

Your code must be robust against floating-point errors, that is it must work for arbitrarily large inputs, in principle.

Since this is a challenge, the shortest code wins.

---

(This is now on the On-Line Encyclopedia of Integer Sequences as A338271. Sequence A338268 has been added too, based on Bubbler's \\$f\\$ function.)

# Answer
> 5 votes
# 05AB1E, ~~20~~ 19 bytes

```
Åœ€œ€`ÙʒÅ«t+}н§Å²}g

```

Brute-force approach, so very slow. Times out for \\$\geq10\\$.

Try it online or verify the first 9 test cases.

**Explanation:**

```
Åœ              # Get all combinations of positive integers that sum to the (implicit)
                # input-integer
  €             # Map over each inner list:
   œ            #  And get all its permutations
    €`          # Flatten the list of lists of lists one level down
      Ù         # Uniquify the list of lists
       ʒ        # Filter it by:
        Å«      #  Cumulative left-reduce the list by:
          t     #   Taking the square of the current integer
           +    #   And adding it to the previous
         }      #  After the cumulative left-reduce, which keeps all intermediate steps:
          н     #  Pop and push its first item
           §    #  Cast this decimal to a string (bug work-around)
            Å²  #  And check that it's a perfect square
       }g       # After the filter: pop and push the length
                # (which is output implicitly as result)

```

The `§` shouldn't have been necessary, but unfortunately there is an 05AB1E bug with decimal values for the `Å²` builtin.

# Answer
> 25 votes
# APL (Dyalog Unicode), 39 bytes

```
+/⊢{∨/⍺⍵<⍵0:0⋄⍺=0:1⋄+/∊∇¨/⍺(⍵*2)-⊂⍳⍺}¨⍳

```

Try it online!

A tacit function containing an inner dfn to use recursion. Does not use floating point numbers at all.

### How it works

First of all, observe that

$$ \displaystyle \sqrt{a\_1+\sqrt{a\_2 + \cdots + \stackrel{\vdots}{\sqrt{a\_t}}}} \le \cdots \le \sqrt{a\_1+a\_2 + \cdots + a\_t} \le a\_1+a\_2 + \cdots + a\_t = n $$

and this holds for all suffixes of any given sequence of positive integers.

Let's define a function \\$f(x,y)\\$ as the number of sequences where the sum is \\$x\\$ and the "root sum" is \\$y\\$. Then the following holds:

$$ \begin{align} f(0, 0) &= 1 \\ f(0, y) &= 0, \qquad 0 \< y \\ f(x, y) &= 0, \qquad x \< y \text{ or } y \< 0 \\ f(x, y) &= \sum\_{i=1}^{x}{f(x-i, y^2-i)} \end{align} $$

Then the desired result is the sum \\$\sum\_{i=1}^{n}{f(n,i)}\\$.

# Answer
> 12 votes
# Python 3, 67 bytes

This builds all sequences that sum to \\$n\\$ and slightly higher and counts those that exactly sum to \\$n\\$.

```
f=lambda n,k=0:(n==0)+sum(f(n-d*d+k,d)for d in range(n-~k)if d*d>k)

```

Try it online!

This approach is based on the observation that \\$\sqrt x\\$ can only be an integer if \\$x\\$ is an integer. This means, when building a sequence right to left, we always have to make sure to complete to a perfect square.

At every step \\$\sqrt{a\_i+k}\\$, \\$a\_i+k = d^2\\$ for some positive \\$d\\$ with \\$0 \lt d^2-k \le n'\\$, where \\$n'\\$ is the remaining integer at the current step. To check every possible square, \\$d\\$ needs to be tested up to \\$\lfloor\sqrt{n'+k}\rfloor\ \le n+k\\$.

In the code we count the number of times \\$n'=0\\$ is exactly reached, by summing all results and adding `n==0`. If `n` gets negative, `range(n-~k)` will eventually be empty, which will cause the recursion to stop.

This seems to be currently the fastest approach, and with some added *memoization* this gets really fast: First 1000 values

With a small modification the sequences can be printed:

```
f=lambda n,k=0,*a:(n==0!=print(a))+sum(f(n-d*d+k,d,d*d-k,*a)for d in range(n-~k)if d*d>k)

```

Try it online!

# Answer
> 6 votes
# Wolfram Language (Mathematica), ~~56~~ 50 bytes

```
If[a=##-i i;0<a<#,a~#0~i,1-Sign@a]~Sum~{i,√+##}&

```

Try it online!

# Answer
> 6 votes
# CP-1610 machine code, 31 DECLEs1 ≈ 39 bytes2

*1. A CP-1610 opcode is encoded with a 10-bit value (0x000 to 0x3FF), known as a 'DECLE'.*
*2. As per the exception described in this meta answer, the exact score is **38.75 bytes** (310 bits)*

---

This is an implementation with only integer additions, subtractions and comparisons.

A routine taking the input in **R1** and returning the result in **R3**.

```
**1DB**  |         CLRR    R3
**1C0**  |         CLRR    R0
**275**  | @@rec   PSHR    R5
**089**  |         TSTR    R1
**20C 001**  |         BNEQ    @@notZ
**00B**  |         INCR    R3
**272**  | @@notZ  PSHR    R2
**1D2**  |         CLRR    R2
**110**  | @@loop  SUBR    R2,     R0
**012**  |         DECR    R2
**110**  |         SUBR    R2,     R0
**148**  |         CMPR    R1,     R0
**20E 00E**  |         BGT     @@done
**080**  |         TSTR    R0
**226 008**  |         BLE     @@loop
**270**  |         PSHR    R0
**271**  |         PSHR    R1
**101**  |         SUBR    R0,     R1
**090**  |         MOVR    R2,     R0
**004 148 040** |         CALL    @@rec
**2B1**  |         PULR    R1
**2B0**  |         PULR    R0
**220 013**  |         B       @@loop
**2B2**  | @@done  PULR    R2
**2B7**  |         PULR    R7

```

### Full commented test code

```
        ROMW    10                ; use 10-bit ROM width
        ORG     $4800             ; map this program at $4800

PNUM    QEQU    $18C5             ; EXEC routine: print a number

        ;; ------------------------------------------------------------- ;;
        ;;  main code                                                    ;;
        ;; ------------------------------------------------------------- ;;
main    PROC

        SDBD                      ; set up an interrupt service routine
        MVII    #isr,   R0        ; to do some minimal STIC initialization
        MVO     R0,     $100
        SWAP    R0
        MVO     R0,     $101

        EIS                       ; enable interrupts

        MVII    #$200,  R3        ; R3 = backtab pointer
        CLRR    R1                ; R1 = number to test

@@loop  INCR    R1                ; increment R1
        PSHR    R1                ; save R1 & R3 on the stack
        PSHR    R3
        CALL    func              ; invoke our routine
        MOVR    R3,     R1        ; save the result in R1
        PULR    R3                ; restore R3
        CALL    print             ; print R1

        PULR    R1                ; restore R1
        CMPI    #28,    R1        ; go on as long as R1 is less than 28
        BLT     @@loop

        DECR    R7                ; done: loop forever

        ENDP

        ;; ------------------------------------------------------------- ;;
        ;;  prints the result of a test case                             ;;
        ;; ------------------------------------------------------------- ;;
print   PROC

        PSHR    R5                ; save the return address on the stack

        MOVR    R1,     R0        ; R0 = number to print
        MVII    #4,     R1        ; R1 = number of digits
        MOVR    R3,     R4        ; R4 = backtab pointer
        ADDI    #5,     R3        ; advance by 5 characters for the next one
        PSHR    R3                ; save R3
        CLRR    R3                ; R3 = attributes (black)
        CALL    PNUM              ; invoke the EXEC routine
        PULR    R3                ; restore R3

        PULR    R7                ; return

        ENDP

        ;; ------------------------------------------------------------- ;;
        ;;  ISR                                                          ;;
        ;; ------------------------------------------------------------- ;;
isr     PROC

        MVO     R0,     $0020     ; enable display
        MVI     $0021,  R0        ; colorstack mode

        CLRR    R0
        MVO     R0,     $0030     ; no horizontal delay
        MVO     R0,     $0031     ; no vertical delay
        MVO     R0,     $0032     ; no border extension
        MVII    #$D,    R0
        MVO     R0,     $0028     ; light-blue background
        MVO     R0,     $002C     ; light-blue border

        JR      R5                ; return from ISR

        ENDP

        ;; ------------------------------------------------------------- ;;
        ;;  our routine                                                  ;;
        ;; ------------------------------------------------------------- ;;
func    PROC

        CLRR    R3                ; R3 = counter for the final result
        CLRR    R0                ; start with R0 = 0

@@rec   PSHR    R5                ; this is the recursive entry point

        TSTR    R1                ; if R1 is equal to 0 ...
        BNEQ    @@notZ

        INCR    R3                ; ... increment R3

@@notZ  PSHR    R2                ; save R2 on the stack
        CLRR    R2                ; start with R2 = 0

@@loop  SUBR    R2,     R0        ; subtract R2 from R0
        DECR    R2                ; decrement R2
        SUBR    R2,     R0        ; subtract R2 from R0
        CMPR    R1,     R0        ; abort if R0 is greater than R1
        BGT     @@done

        TSTR    R0                ; skip the recursive call if R0 <= 0
        BLE     @@loop

        PSHR    R0                ; save R0 and R1 on the stack
        PSHR    R1
        SUBR    R0,     R1        ; subtract R0 from R1
        MOVR    R2,     R0        ; move R2 to R0
        CALL    @@rec             ; recursive call
        PULR    R1                ; restore R0 and R1
        PULR    R0
        B       @@loop            ; keep going

@@done  PULR    R2                ; this is either the end of a recursive
        PULR    R7                ; call or the end of the routine

        ENDP

```

### Output

Below are **a(1)** to **a(28)**.

*screenshot from jzIntv*

# Answer
> 5 votes
# Retina, 65 bytes

```
.+
*_;
+%L$w`^((^_|\2__)*)(;|(?=(_+);(?!\1)))
$#4*$#2*_$4;$#2*_
;

```

Try it online! Link includes test suite that tests all `n` up to and including the input. Explanation:

```
.+
*_;

```

Convert the input to unary and append a working area for the previous square root.

```
+`

```

Repeat until no new solutions can be found.

```
%`

```

Check all lines separately for new solutions.

```
L$w`^((^_|\2__)*)(;|(?=(_+);(?!\1)))

```

Match all square prefixes of the current value. This (`$.1`) represents the amount being square rooted on this pass. `$#2` is its square root. `$.4` is the residue after subtracting the terms so far; `$#4` is a flag for whether the residue is non-zero, in which case the square must be greater than the previous square root. This check is not performed if the residue is zero, as the previous residue must have been non-zero anyway, thus allowing completed sequences to remain undisturbed.

```
$#4*$#2*_$4;$#2*_

```

For each square prefix, add its square root to the residue, and record the new value along with the square root. However, if the current value turned out to be square, then the square root is skipped and all that remains is the `;`. This indicates a completed sequence.

```
;

```

Count the number of complete sequences found.

# Answer
> 4 votes
# APL (Dyalog Unicode), ~~35~~ 34 bytes

Thanks to Bubbler for -1 byte!

Another port of my Python answer.

```
0∘{⍵≤⍺:⍵=⍺⋄(⊢+.∇⊢+⍵-×⍨)(⌊⍺*÷2)↓⍳⍵}

```

Try it online!

The main function is the *dfn* `{ ... }` which takes \\$k\\$ as the left argument and \\$n+k\\$ as the right argument. `0∘` supplies the initial \\$k=0\\$.

`⍵≤⍺:⍵=⍺` is the stopping condition, if \\$n+k \le k \Leftrightarrow n \le 0\\$, this returns a value of \\$1\\$ if \\$n=0\\$ and \\$0\\$ otherwise.

`⍳⍵` is the inclusive range from \\$1\\$ to \\$n+k\\$.
`⌊⍺*÷2` is the floor of the aqure root of \\$k\\$.
drops this many items from the range. This results in a new range from \\$\left\lceil\sqrt{k}\right\rceil\\$ to \\$n+k\\$. These are the values for \\$d\\$ that satisfy \\$d^2\>k\\$.

`⊢∇¨⊢+⍵-×⍨` is a train applied to this range.
`×⍨` squares every value. =\> \\$d^2\\$
`⍵-` subtracts each square from \\$n+k\\$. =\> \\$n+k-d^2\\$
`⊢+` adds the range again. This is needed beacuse we actually call the function with \\$n+k\\$ and not just \\$n\\$. =\> \\$n+k-d^2 + d\\$
is the right argument, in this this case the potential \\$d\\$'s.
`+.∇` is the inner product of the functions `+` and . First  (recurse) is called on every pair of \\$d\\$ and \\$n+k-d^2 + d\\$, then the resulting vector is reduced by addition (`+`).

# Answer
> 3 votes
# Haskell, 53 bytes

A port of my Python answer.

```
(#0)
n#k|n==0=1|w<-n+k=sum[(w-d*d)#d|d<-[1..w],d*d>k]

```

Try it online!

# Answer
> 2 votes
# Perl 5 (`-MList::Utils+sum`), 64 bytes

```
sub f{my($n,$k)=@_;sum!$n,map f($n+$k-$_*$_,$_),$k**.5+1..$n+$k}

```

Try it online!

Using @ovs formula

# Answer
> 1 votes
# Jelly (fork), 15 bytes

```
ŒṗŒ!€ẎQ½+¥/€Æ²S

```

Try it online!

This will work for some inputs on TIO, but will fail for others due to floating point errors. However, my fork has symbolic math support, meaning that it basically never uses floats.

## How it works

This is a brute force attempt. Times out on TIO for \\$n \ge 10\\$. Uses a similar approach to Kevin's answer, but found independently.

```
ŒṗŒ!€ẎQ½+¥/€Æ²S - Main link. Takes n on the left
Œṗ              - Integer partitions of n
    €           - Over each:
  Œ!            -   Calculate the permutations
     Ẏ          - Merge into a list of lists
      Q         - Deduplicate
           €    - Over each list:
         ¥/     -   Reduce by:
       ½        -     Square root of left
        +       -     Plus right
            Æ²  - Is a square?
              S - Sum

```

---
Tags: code-golf, math, sequence, combinatorics
---


# Question
Title: Thorough though Thoreau threw, Troll throws through tough troughs
To each of these nine confusingly similar words, assign a number 1-9 in any way you like:

```
though
through
thorough
Thoreau
throw
threw
trough
tough
troll

```

Write a program that takes in a string. If the input is one of these nine words, output the number you assigned to it. If the input is not one of the words above, the program may do anything (including error or loop forever).

The words are case sensitive, e.g. `Thoreau`, should produce a number from 1-9 but `thoreau` will not necessarily do the same.

## Example

Suppose you assign the numbers as follows:

```
though   9
through  2
thorough 7
Thoreau  6
throw    3
threw    5
trough   4
tough    1
troll    8

```

Then when `tough` is input, `1` should be output.
When `through` is input, `2` should be output.
When `throw` is input, `3` should be output.
. . .
When `though` is input, `9` should be output.

All other inputs may do anything.

## Details

* Take the input string via stdin or the command line and output to stdout.
* The output may contain a single trailing newline.
* Instead of a program, you may write a function that takes in a string and prints the result normally or returns it.
* **The shortest submission in bytes wins**

# Answer
# CJam, ~~11 9~~ 7 bytes

```
q1b2+B%

```

**How it works**:

We are making use of the fact that the sum of the ASCII codes + 2 moded with 11 gives very nice order of 1 through 9 and then 10 for the nine concerned words. Here is the ordering:

```
through -> 1
thorough -> 2
tough -> 3
Thoreau -> 4
throw -> 5
threw -> 6
trough -> 7
though -> 8
troll -> 9

```

**Code explanation**:

```
q               e# Read the input
 1b             e# Sum the ASCII code values of all characters in this word
   2+           e# Increment the sum by 2
     B%         e# Mod by 11 and automatically print the mod result at the end

```

*4 bytes saved thanks to user23013*

Try it online here
> 19 votes

# Answer
# Pyth, 8 chars

```
e%Cz8109

```

Try it online: Demonstration or Test Suite

I'm using the assignment:

```
though   5
through  9
thorough 4
Thoreau  7
throw    3
threw    2
trough   8
tough    6
troll    1

```

### Explanation:

```
   z       input()
  C        convert to int (convert each char to their ASCII value
           and interprete the result as number in base 256)
 %  8109   modulo 8109
e          modulo 10

```

Btw, I found the magic number 8109 by using this script: `fqr1 10Sme%CdT.z1`.
> 18 votes

# Answer
# Python 2, ~~92~~ 54 bytes

```
print'K{7j)yE<}'.find(chr(hash(raw_input())%95+32))+1

```

The index string is created with `for word in words: print chr(hash(word)%95+32),`. As pointed out in Jakube's answer, the hash function will give different results depending on Python version. This index string is computed on 64 bit Python 2.7.6.

Longer (92 bytes) but less cryptic answer:

```
print'though through thorough Thoreau throw threw trough tough troll'.find(raw_input())/7+1

```

The programs returns 1-9 for *though through thorough Thoreau throw threw trough tough troll* in that order. When the input is not found, find will return a -1 which conveniently turns into a zero after the `+1`.
> 11 votes

# Answer
# Python 2.7.9 32 bit version, 22 bytes

```
lambda x:hash(x)%78%10

```

Notice, the version is really important here. You will get different results if your using a 64 bit version of Python. Since the `hash` method will compute 64 bit hash values instead of 32 bit.

The assignment is:

```
though  => 5   through => 6   thorough => 8
Thoreau => 7   throw   => 3   threw    => 1
trough  => 9   tough   => 4   troll    => 2

```

Try it online: http://ideone.com/Rqp9J8
> 7 votes

# Answer
# Pyth, 7 bytes

```
et%Cz31

```

I am using the following asignment:

```
though   8
through  3
thorough 1
Thoreau  5
throw    4
threw    7
trough   6
tough    2
troll    9

```

`Cz` interprets the input as a base 256 number. Then, we take this mod 31, subtract 1, and take the result mod 10. Equivalent pseudocode:

```
((base_256(input()) % 31) - 1) % 10

```

Demonstration, test harness.
> 5 votes

# Answer
# Japt, 6 bytes

```
nH %BÉ

```

Try it | Test all words

---

## Explanation

Takes advantage of the fact that, when parsing a base-`n` string to an integer, JavaScript will stop parsing if it encounters a digit greater than `n` and return the result up to that point. By using base-32 here (digits `0-v`) the `w`s in "threw" and "throw" are, essentially, ignored.

```
nH      :Convert from base-32
   %B   :Modulo 11
     É  :Subtract 1

```

Here's a breakdown of the formula applied to each word:

| Input | `nH` | `%B` | `É` |
| --- | --- | --- | --- |
| through | 31738067473 | 2 | 1 |
| tough | 31226385 | 3 | 2 |
| troll | 31318709 | 4 | 3 |
| trough | 1002207761 | 5 | 4 |
| though | 991722001 | 6 | 5 |
| thro*w* | 968568 | 7 | 6 |
| thre*w* | 968558 | 8 | 7 |
| thorough | 1015520459281 | 9 | 8 |
| Thoreau | 31735003486 | 10 | 9 |

---

## JavaScript, 22 bytes

A direct translation - doesn't seem worth posting it separately.

```
f=
U=>parseInt(U,32)%11-1
o.innerText=["through","tough","troll","trough","though","throw","threw","thorough","Thoreau"].map(s=>f(s)+": "+s).join`\n`
```

```
<pre id=o><pre>
```
> 2 votes

# Answer
# Vyxal, 6 bytes

```
C∑⇧11%

```

Try it Online!

Cjam port.
> 2 votes

# Answer
# Python 2, 27 bytes

```
f=lambda w:int(w,34)%444/46

```

With this assignment:

```
>>> for w in "though through thorough Thoreau throw threw trough tough troll".split(): print f(w),w
...
9 though
7 through
3 thorough
8 Thoreau
2 throw
5 threw
6 trough
1 tough
4 troll

```

Several variations are possible, e.g.

```
f=lambda w:int(w,35)/159%10

```
> 1 votes

# Answer
# C (gcc), 66 bytes

```
h,k;f(char*s){for(h=33;*s;)h^=*s++;h=strchr(k="(Z5qW]2@H",h)-k+1;}

```

Try it online!
> 0 votes

# Answer
# Java 8, ~~53~~ 25 bytes

```
s->(s.chars().sum()+2)%11

```

or

```
s->-~-~s.chars().sum()%11

```

Port of *@Optimizer*'s CJam answer, because it (most likely) cannot be done any shorter in Java..

Try it online.
> 0 votes

# Answer
# Jelly, 7 bytes

```
OS+2%11

```

Try it online!

Boring Jelly port of the fantastic CJam answer.
> 0 votes

---
Tags: code-golf, kolmogorov-complexity
---


title: What is the link to your answer?

text:
# Question
Title: What is the link to your answer?
## Goal

Your task is to create a program taking no input that returns the link to your answer. You can find a link to your answer by clicking at the share button on your answer.

## Rules

1. Standard loopholes apply except for searching for the answer online. In fact, you are expected to find the answer online.
2. You are allowed to use curl or the equivalent, but you are not allowed to use any html parser library or built-in. If you need to import the library, the import declaration does **NOT** count into the code size as long as you don't rename any identifiers.
3. **You are not allowed to assume, or hardcode, the link to your answer**. You have to search this page for your submission. If you remove your submission and re-add it, and your code breaks, you fail the challenge.
4. You may still assume your username, the contents of your code, and the programming language/byte count you are using. You are not allowed to assume the description below your code. If you edit the description part of the submission and the code breaks, you fail the challenge. You may assume that the code of each submission is unique and no one copies your submission into another answer.
5. Your answer has to be exactly the same as what you get when you clicked on the share button.
6. You may post the dummy answer for the prototyping purpose. Just delete it immediately after posting, and edit your answer into it once completed.
7. You are not allowed to take an user input

## Scoring

This is so, the shortest answer in bytes wins.

# Answer
# Jelly, ~~61~~ 57 bytes

```
“¦ɦḍɓḃɠṭṢ⁽&½ṛøHØÐ»Ȯ;⁾q/;“£ɓ⁶’ŒGœṣ“"/a/”iƇ”ɦṪṣ”=-3ịḊḣ6⁾a/;

```

Try it online!

What's a worse idea than parsing HTML with regex? Parsing HTML with *Jelly*

This outputs `codegolf.stackexchange.com/a/226641`. This will fail if this is "reposted" after ~780000 more posts are posted to the site, but that is currently 3.5 times the number of posts we currently have. A more future-proof version comes out as the same length

## How it works

This works in two parts. First we build and print the string to fetch the HTML of the question (including the answers), then we process and extract my answer id

```
“¦ɦḍɓḃɠṭṢ⁽&½ṛøHØÐ»Ȯ;⁾q/;“£ɓ⁶’ŒG - Main link
“¦ɦḍɓḃɠṭṢ⁽&½ṛøHØÐ»              - Compressed string "codegolf.stackexchange.com/"
                  Ȯ             - Print this
                   ;⁾q/         - Concatenate "q/"
                        “£ɓ⁶’   - Compressed integer: 226635
                       ;        - Concatenate; "codegolf.stackexchange.com/q/226635"
                             ŒG - GET request, prepending "http://"

```

Building the string this way takes 2 more bytes than simply compressing `codegolf.stackexchange.com/q/226635`: `“ñoHƑ;ɦŻt%WɓḤȦ3æḶ2ỤƭȮ¦1ẈA»`. However, by having `“¦ɦḍɓḃɠṭṢ⁽&½ṛøHØÐ»` (`"codegolf.stackexchange.com/"`) by itself at the start, we can print it using `Ȯ`, allowing us to just output `a/226641` later on

```
œṣ“"/a/”iƇ”ɦṪṣ”=-3ịḊḣ6⁾a/; - Main link.
                             To our left, we have the HTML content of this page
  “"/a/”                   - Yield '"/a/'
œṣ                         - Split at '"/a/', splitting roughly into answers
        iƇ”ɦ               - Keep those with the "ɦ" character in them. Currently, that's just me
            Ṫ              - Extract this bit of HTML
             ṣ”=           - Split at equals signs
                -3ị        - Take the 4th from last, which is '"226641">    <div class'
                   Ḋ       - Remove the quote
                    ḣ6     - Extract the first 6 characters
                   fØD     - Future proof version: keep only digits
                      ⁾a/; - Prepend "a/" and output

```
> 15 votes

# Answer
# JavaScript (Browser Console), 155 bytes

```
alert(`${c='https://codegolf.stackexchange.com/'}a/${(await(await fetch(c+`search?q=user:${u=44718}+inquestion:226635`)).text()).match(/(?<=s#)\d+/)}/${u}`)

```

I'm using Firefox 88. The code need to be executed under same domain due to permission restriction of fetch.

Btw, top level await is allowed in most browsers' console.
> 6 votes

# Answer
# Red, 151 byte

```
r: :rejoin n:"104280"u: https://codegolf.stackexchange.com/ r[u"a/"parse read r[u"questions/226635"][collect[thru[{"}ahead[22 skip n]]keep to{"}]]"/"n]

```

No TIO link, since it uses an outdated toolchain and errors out during lexing. Try it locally instead, using the latest automated build.

---

Red's implementation of GZIP and DEFLATE decompression is completely broken, so, instead of working with StackExchange API, I had to fall back on HTML parsing... which is a nice showcase in its own regard, since the solution relies on the embedded PEG parsing DSL.
> 5 votes

# Answer
# PHP 5, 211 bytes

```
foreach(json_decode(gzdecode(join(file('http://api'.($s='.stackexchange.com/').'2.2/questions/226635/answers?site=codegolf'))))->items as$i)if($i->owner->user_id==90841)echo"https://codegolf{$s}a/$i->answer_id";

```

(Cannot) Try it online!

Unfortunately, `file` and `gzdecode` functions re disabled in PHP online testers, but it works so far on my localhost

**EDIT:** first version didn't work (because of the content of my own answer, lol) and was easy to break with a single comment, switched to a supposedly foolproof version with the API, much longer though

**EDIT 2:** saved 5 bytes with strings optimizations

**EDIT 3:** another byte saved (the dust) by using `http` instead of `https` for the API
> 4 votes

# Answer
# Go, 342 bytes

```
package main
import(."encoding/json"
."net/http")
func main(){t,u:="codegolf",".stackexchange.com/"
r,_:=Get("https://api"+u+"2.2/questions/226635/answers?site="+t)
var s struct{Items[]struct{Answer_ID int
Owner struct{User_ID int}}}
NewDecoder(r.Body).Decode(&s)
for _,i:=range s.Items{if i.Owner.User_ID==7815{print(t,u,"a/",i.Answer_ID)}}}

```
> 3 votes

# Answer
# Bash \+ Wget \+ Sed, 114 bytes (104 bytes + 5 byte user ID twice)

```
U=https://codegolf.stackexchange.com
wget $U/q/226635 -O-|sed -nE '/44694/s?.*answer-([0-9]+).*?'$U'/a/\1/44694?p'

```

Prints `https://codegolf.stackexchange.com/a/226723/44694` on stdout.

Note that `wget` prints logs to stderr, which should be ignored.

(No TIO link because wget doesn't work on TIO; I assume TIO blocks internet access.)

Explanation:

* Save the string `https://codegolf.stackexchange.com` in `$U`
* `wget` the webpage for this question, piping it to `sed`
* Using `sed`:
    + Search for all lines containing my user ID.
    + (Specifically we are looking for the line containing `<div
    id="answer-**XXXX**" class="answer" data-answerid="XXXX"
    data-ownerid="**YYYY**" ...`, where `**YYYY**` is my user ID, and `**XXXX**` is the answer ID we are looking for.)
    + If the line contains `answer-**XXXX**`, then
        - The `**XXXX**` is the answer ID; capture it in a subexpression.
        - Print the string saved in `$U` followed by `/a/`, followed by the answer ID using `\1` subexpression replacement, followed by a slash and my user ID.

---

# Bash \+ Wget \+ Sed, 100 bytes (95 bytes + 5 byte user ID)

If the output format is not as strict, then I have a 100 byte version that prints the URL without the `https://` or the trailing user ID.

Prints `codegolf.stackexchange.com/a/226723` on stdout.

```
U=codegolf.stackexchange.com
wget $U/q/226635 -O-|sed -nE '/44694/s?.*answer-([0-9]+).*?'$U'/a/\1?p'

```
* -8 bytes: no `https://`
* -(1+5) bytes: no trailing `/` and user ID
> 2 votes

# Answer
## JavaScript (ES6), 216 bytes

```
fetch("https://api.stackexchange.com/2.2/questions/226635/answers?site=codegolf").then(r=>r.json()).then(j=>"https://codegolf.stackexchange.com/a/"+j.items.find(a=>a.owner.user_id==17602).answer_id).then(console.log)
```
> 1 votes

# Answer
# 05AB1E, 60 bytes

```
’ƒËŠˆ.Â‚‹º.ŒŒ’žYì©…/q/•3{Ä•J.w“"/a/“¡ʒ'ʒå}`'=¡4(èþ'a®rŽÍ¿'/ý

```

Port of *@cairdCoinheringaahing*'s Jelly answer, so make sure to upvote him.
Assumes this is the only answer that contains a `ʒ`. If another answer should pop up with this character, it could be switched to another unique character from my program that probably isn't used in a lot of languages instead, like `þ` or `®`.

No TIO of the entire program, since `.w` is disabled.

**Explanation:**

Generate the question URL, and get its HTML content:

```
’ƒËŠˆ.Â‚‹º.ŒŒ’     # Push dictionary string "codegolf.stackexchange.com"
  žYì              # Prepend "https://"
     ©             # Store this string in variable `®` (without popping)
      …/q/         # Push string "/q/"
          •3{Ä•    # Push compressed integer 226635
               J   # Join the entire stack together
                .w # Browse to this URL and get its HTML content as string

```

Try it online (without `.w`).

And then get the answer-ID and generate the resulting URL:

```
“"/a/“¡           "# Split the HTML content on '"/a/'
       ʒ           # Filter these parts by:
        'ʒå       '#  Check if it contains character "ʒ"
       }`          # After the filter: pop and push this only part to the stack
         '=¡      '# Split it on "="
            4(è    # Index to get the 0-based -4'th item (fourth item from the back)
               þ   # Only leave its digits
'a                '# Push string "a"
  ®                # Push the string from variable `®`
   r               # Reverse the three values on the stack
    ŽÍ¿            # Push compressed integer 52210
       '/ý        '# Join the stack with "/" delimiter
                   # (after which the result is output implicitly)

```

The URL generated by TIO would be too big for a stackexchange answer and most URL-shorteners unfortunately, so here the TIO where you'll have to insert the question's HTML content yourself (Ctrl+U in your browser, select everything, and past it between the `"""` in the input-block of the TIO):
'Try it online.'

See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress large integers?*) to understand how `’ƒËŠˆ.Â‚‹º.ŒŒ’` is `"codegolf.stackexchange.com"`; `•3{Ä•` is `226635`; and `ŽÍ¿` is `52210`.
> 1 votes

---
Tags: code-golf, parsing, internet, self-referential
---


title: Ascii smiley face challenge

text:
# Question
Title: Ascii smiley face challenge
I made this because, although we have a bunch of other questions involving smiley faces, there is nothing for just printing an ASCII smiley face with as little code as possible.

Anyway, print this exactly (Trailing spaces allowed):

```
        **********
    ******************
  **********************
 *******  ******  *******
 ************************
**************************
**************************
*****   **********   *****
 *****   ********   *****
 ******            ******
  **********************
    ******************
        **********

```

This is code-golf, so fewest bytes wins. Yes, you have to use asterisks.

# Answer
> 7 votes
# Python 3, ~~97~~ 93 bytes

Thanks to Mukundan314 for -4 bytes!

The string has a leading and trailing unprintable with value `19`.

```
for c in"%.»677íìư.%":c=ord(c);s=c//8%8*'*'+c//64*' '+c%8*'*';print(f'{s+s[::-1]:^26}')

```

Try it online!

# Answer
> 6 votes
# APL+WIN, 57 bytes

```
m,⌽m←13 13⍴(¯17+⎕av⍳'hedibkagbca⊢ceaecdafhkdihe')/26⍴' *'

```

String used to index into atomic vector has been adjusted to allow for differences between APL+WIN and Dyalog

Try it online! Thanks to Dyalog Classic

# Answer
> 4 votes
# Java (JDK), 153 bytes

```
v->{var s=0;for(var c:"HJ!DR!BV!AGBFBG!AX!@Z!@Z!@ECJCE!AECICE!AFLF!BV!DR!HJ".getBytes())System.out.print("\n* ".split("")[c/64+(s^=c/64)].repeat(c%32));}

```

Try it online!

## Explanation

The idea is to have toggle, `s`, which will tell us when to print spaces or stars. The number of those spaces or spaces is defined by each character used in the long string. Any letter is their corresponding number (`A=1, B=2, ...`), `@` actually is zero, and `!` also means 1, but it's in a lower range than `A` to know when to go to the next line.

We can see the smiley as a sequence of \[0,26\] spaces followed by stars \[1,26\], possibly repeated. This makes sure that if we provide 2 chars, the first char represent the spaces and the second char represent the stars. This toggling is done using `s^=1`.

But it happens that I have to insert new lines in that sequence. A new character would then mess up with that `s^=1`, so I changed that to `s^=c/64`, meaning that only letters and `@` actually trigger the toggle, while `!` result in `s^=0` which is a no-op.

| `s` | `c` | `s^(c/64)` | `c/64+(s^(c/64))` | Result |
| --- | --- | --- | --- | --- |
| `0` | `!` | `0` | `0` | `\n` |
| `0` | `[@-Z]` | `1` | `2` | (space) |
| `1` | `!` | `1` | `1` | Never occurs |
| `1` | `[@-Z]` | `0` | `1` | `*` |

After the character is selected (but kept as a string, not as a character), it is repeated `c%32` times. It is to note that `'!' % 32 = 33 % 32 = 1` and `'@' % 32 = 64 % 32 = 0`. Java's `.repeat(0)` will indeed result in the empty string (`""`).

# Answer
> 4 votes
# TI-BASIC, 172 bytes (on-calc) / 205 bytes (as text)

Conveniently, the image is exactly as wide as the screen on the TI-84 Plus CE. This should work with an 83/84(+) too, but it won't display properly due to the smaller screens.

```
{7,10,12,18,6,22,3,7,2,6,2,7,2,24,1,57,3,10,3,5,1,5,3,8,3,5,2,6,12,6,3,22,6,18,12,10,8→D
"
For(I,1,37
For(J,1,⌊D(I
Ans+sub("* ",remainder(I,2)+1,1
End
End
For(I,1,338,26
Disp sub(Ans,I,26
End

```

## Explanation

* `{7,10,12,18,6,22,3,7,2,6,2,7,2,24,1,57,3,10,3,5,1,5,3,8,3,5,2,6,12,6,3,22,6,18,12,10,8→D`: Stores a list of the number of spaces and asterisks, alternating, like the lines of the image are unwrapped in 1-D space one after the other. The first value is an exception; it should theoretically be 8, but since TI-BASIC doesn't like empty strings, the output string is created with a single space already in it.
* `"` : Create a string in the `Ans` "variable" with a single space in it.
* `For(I,1,37`: For (the index of) each value in `⌊D`...
    + `For(J,1,⌊D(I`
        - `Ans+sub("* ",remainder(I,2)+1,1`: ...concatenate that number of either asterisks or spaces to the string, depending on whether `I`, the index of the list, is odd or even.
    + `End`
* `End`
* `For(I,1,338,26`: For I from 1 to 338 (length of the resulting string) with a step of 26 (length of each row of the image)...
    + `Disp sub(Ans,I,26`: ...display a substring starting at I (the start of the I-th row of the image) which is 26 characters long.
* `End`

# Answer
> 3 votes
# JavaScript (ES6), 108 bytes

```
_=>`8a
4i
2m
172627
1o
0q
0q
053a35
153835
16c6
2m
4i
8a`.replace(/./g,c=>"* "[_^=1].repeat(parseInt(c,36)))

```

Try it online!

---

# JavaScript (ES6),  ~~112~~  109 bytes

Returns an array of strings.

```
_=>[p=1020,960,768,515,512,0,0,28,526,519.9,768,960,p].map(n=>(g=(k,c="* "[n*8>>k&1])=>~k?c+g(k-1)+c:'')(12))

```

Try it online!

### How?

Each value in the array represents the inverted 13-bit value of the left side of the smiley, divided by 8. Dividing by 8 saves 7 bytes overall, although there's a non-integer value in there (`519.875`, which can be rounded to `519.9`).

```
........***** -> 1111111100000 -> 8160 / 8 = 1020
....********* -> 1111000000000 -> 7680 / 8 = 960
..*********** -> 1100000000000 -> 6144 / 8 = 768
.*******..*** -> 1000000011000 -> 4120 / 8 = 515
.************ -> 1000000000000 -> 4096 / 8 = 512
************* -> 0000000000000 ->    0 / 8 = 0
************* -> 0000000000000 ->    0 / 8 = 0
*****...***** -> 0000011100000 ->  224 / 8 = 28
.*****...**** -> 1000001110000 -> 4208 / 8 = 526
.******...... -> 1000000111111 -> 4159 / 8 = 519.875
..*********** -> 1100000000000 -> 6144 / 8 = 768
....********* -> 1111000000000 -> 7680 / 8 = 960
........***** -> 1111111100000 -> 8160 / 8 = 1020

```

So, we extract the **k**th 'pixel' stored in the bitmask **n** with:

```
n * 8 >> k & 1

```

# Answer
> 3 votes
# 05AB1E, ~~72~~ ~~68~~ 42 bytes

```
•A9lΘRfÓβèε¢|Ïí"·тjêøèÂ§Äα9₃ê˜ì•… *
ÅвJº.c

```

-26 bytes by adding a mirror (inspired by *@Neil*'s Charcoal answer).

Try it online.

**Explanation:**

```
•A9lΘRfÓβèε¢|Ïí"·тjêøèÂ§Äα9₃ê˜ì•
              "# Push compressed integer 61833926632893543016875916488121666051545681457434856388592933517828315
  … *\n        # Push string " *\n"
       Åв      # Convert the integer to base-" *\n" (which means to convert it to base-3,
               # and index them into the 3-char string)
         J     # Join all characters together to a string
          º    # Mirror each line
           .c  # And centralize all lines
               # (after which the result is output implicitly)

```

This is the result without the mirror and centralize. The code for this is generated with this 05AB1E ASCII-art tip.
See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•A9lΘRfÓβèε¢|Ïí"·тjêøèÂ§Äα9₃ê˜ì•` is `61833926632893543016875916488121666051545681457434856388592933517828315`.

# Answer
> 3 votes
# PHP, (all versions) ~~119~~ ~~106~~ ~~104~~ 71 bytes

`<?=gzinflate("SP€ -8àåBå#‹cŠBe ,˜ ¸J„]¸dˆ’Cq#Œ³I]JK À‰Ûg8Ã=Ü");`

**WARNING**: this code contains many non-printable chars and a function that is disabled in most online code testers. It is either impossible to enter the correct code on the page or run the function. Here is the php file I uploaded to gitHub so that you can test:

Try it OFFline!

For info, it was generated by PHP's `file_put_contents` with the direct result of `gzdeflate`, no other manipulation required, the file is not manually edited with an Hex program, the only modification is deleting the last null byte of the generated zip string in notepad.

Thanks to @hanshenrik for the help trying to share this shortest version!

**Longer version that can be tested online:**

## PHP, (version \< 8.0) 104 bytes

```
<?=gzinflate(base64_decode(U1CAAC044OVC5SOLY4pCZaAsmAq4SoQUFl24ZIiSQ3EjjAOzDkkSXUpLAQnAHYnbZzjDAj3cAA));

```

Online PHP function(s)

Simply encoded with gz, which is not available in TIO so I provided another site's link. (inspired by this answer after following @Neil's link "In Honor of Adam West")

EDIT: zip shortened by removing trailing spaces + finally it's only alphanumeric chars so I could remove the quotes (the warning would not show in the output in TIO like it does with Online PHP functions)

# Answer
> 2 votes
# Charcoal, 36 bytes

```
⭆”←＆∨n？Þ\`W!π↖δ℅If#≕W⧴@b⪪¹λ”∨×Σι*ι‖Ｍ←

```

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

```
⭆”...”

```

Map over partially RLE-encoded string.

```
∨×Σι*ι

```

Replace non-zero digits with their count of `*`s.

```
‖Ｍ←

```

Reflect the result.

Out of interest, I tried porting my answer to In Honor of Adam West but that weighed in at a massive 39 bytes (although it was still my second best approach).

# Answer
> 2 votes
# 05AB1E, ~~33~~ 32 bytes

-1 byte thanks to Kevin Cruijssen!

Very similar to my Python answer, this encodes the half of every line as a 3-digit base 8 integer.

```
•γÂÂàª[O‘ôγÌ¹‚5•₄;вε8в„* Þ×J}º.c

```

Try it online!

**Commented:**

```
•γÂÂàª[O‘ôγÌ¹‚5•₄;в  # compressed integer list
                     # [5,135,263,467,327,391,391,349,348,432,263,135,5] (base 10)
                     # [5,207,407,723,507,607,607,535,534,660,407,207,5] (base 8)

ε         }          # map over the integers; example: 467
 8в                  # convert to base 8               [7, 2, 3]
   „*                # push the string "* "
       Þ             # create a infinite list by cycling the characters
        ×            # for each each base-8 digit, repeat the character at the same index this many times
                     #                                 ['*******', '  ', '***']
         J           # join into a single string       '*******  ***'

º                    # mirror every line
 .c                  # centralize and join by newlines

```

# Answer
> 2 votes
# Perl 5, 93 bytes

```
say'IK
ES
CW
BHCGCH
BY
A[
A[
AFDKDF
BFDIDF
BGMG
CW
ES
IK'=~s/./('*',$")[--$|]x(-65+ord$&)/ger

```

Try it online!

# Answer
> 2 votes
# Vyxal `j`, 50 bytes

```
»
«0QÞ*⌊B⊍E⟨}¹ǍaȦM.¥⁺⊍Ṅ₂ṖA«[¥ȯ⇩»3τ` *
`viṅøṀ`
`€øĊ

```

Try it Online!

All hail new vertical mirror!!

# Answer
> 2 votes
# ///, 121 bytes

```
/4/33//3/22//2/11//1/**//8/99//9/00//0/  /813
914
0124
 *120120*12
 34
134
134
*2 013 0*2
 *2 03 0*2
 129812
0124
914
813

```

Try it online!

Will add explanation soon!

In the meantime, if this isn't obscure enough, see if you can figure this one out!

# Answer
> 2 votes
# Vim, 82 bytes

```
13i*<esc>Ypr Yppr p3r p7r :g/^/t0
3j2r 3jYp6|3r jh3r jh6r :%s/\v(\*+)( *)(.*)/&\3\2\1

```

Try it online!

### Explanation

Approach: 1) Make a quarter-circle with asterisks. 2) Mirror it vertically. 3) Replace some of the asterisks with spaces. 4) Mirror it horizontally.

```
13i*<esc>

```

Insert 13 asterisks.

```
Ypr<spc>

```

Make a copy of the line and replace the first character of the copy with a space.

```
Yppr<spc>

```

Make two copies of that line. Replace the first non-space character of the second copy with a space.

```
p3r<spc>p7r<spc>

```

Paste another copy and replace the first three characters with spaces; paste one more copy and replace the first seven characters with spaces.

```
:g/^/t0<nl>

```

A modified version of this trick for reversing the lines in the buffer: instead of moving each line to the beginning with `m0`, copy it to the beginning with `t0`, effectively mirroring the whole buffer upward.

```
3j2r<spc>

```

The cursor is on the first asterisk of the top line; if we go down three times, we happen to land on the leftmost character that should become the eye. Replace two characters with spaces.

```
3jYp

```

Go down three more times and make a copy of the line. (This is the center line; we need three copies of it, but the mirroring code left us with only two.)

```
6|3r<spc>

```

Go to the sixth character; replace three characters with spaces.

```
jh3r<spc>

```

Go down one line, go left one column, and replace three characters with spaces.

```
jh6r<spc>

```

Go down and left again and replace six characters with spaces.

```
:%s/\v

```

On all lines, substitute (using the "very magic" setting so we don't have to backslash all the parentheses)...

```
(\*+)( *)(.*)

```

... one or more asterisks, zero or more spaces, and the rest of the line if any...

```
/&\3\2\1<cr>

```

... with the full match followed by the three capture groups in reverse order.

# Answer
> 1 votes
# Retina 0.8.2, 82 bytes

```

i10¶e18¶c22¶b7c6c7¶b24¶26¶26¶5d10d5¶b5d8d5¶b6jd6¶c22¶e18¶i10
\d+
$**
T`l`d
\d
$*

```

Try it online! Explanation: Uses run-length encoding, where numbers encode `*`s and letters `b-j` encode spaces (so for the 12 spaces of the mouth I need two letters).

```

i10¶e18¶c22¶b7c6c7¶b24¶26¶26¶5d10d5¶b5d8d5¶b6jd6¶c22¶e18¶i10

```

Insert the run-length encoded text.

```
\d+
$**

```

Decode integers to runs of `*`s.

```
T`l`d

```

Replace letters `b-j` with digits `1-9`.

```
\d
$*

```

Decode digits to runs of spaces.

# Answer
> 1 votes
# Jelly, ~~35~~ 33 bytes

```
“ ṄUçɓĠḷƑżØS`’b12o43µ⁾ *ṁxs13m€0Y

```

Try it online!

## Explanation

```
“ ṄUçɓĠḷƑżØS`’b12o43µ⁾ *ṁxs13m€0Y   Main monadic link
“ ṄUçɓĠḷƑżØS`’                      8060783762011200773438708597
              b12                   Convert to base 12 => [8,5,4,9,2,11,1,7,2,3,1,0,3,5,1,5,3,4,1,6,8,11,4,9,8,5]
                 o43                Logical OR with 43 => [8,5,4,9,2,11,1,7,2,3,1,43,3,5,1,5,3,4,1,6,8,11,4,9,8,5]
                    µ               Use as argument to new monadic chain
                     ⁾ *ṁ           Repeat " *" to have the same length
                         x          Repeat each character as many times as the corresponding number
                          s13       Split into chunks of 13
                             m€0    Mirror each
                                Y   Join with newlines

```

# Answer
> 1 votes
# Bubblegum, 49 bytes

Obligatory bubblegum entry. Generated with `zopfli --i1000 --deflate -c smiley.txt | xxd`.

```
00000000: 5380 022d 38e0 42e6 a208 8369 4c09 9838  S..-8.B....iL..8
00000010: 4401 8246 c860 ea01 6272 a560 ae83 71a0  D..F.`..br.`..q.
00000020: 56c1 b898 3230 3e02 60f5 11e1 10c0 0c2b  V...20>.`......+
00000030: 00                                       .

```

Try it online!

# Answer
> 1 votes
# C (gcc), ~~175~~ 168 bytes

-7 bytes thanks to ceilingcat

```
*s;i;p(x,y){for(i=x-printf("%*s",x-97,"");i++<y;printf("*"));s++;}f(){for(s=L"ikjesjcwjbhcgchjbyja{ja{jafdkdfjbfdidfjbgmgjcwjesjikA";*s-'j'?p(*s,s[1]):puts(""),*s++;);}

```

Try it online!

Explanation before some golfing:

```
char*s="ikjesjcwjbhcgchjbyja{ja{jafdkdfjbfdidfjbgmgjcwjesjik";

```

This string encodes the number of consecutive spaces and asterisks along with the newlines position.

```
p(x,y){for(i=97;i++<x;printf(" "));for(i=97;i++<y;printf("*"));s++;}

```

This function takes as arguments the ASCII value of two characters and use the first one to print whitespace and the second to print asterisks.

```
f(){*s-'j'?p(*s,s[1]):puts("");*s++&&f();};

```

Here we check whether the current character is a `'j'`, which has been chosen to encode a newline.

# Answer
> 1 votes
# Julia, 102 bytes

```
println.(split(join(collect(" *"^18).^(b"HJKRFVCGBFBGBXAyCJCEAECHCEBFLFCVFRLJ".-64)),r"(?<=\G.{25})"))

```

Try it online!

the string stores the amount of consecutive `' '` and `'*'`. We than split the string in 26-character chunks and print with line breaks

# Answer
> 1 votes
# Japt `-R`, ~~66~~ ~~55~~ 52 bytes

-11 bytes thanks to AZTECCO

```
"ǿ߿࿧࿿῿῿἟ྏ࿀߿ǿ"¬®c s" *" ê1Ãû

```

Test it

## Explanation

```
"..."              // String with characters at codepoints:
                   //   31   ('        *****' as binary string where ' ' -> 0, '*' -> 1)
                   //   511  ('    *********' as binary string where ' ' -> 0, '*' -> 1)
                   //   2047 ('  ***********' as binary string where ' ' -> 0, '*' -> 1)
                   //   4071 (' *******  ***' as binary string where ' ' -> 0, '*' -> 1)
                   //   4095 (' ************' as binary string where ' ' -> 0, '*' -> 1)
                   //   8191 ('*************' as binary string where ' ' -> 0, '*' -> 1)
                   //   8191 ('*************' as binary string where ' ' -> 0, '*' -> 1)
                   //   7967 ('*****   *****' as binary string where ' ' -> 0, '*' -> 1)
                   //   3983 (' *****   ****' as binary string where ' ' -> 0, '*' -> 1)
                   //   4032 (' ******      ' as binary string where ' ' -> 0, '*' -> 1)
                   //   2047 ('  ***********' as binary string where ' ' -> 0, '*' -> 1)
                   //   511  ('    *********' as binary string where ' ' -> 0, '*' -> 1)
                   //   31   ('        *****' as binary string where ' ' -> 0, '*' -> 1)
     ¬             // Convert the string to an array
      ®            // map array with func:
       c           //   convert char to codepoint
         s" *"     //   convert codepoint to a binary string with chars "* "
              ê1   //   concatenate reverse of the binary string to itself
                 û // centre-pad result of map

The -R flag then concatenates the resulting array with newlines

```

# Answer
> 1 votes
# Perl 5 `-M5.10.0`, 73 bytes

```
$_=unpack"B*","......w......|{.......";y/01/ */,say$_.reverse for/.{13}/g

```

Try it online!

## Explanation

This solution consists of mostly unprintable characters which are a packed binary string containing a representation of the left-half of the image as `0`s and `1`s which is `unpack`ed into `$_`, then `y///` (`tr///`) changes all the `0`s to s and the `1`s to `*`s, before the `/.{13}/g` (`m//`) matches each stretch of 13 chars passing them to `say` (`$_`), along with the `reverse` of `$_`, to print the result on individual lines.

# Answer
> 1 votes
# Python, ~~142~~ 140 bytes

```
for x in"销夀㬀✣Ⰰᴀᴀᔵ┴♠㬀夀销":a,b,c,d=[int(x,16)for x in hex(ord(x))[2:]];s=' '*(a-1)+'*'*b+' '*c+'*'*d;print(s+s[::-1])

```

Try it online

This is very... stupid. It's in the vein of another Python answer but uses a more naive encoding:

```
(number of alternating spaces and asterisks in half of the image.)
_ *  _ *
========
9 5  0 0  \u9500 销
5 9  0 0  \u5900 夀
3 11 0 0  \u3b00 㬀
2 7  2 3  \u2723 ✣
2 12 0 0  \u2c00 Ⰰ
1 13 0 0  \u1d00 ᴀ
1 13 0 0  \u1d00 ᴀ
1 5  3 5  \u1535 ᔵ
2 5  3 4  \u2534 ┴
2 6  6 0  \u2660 ♠
3 11 0 0  \u3b00 㬀
5 9  0 0  \u5900 夀
9 5  0 0  \u9500 销

```

# Answer
> 1 votes
# Excel, 111 bytes

## Formula, 60 bytes

```
=CONCAT(IF(A1:A32="","
",REPT(" ",A1:A32)&REPT("*",B1:B32)))

```

## Data in cells, 51 bytes

|  | A | B |
| --- | --- | --- |
| 1 | 8 | 10 |
| 2 |  |  |
| 3 | 4 | 10 |
| 4 |  |  |
| 5 | 2 | 22 |
| 6 |  |  |
| 7 | 1 | 7 |
| 8 | 2 | 6 |
| 9 | 2 | 7 |
| 10 |  |  |
| 11 | 1 | 24 |
| 12 |  |  |
| 13 | 0 | 26 |
| 14 |  |  |
| 15 | 0 | 26 |
| 16 |  |  |
| 17 | 0 | 5 |
| 18 | 3 | 10 |
| 19 | 3 | 5 |
| 20 |  |  |
| 21 | 1 | 5 |
| 22 | 3 | 8 |
| 23 | 3 | 5 |
| 24 |  |  |
| 25 | 1 | 6 |
| 26 | 12 | 6 |
| 27 |  |  |
| 28 | 2 | 22 |
| 29 |  |  |
| 30 | 4 | 18 |
| 31 |  |  |
| 32 | 8 | 10 |

Link to Spreadsheet

Column A indicates the number of " "; Column B the number of "\*". If column A is "" then add a line feed.

# Answer
> 0 votes
# C (gcc), 145 bytes116 Bytes

Thanks to ASCII-only, who managed to shave 29 bytes off.

```
c;f(i){for(i=0;c="+m'u%y$*%)%j${#}#}#(&-&h$(&+&h$)/i%y'u+-"[i++];c&64&&puts(""))while(--c%64>34)putchar(i&1?32:42);}

```

Try it online!

I had to start the encoding at 35, since 34 is `"` which requires an additional `\` as escape character and thus would increase the total character count. Each character in the string `+m'u%y$*%)%j${#}#}#(&-&h$(&+&h$)/i%y` minus 35 represents the number of spaces and asteriks, in an alternating pattern. This achieves a compression rate of almost 8 (318/40).

Ungolfed:

```
char*s="+m'u%y$*%)%j${#}#}#(&-&h$(&+&h$)/i%y'u+-";
void f()
{
    for( int i=0; i < 40; ++i)
    {
        for(int j=35; j < (s[i]&63); ++j )
        {
            if( i&1 )
            {
                printf("*");
            }
            else
            {
                printf(" ");
            }
        }
        if( s[i] & 64 )
        {
            printf("\n");
        }
   }
}

```

# Answer
> 0 votes
# Pyth, 57 bytes

```
jm.[26+_K++*\*%/J|Cd390 8 8*\ /J64*\*%J8K\ ",5Ÿ6>>íå5,

```

Try it online!

# Answer
> 0 votes
## x86-16 machine code, ~~101~~ 96 bytes

Saved 5 bytes thanks to @peterferrie.

```
0BEC:0100  BE 44 01 31 DB AD 91 E3-22 51 E8 20 00 59 C1 E9   .D.1...."Q. .Y..
0BEC:0110  03 80 36 2E 01 08 E8 14-00 80 36 2E 01 08 83 FB   ..6.......6.....
0BEC:0120  0C 74 05 B8 0A 00 CD 29-43 EB DA CD 20 D1 E1 19   .t.....)C... ...
0BEC:0130  C0 24 0A 0C 20 83 FB 09-75 03 83 F0 0A CD 29 85   .$.. ...u.....).
0BEC:0140  C9 75 EA C3 F8 00 F8 0F-F8 3F 38 7F F8 7F F8 FF   .u.......?8.....
0BEC:0150  F8 FF F8 F8 78 7C F8 81-F8 3F F8 0F F8 00 00 00   ....x|...?......

```

Standalone executable.

Instruction listing (nasm syntax):

```
org 100h

    mov si, face
    xor bx, bx
lop:    lodsw
    xchg cx, ax
    jcxz ed
    push cx
    call loop
    pop cx
    shr cx, 3
    xor byte [loop+1], 8
    call loop
    xor byte [loop+1], 8
    cmp bx, 12
    je sk
    mov ax, 0Ah
    int 29h
sk: inc bx
    jmp lop
ed:
    int 20h

loop:   shl cx, 1
    sbb ax, ax
    and al, 0ah
    or al, ' '
    cmp bx, 9
    jne yy
    xor ax, 10
yy: int 29h
    test cx, cx
    jnz loop
    ret

face:   dw 00f8h, 0ff8h, 3ff8h, 7f38h, 7ff8h, 65528, 65528, 63736, \
        7c78h, 33272, 3ff8h, 0ff8h, 00f8h, 0000h

```

## Example run

```
C:\test>smile.com
        **********
    ******************
  **********************
 *******  ******  *******
 ************************
**************************
**************************
*****   **********   *****
 *****   ********   *****
 ******            ******
  **********************
    ******************
        **********

```

# Answer
> 0 votes
# Python 3.8 (pre-release), 123 bytes

```
print(''.join(['\n',['*'*x,' '*-x][x<0]][x!=0]for x in(y-90for y in b'RdZVlZXpZYaX`XaZYrZtZtZ_WdW_ZY_WbW_ZY`N`ZXpZVlZRd')))

```

Try it online!

## Explanation

The list-switch part outputs newlines when x is 0, x number of `'*'` characters when x \> 0, and -x number of `' '` characters when x \< 0. I think of it as abs(x) characters, where the sign determines which character I'm writing.

The byte list comprehension subtracts 90 from each byte in the buffer to feed the outer comprehension the expected values centered at 0, since a buffer can't hold negatives in a literal (afaik).

Used a script to encode the smiley face as character run lengths to create the bytes literal... I think I lost the original but may add it later.

# Answer
> 0 votes
# JavaScript (Node.js), 249 bytes

```
s=`\t*****
    *********
  ***********
 *******  ***
 ************
*************
*************
*****   *****
 *****   ****
 ******
  ***********
    *********
\t*****`;s=s.split`\n`;s=s.map(l=>l+[...l].reverse().join``);console.log(s.join`\n`)

```

Try it online!

---
Tags: code-golf, kolmogorov-complexity
---


title: Code Golf: Your own pet ASCII snake

text:
# Question
Title: Code Golf: Your own pet ASCII snake
So, I wrote myself a one-liner which printed out a snake on the console. It's a bit of fun, and I wondered how I might condense my code...

Here's a (short) example output:

```
                +
                 +
                  +
                   +
                   +
                   +
                  +
                   +
                    +
                    +
                    +
                     +
                     +
                      +
                      +
                       +
                      +
                     +
                     +
                    +

```

Here's the specs:

* In each line, a single non-whitespace character (whichever you like) is printed to the console, initially with 29 to 31 spaces padding to the left of it.
* Each iteration, a random decision is made between these three actions
    + The amount of padding decreases by 1
    + The amount of padding remains the same
    + The amount of padding increases by 1

Do this 30 times, to print 30-segment long a snake to the console.

The shortest answer in bytes wins.

# Answer
# 05AB1E, ~~15~~ 14 bytes

```
30DF2Ý<+ΩD0sú,

```

Try it online!

Uses `0`.

### Explanation

```
30DF2Ý<+ΩD0sú,
30D            # Push 30 to the stack (One for the amount of iterations we are going to perform and one for the initial padding)
   F           # Pop one of the 30s and perform the following that many times...
    2Ý          # Push [0,1,2] ...
      <         # and create [-1,0,1] from that
       +        # Add the last padding to every entry (e.g. 30 in the beginning resulting in [29,30,31]
        Ω       # Pick one of the results at random ...
         D      # and push it to the stack twice
          0     # Push 0 (Any character will work fine here) ...
           sú   # and pad it with the randomly chosen amount of spaces in the front
             ,  # Finally print the result with a trailing newline

```
> 15 votes

# Answer
# Random Brainfuck, ~~123 122~~ 121 bytes

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

```

Try it online!

Random Brainfuck is an extension of brainfuck, with the helpful addition of the `?` command, which sets the current cell to a random byte. This prints a snake made of `!`s, which looks more like footsteps than a snake funnily enough.

### How It Works:

```
+[--[<]>>+<-]>+ Create the value 30
[->+>+>+<<<]    Copy it three times
++++++++++      Create a newline cell
>>++<            Adds 2 to the second copy to make it a space and move to the counter
[ While counter
  >>[->+<<.>]>[-<+>] Print out the padding cell number of spaces
  ?>+++<[>->+<[>]>[<+>-]<<[<]>-] Get 3-(random byte%3)
  >-->,<[-<<<+>>>]   Add (result-2) to the padding cell
  <<<<+.-<           Print an exclamation mark
  <<.                Print a newline
  >-                 Decrement counter
] end loop

```

Another solution that sticks to the *letter* of the question, rather than the spirit.

### 87 bytes

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

```

Try it online!

This one is heavily biased towards leaving the padding alone, but increasing or decreasing the padding are both equally possible. Each one has a slightly less than 1 in 256 chance to happen.
> 15 votes

# Answer
# C (gcc), ~~61~~ ~~58~~ 56 bytes

Answer edited to reflect rules changes...

```
i;f(s){for(s=i=31;--i;printf("%*d\n",s+=1-rand()%3,8));}

```

Try it online!
> 8 votes

# Answer
# JavaScript (ES8), ~~63~~ ~~62~~ 60 bytes

Includes a trailing newline. `*2-1` could be replaced with `-.5` for a 1 byte saving but the chances of each line being the same length as the previous line would be greatly increased. Of course, as "random" isn't defined in the challenge, the RNG *could* be replaced with `new Date%3-1` for a total byte count of 55.

```
f=(x=y=30)=>x?``.padEnd(y+=Math.random()*2-1)+`+
`+f(--x):``

```

Saved a byte thanks to someone who deleted their comment before I could catch the name. I'd actually tried it this way with `repeat` and `padStart` but didn't think to try `padEnd` \- don't know why!

```
o.innerText=(
f=(x=y=30)=>x?``.padEnd(y+=Math.random()*2-1)+`+
`+f(--x):``
)()
```

```
<pre id=o>
```

---

## Bonus

For the same number of bytes, here's a version that takes the number of starting spaces & iterations as input.

```
f=(x,y=x)=>x?``.padEnd(y)+`+
`+f(--x,y+Math.random()*2-1):``

```

```
o.innerText=(
f=(x,y=x)=>x?``.padEnd(y)+`+
`+f(--x,y+Math.random()*2-1):``
)(i.value=30);oninput=_=>o.innerText=f(+i.value)
```

```
<input id=i type=number><pre id=o>
```
> 7 votes

# Answer
# C# (.NET Core), ~~112~~ ~~110~~ ~~106~~ ~~100~~ ~~99~~ 98 bytes

```
v=>{var r="";for(int t=30,i=t;i-->0;r+="+\n".PadLeft(t+=new System.Random().Next(3)-1));return r;}

```

-1 byte thanks to *@raznagul*.
-1 byte thanks to *@auhmaan*.

**Explanation:**

Try it online.

```
v=>{                      // Method with empty unused parameter and no return-type
  var r="";               //  Result-string, starting empty
  for(int t=30,           //  Temp-integer, starting at 30
      i=t;i-->0;          //  Loop 30 times
    r+=                   //   Append the result-String with:
       "+\n"              //    The character and a new-line,
            .PadLeft(     //    left-padded with `t` spaces,
                     t+=new System.Random().Next(3)-1));
                          //    after `t` first has been changed with -1, 0, or 1 randomly
  return r;}              //  Return the result-string

```
> 7 votes

# Answer
## Retina, 24 bytes

```

30* +
-29{¶<`^

S,2@1`

```

Try it online!

### Explanation

```

30* +

```

Initialise the working string to the first line, i.e. 30 spaces and a `+`.

```
-29{¶<`^

```

There's a space on the second line. `-29{` wraps the remainder of the program in a loop, which is run 29 times. `¶<` prints the working string at the beginning of each loop iteration with a trailing linefeed. The atomic stage itself inserts a space at the beginning of the string (the basic idea is to insert one space, and then randomly remove 0–2 spaces, because that's a byte shorter than randomly choosing between deletion, inserting and no-op).

```
S,2@1`

```

This matches the empty regex against the input, which gives us every position between characters (and the start and end of the string). Then `,2` keeps only the first three matches, i.e. the matches after zero, one and two spaces. `@` selects a random one of those three matches. Then the split stage (`S`) splits the input around that match. And the `1` tells it to keep only the second part of the split. In other words, we discard everything up to our random match.

The 30th line, which is the result of the final loop iteration, is printed implicitly at the end of the program.
> 7 votes

# Answer
# VBA, ~~60~~ ~~59~~ 49 Bytes

```
For l=1To 30:?Spc(30+i)"+":i=i+Sgn(Rnd()-.5):Next

```

Paste it in the Immediate window and hit enter. (Make sure explicit declaration is turned off!)

*Far* more likely to move than to stay in a line (i.e. actions are not equally weighted) but that was not a specified requirement (Fortunately!)

**{EDIT}** *Saved 1 byte by removing the space between `=1` and `To`*

**{EDIT2}** *Saved **10** bytes thanks to remoel's comment*

Old Versions:

```
'V1
i=30:For l=1 To 30:?String(i," ")&"+":i=i+Sgn(Rnd()-.5):Next
'V2
i=30:For l=1To 30:?String(i," ")&"+":i=i+Sgn(Rnd()-.5):Next

```
> 7 votes

# Answer
# C, 56 bytes

```
n;f(p){n>29?n=0:f(printf("%*d\n",n++?p-rand()%3:31,0));}

```

Try it online!

**Explanation:**

```
n; // As a global variable, n is initialized to zero.
f(p)
{
    // Call the function recursively until n > 29.
    n > 29

        // At the end, set n back to zero.
        ? n=0

        // On the first iteration, n == 0 and p has an indeterminate value.
        // 'n++ ? p-rand()%3 : 31' returns 31 (without reading p), and thus
        // 30 spaces get printed. printf() returns the number of characters
        // printed, 32 (30 spaces + '0' + '\n').
        //    On subsequent iterations, p has the value the previous printf
        // call returned, which is the padding on last iteration + 2. Also,
        // n > 0, so the same expression now returns p-rand()%3, and thus
        // the padding changes either by -1, 0, or 1 spaces. The function
        // is again called with the value of the current line's padding + 2.
        : f(printf("%*d\n", n++ ? p-rand()%3 : 31, 0));
}

```

# C (gcc), 55 bytes

```
n;f(p){n=n<30&&f(printf("%*d\n",n++?p-rand()%3:31,0));}

```

Depends on **f** "returning" the value assigned to **n** in the function, which is undefined behaviour, but works consistently with gcc when no optimizations are enabled.

Try it online!
> 7 votes

# Answer
# APL (Dyalog), 20 bytes

*1 byte saved thanks to ngn*

```
↑'+'↑⍨¨-+\30,2-?29⍴3

```

Try it online!
> 6 votes

# Answer
# Charcoal, ~~14~~ 11 bytes

```
× ³⁰Ｆⅈ✳～‽³+

```

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

```
× ³⁰        Print 30 spaces (forces the desired indentation)
    Ｆⅈ      Repeat the same number of times
      ✳～‽³  Move a random downward direction after printing
          + Print a `+`

```

Would be only ~~10~~ 8 bytes if there was no initial indentation requirement.
> 6 votes

# Answer
# Python 2 , ~~83~~ ~~65~~ 64 bytes

Straightforward approach:

```
import os
k=30
exec"print' '*k+'+';k+=ord(os.urandom(1))%3-1;"*k

```

Try it online!

Thanks to @Rod for saving some bytes! Thanks to @ovs for -1 byte!

Edit: changed variable name and output string to the letter 's'

# More snake-like output for 88 bytes:

```
from random import*
s=[30,0]
exec"print' '*sum(s)+'(S)'[s[-1]+1];s+=[randint(-1,1)];"*30

```
> 6 votes

# Answer
# Java 8, ~~89~~ 87 bytes

First golf, I'm sure it could be much better..

Edit: Fixed first line thanks to Steadybox.

```
l->{for(int a=31,b=a;--a>0;){System.out.printf("%"+b+"c\n",'+');b+=2-Math.random()*3;}}

```

Try it online!

```
 l->{                                           //Begin lambda
    for(int a=31,b=a;--a>0;)                  //Initialise vars, loop through 30 lines
    {
        System.out.printf("%"+b+"c\n",'+');     //Print result
        b+=2-Math.random()*3;                   //Change padding by -1, 0, or 1
    }

```
> 6 votes

# Answer
# Java 8, ~~131~~ ~~129~~ ~~127~~ ~~126~~ ~~119~~ ~~108~~ 101 bytes

```
v->{String r="";for(int i=30,j,t=i;i-->0;r+="+\n")for(j=t+=Math.random()*3-1;j-->0;r+=" ");return r;}

```

**Explanation:**

Try it online.

```
v->{                     // Method with empty unused parameter and String return-type
  String r="";           //  Result-String, starting empty
  for(int i=30,j,t=i;    //  Two index integers, and a temp integer (starting at 30)
      i-->0;             //  Loop 30 times:
      r+="+\n")          //    After every iteration: Append the character and a new-line
    for(j=t+=Math.random()*3-1;
                         //   Change `t` with -1, 0, or 1 randomly
        j-->0;r+=" ");   //    And append that many spaces to the result-String
  return r;}             //  Return the result-String

```

**Old 119 byte answer:**

```
v->{String s="",r=s;int i=90,t=30;for(;i-->t;s+=" ");for(;i-->0;t+=Math.random()*3-1)r+=s.substring(t)+"+\n";return r;}

```

**Explanation:**

Try it online.

```
v->{                      // Method with empty unused parameter and String return-type
  String s="",            //  Temp-String, starting empty
         r=s;             //  Result-String, starting empty
  int i=90,t=30;          //  Temp integer, starting at 30
  for(;i-->t;s+=" ");     //  Fill the temp String with 60 spaces
  for(;i-->0;             //  Loop 30 times:
      t+=Math.random()*3-1//    After every iteration: Change `t` with -1, 0, or 1 randomly
    r+=s.substring(t)     //   Append the result with `60-t` amount of spaces
       +"+\n";            //   + the character and a new-line
  return r;}              //  Return the result-String

```
> 5 votes

# Answer
# PHP, 61 bytes

```
for($p=32;$i<30;$i++)echo str_pad("+
",$p+=rand(-1,1),' ',0);

```

Try it online!
> 5 votes

# Answer
# Perl, 36 bytes

```
perl -E '$#a=29;map{$#a+=rand(3)-say"@a -"}@a'

```
> 5 votes

# Answer
# Japt, ~~13~~ 12 bytes

Outputs an array of lines.

The first line can be removed, saving 3 bytes, to allow the number of starting spaces & iterations to be taken as input.

```
30
°ÆQùU±Ó3ö

```

Test it or try it with input

```
30\n°ÆQùU±Ó3ö
30\n              :Assign 30 to variable U
    °             :Postfix increment U
     Æ            :Map the range [0,30)
      Q           :  Quotation mark
       ù          :  Left pad with space to length
        U±        :    Increment U by
          Ó       :      Bitwise NOT of the negation of (i.e., decrement)
           3ö     :      Random integer in the range [0,3)

```
> 5 votes

# Answer
# Vyxal, 12 bytes

```
30:(kɽ℅+:×꘍,

```

Try it Online!

```
30:          # Push 30 twice
   (         # Iterate over one copy (30 times)
       +     # Increment the number on the stack (initially 30) by...
      ℅      # A random choice from
    kɽ       # [-1, 0, 1]
        :    # Duplicate
         ×꘍  # Prepend that many spaces to an asterisk
           , # And output, leaving the number on the stack

```

An alternative
> 5 votes

# Answer
# , ~~72~~ ~~69~~ 67 bytes

```
cat(sprintf(paste0("% ",cumsum(c(30,sample(3,29,T)-2)),"s"),"+\n"))

```

Thanks to Zahiro Mor for 2 extra bytes!

Try it online!
> 4 votes

# Answer
# Ruby, ~~45~~ 39 bytes

```
x=30
x.times{puts' '*(x+=rand(3)-1)+?S}

```

Try it online!

Modifying `x` during the loop does not affect the loop counter. I chose S as a particularly snakelike output character.

-6 bytes: Use `rand(3)-1` instead of `[-1,0,1].sample`. *Thanks, Eric Duminil!*
> 4 votes

# Answer
# Jelly, 18 bytes

```
1ŒRX+
30Ç’Ð¡⁶ẋ;€0Y

```

Try it online!

The chosen character is **0**. If returning a list of list of characters is allowed, then the `Y` can be dropped and the submission can be turned into a niladic chain for **17 bytes**. Alternative.

## How it works

```
30Ç’Ð¡⁶ẋ;€0Y | Niladic main link.
30           | Starting from 30...
  Ç’Ð¡       | ... Repeat the helper link 29 times and collect the results in a list.
             | (This list includes the first 30, so there are actually 30 numbers).
      ⁶ẋ     | Repeat a space that many times, for each item in the list.
        ;€0  | Append a 0 to each.
           Y | And join by newlines.
-------------+
1ŒRX+        | Monadic helper link. Alternatively, you can use µ1ŒRX+µ instead of the Ç.
1            | The literal one.
 ŒR          | Symmetric range from –1 to 1.
   X+        | Choose a random number therein and add it to the argument.

```

# Jelly, 16 bytes

Combining mine, Erik’s and Jonathan’s solutions, we can golf this down to 16 bytes. The chosen character is **1**.

```
’r‘X
30Ç’Ð¡Ṭ€o⁶Y

```

Try it online!

Thanks to Jonathan Allan for the heads-up (on `Ṭ€o⁶`).
> 4 votes

# Answer
# Swift, 101 bytes

```
import UIKit
var g=29;for _ in 0...g{print((0..<g).map{_ in" "}.joined(),0);g+=Int(arc4random()%3)-1}

```

## Explanation

A full program. This uses a rather odd trick: `arc4random()` is a member of the `Darwin` module, but `UIKit` also comes with this function installed, so it saves a byte :) Also uses one of my Swift golfing tips for repeating strings an arbitrary number of times.

```
import UIKit        // Imports the UIKit module, necessary for the RNG.
var g=29;           // Declares an integer variable g by assigning it to 30.
for _ in 0 ... g {  // Execute the code block 30 times (for each integer in [0; g]):
 print(             // Output the following:
  (0..<g).map       // For each integer in [0; g)...
   {_ in" "}        // ... return a literal space character.
    .joined()       // ... And join the result to a single string.
             ,0     // Also print a "0" preceded by a single space (g starts from 29).
 );
g+=                 // Increment the variable g by...
   arc4random()%3   // ... A random integer, modulo 3...
   Int(...)-1       // ... Casted to an integer (yes, this is needed!) and decremented.
}

```
> 4 votes

# Answer
# R, ~~54~~ 53 bytes

```
cat(sprintf('
%*s',cumsum(c(30,sample(3,29,T)-2)),0))

```

Similar idea as above, but with shortened `sprintf` code and a shorter character string literal. Instead of `\n` (two bytes) I’m using a literal line break (one byte).

`Try it online!`
> 4 votes

# Answer
# SenseTalk, 237 198 Bytes

This is a language that I came to know and love about a decade ago. It's the scripting language that drives the automated testing tool Eggplant Functional. I was an avid user of the tool for many years before joining the company for a while. It's not the most golf-capable language, but I find it very enjoyable to write in. Golfing in it is actually quite challenging as the language is meant to be verbose and English-like... took me quite a while to get it down to 237 bytes.

```
set s to "                              +"&lf
set p to s
repeat 30
set a to random(0,2)
if a equals 0
delete first char of p
else if a equals 1
put " " before p
end if
put p after s
end repeat
put s

```

## Ungolfed/Explanation

```
set the_snake to "                              +"&lf #assign the first line of the snake
set previous_line to the_snake                        #set up for the loop

repeat 30 times                                       #loop 30x
    set action to random(0,2)                         #random add/subtract/stay the same

    if action equals 0
        delete the first character of previous_line   #SenseTalk really shines at string manipulation
    else if action equals 1
        put " " before previous_line                  #insert a character at the beginning
    end if

    put previous_line after the_snake                 #plop the new segment into the string
end repeat                                            #close the loop

put the_snake                                         #print to standard out

```

Edit: Saved 36 bytes thanks to @mustachemoses
> 4 votes

# Answer
# , 23 bytes

```
echo(8":~+/)\31,1-?29$3

```

Try it online!
> 3 votes

# Answer
# PowerShell, 42 bytes

```
1..($l=30)|%{" "*$l+"x";$l+=-1,0,1|Random}

```

Try it online!

Loops from `1` to `$l=30`. Each iteration we put `$l` spaces plus an `x` onto the pipeline as a string, then `+=` either of `-1, 0, 1` based on `Get-Random` into `$l` for the next loop. Those strings are gathered from the pipeline and an implicit `Write-Output` gives us a newline-separated list for free.
> 3 votes

# Answer
# Bash, 53

* 3 bytes saved thanks to @Dennis

```
for((i=p=30;i--;p+=RANDOM%3-1));{ printf %${p}s+\\n;}

```

Try it online.
> 3 votes

# Answer
# Octave, ~~53 51 50~~ 49 bytes

```
printf('%*d\n',[a=31+cumsum(randi(3,1,30)-2);~a])

```

Try it online!

Saved 1 byte by no longer doing any looping. Saved another as Octave has `printf` as well as `fprintf`.

This new code creates an array of 30 random integers in the range `-1:1`. It then cumulatively sums the array and adds 30, which gives the desired sequence.

The result is printed using `fprintf` with a format that says "A decimal number, padded to a specified width, followed by a new line. The width will be the first value input, and the decimal number will be the second value input. If the number of values input is more than this, Octave will keep repeating the print automatically to get the desired output.

To achieve the looping then, we need only interleave zeros between the sequence array so the `fprintf` function uses each value in the sequence as a width, and each zero as the digit to be printed.

Prints an output like:

```
                              0
                             0
                              0
                             0
                              0
                               0
                              0
                               0
                              0
                              0
                             0
                            0
                           0
                           0
                           0
                          0
                           0
                            0
                             0
                              0
                              0
                             0
                             0
                              0
                               0
                              0
                              0
                               0
                               0
                                0

```

---

The above code doesn't always print exactly 30 spaces on the first line. It will be either 29, 30, or 31. To correct that, you would use this 53 byte version:

```
x=31;for i=2:x;fprintf('%*d\n',x,0);x+=randi(3)-2;end

```
> 3 votes

# Answer
# Python 3.6, ~~84~~ ~~73~~ 69 bytes

```
from random import*
x=30
exec("print(' '*x+'+');x+=randint(-1,1);"*x)

```

Thanks to @WheatWizard for -11 bytes. Thanks to @JoKing for -4 bytes.
> 3 votes

# Answer
# ES5, ~~97~~ ~~95~~ 81 bytes

```
for(p=i=30;i--;)console.log(Array(p).join(" ",r=Math.random()*3|0,p+=r>1?-1:r)+0)
```

**ES5, ~~112~~ 98 bytes** if function format is needed:

```
function a(){for(p=i=30;i--;)console.log(Array(p).join(" ",r=Math.random()*3|0,p+=r>1?-1:r)+0)}a()
```
> 3 votes

# Answer
## Lua, ~~81~~ 75 bytes

```
n=30;for i=1,n do print(("%-"..n.."s+"):format(" "))n=n-2+math.random(3)end

```

In `for i=1,n ...` the *to\_exp* `n` is evaluated only once before entering the loop, saving one byte.

-6 thanks to @user202729

Try it online!
> 3 votes

# Answer
# Red, 54 bytes

```
loop n: 30[loop n[prin" "]print"+"n: n - 2 + random 3]

```

Try it online!
> 2 votes

# Answer
# Pyth, ~~21~~ ~~19~~ ~~16~~ 15 bytes

*Thanks to Rod for saving 2 bytes and Mr. Xcoder for saving another 3 :)*

Uses `0`

```
VK30p*KdZ=+KtO3

```

Try it online!
> 2 votes

# Answer
# Python 2, 73 bytes

```
from random import*
l=c=30
while c>0:l+=randint(-1,1);print' '*l+"+";c-=1

```

Try it online!
> 2 votes

# Answer
# Mathematica, 74 bytes

```
""<>(" "&~Array~#<>"+
"&)/@Accumulate@Prepend[{-1,1}~RandomInteger~29,30]&

```

Pure function. Takes no input and returns a string as output.
> 2 votes

# Answer
# Julia 0.6, 52 49 bytes

Full program, prints a snake with `0`. I usually prefer comprehensions to `for...end` blocks because comprehensions return things. But since I'm printing anyway this is shorter, and you can use newlines at no cost (meaning equal to `;`) for a nice readable golf. Saved a byte by using `1:n` instead of `1:30` and two bytes with `println(" "^n,0)` instead of `println(" "^n*"+")`.

```
n=30
for i=1:n
println(" "^n,0)
n+=rand(-1:1)
end

```

Try it online!
> 2 votes

# Answer
# K4, 26 bytes

**Solution:**

```
-1(-31+\0,-1+29?3)$\:,"$";

```

**Example:**

```
q)k)-1(-31+\0,-1+29?3)$\:,"$";
                              $
                             $
                             $
                            $
                           $
                            $
                             $
                              $
                              $
                              $
                              $
                              $
                               $
                                $
                               $
                              $
                               $
                              $
                              $
                               $
                                $
                                 $
                                 $
                                $
                                 $
                                $
                               $
                                $
                                $
                                 $

```

**Explanation:**

Build a list of negative numbers to left-pad `"$"`, perform padding and print to stdout.

```
-1(-31+\0,-1+29?3)$\:,"*"; / the solution
-1                       ; / print to stdout and swallow return
                     ,"$"  / enlist "$" (e.g. ["$"])
  (              )$\:      / pad right with each-left
             29?3          / 29 choose 3, takes from 0 1 2
          -1+              / subtract 1, so range is -1 0 1
        0,                 / join 0
      +\                   / sums
   -31                     / add to -31

```

**Bonus:**

**27 byte** version in K (oK):

```
`0:(-31+\0,-1+29?3)$\:,"*";

```

Try it online!
> 2 votes

# Answer
# Icon, 51 bytes

-2 bytes thanks to Kevin Cruijssen

```
n:=30;every 1to 30do{write(repl(" ",n),8);n+:=?3-2}

```

Try it online!
> 2 votes

# Answer
# Clojure, 88 77 bytes

Always happy to provide a Clojure answer. Always sad, it's quite long.

```
(loop[x 30 p x](when(> x 0)(printf(str "%"p"d\n")1)(recur(dec x)(+(-(rand-int 3)1)p))))

```

Ungolfed:

```
(loop [x 30 p x]
  (when (> x 0)
    (printf (str "%" p "d\n") 1)
    (recur (dec x) (+ (- (rand-int 3) 1) p))))

```

### Update 1

Managed to shave off 11 bytes by making the code more idiomatic. Who would have thought that making things "more right" would end up being more effective in a Code Golf challenge.

```
(doseq[p(take 30(iterate #(+ %(-(rand-int 3)1))30))](printf(str "%"p"d\n")1))

```

Ungolfed:

```
(doseq [p (take 30
            (iterate
              #(+ % (- (rand-int 3) 1))
              30))]
  (printf (str "%" p "d\n") 1))

```

Try it online!
> 2 votes

# Answer
# SmileBASIC, 40 bytes

This answer turned out to be pretty boring.

```
X=30FOR I=1TO 30?" "*X;0X=X+RND(3)-1NEXT

```
> 2 votes

# Answer
# Pip, 21 bytes

```
Ln:30{PsXn.0--n+:RR3}

```

Try it online!

### Explanation

```
                       s is space (implicit)
 n:30                  Set n to 30
L    {              }  Loop that many times:
      P                 Print, with trailing newline:
       sXn               space, repeated n times
          .0             with "0" concatenated
            --n         Decrement n
               +:       and add to it (in-place)
                 RR3    randrange(3), i.e. a random integer between 0 and 2

```
> 2 votes

# Answer
# PHP, 58 56 bytes

```
for($a=$b=30;$a--;)echo str_pad('',$b+=rand(-1,1))."+
";

```

Try it online!

-2 bytes thanks to @Shaggy
> 2 votes

# Answer
# Jelly, 18 bytes

```
30µ3ẋX€_2+\+⁸Ṭ€o⁶Y

```

Uses `1` as the character.

**Try it online!**
> 1 votes

# Answer
# Jelly, 17 bytes

```
30µ’r‘Xµ’Ð¡⁶ẋp”.Y

```

Try it online!

Full program.
> 1 votes

# Answer
# Haskell, 108 bytes

```
import System.Random
0%_=pure()
n%p=putStrLn(([1..p]>>" ")++"+")>>randomRIO(-1,1::Int)>>=((n-1)%).(p+)
30%30

```

Try it online! I was surprised to find that this code works in GHCi without the explicit type annotation but not on TIO, until BMO told me about the `ExtendedDefaultRules` flag which is set by GHCi.
> 1 votes

# Answer
# SOGL V0.12, 14 bytes

```
'∑:{:@*O2ψH+╗p

```

Try it Here!
> 1 votes

# Answer
# AWK, 54 bytes

```
{for(f=30;a++<30;f+=int(4*rand()-2))printf"%"f"s\n",1}

```

Try it online!

Very straightforward. This requires a 1 line input to run. Could make it a "program" by using a `BEGIN` label.
> 1 votes

# Answer
# CJam, 31 bytes

```
{S*TN}:F;30:V{3,{V1-+}%mRz:VF}*

```

Try it online!

Sort of a port of @Datboi's answer

**Explanation**

```
{S*TN}:F                         -The padded string function
{                                -Start block
 S*                              -Multiply space string by argument and push to stack
   T                             -Push integer 0 to stack
    N                            -Push newline string to stack
     }                           -End block
      :F                         -Store top of stack(the block) in variable F
        ;                        -Pop from stack
         30:V                    -Push integer 30 to stack and store in variable V
             {3,{V1-+}%mRz:VF}   -The main loop
              3                  -Push integer 3 to stack
               ,                 -Array range from 0 to n-1
                {V1-+}%          -Map to array
                 V               -Push variable V to stack
                  1              -Push integer 1
                   -+            -subtract values from each other and add to array index
                       mR        -Random choice
                         z       -Absolute value
                          :V     -Store in variable V
                            F    - Execute function in F
                              *  -pop stack and repeat block

```
> 1 votes

# Answer
# Go, ~~123~~ ~~107~~ 94 bytes

```
import(."fmt"
."math/rand")
func s(){s:=30
for i:=0;i<30;i++{Printf(`%*d
`,s,4)
s+=Intn(3)-1}}

```

call function `s`

Try it online!
> 1 votes

# Answer
## Perl 6, 39 bytes

```
$_=30;say(" "x($_+=^3 .roll-1)~"x")xx$_

```

Explanation:

`$_=30`: Sets the number of spaces to prefix to 30.

`say(" "x($_+=^3 .roll-1)~"x")`: Outputs that number of spaces and updates it (`^3 .roll-1`: pick a random integer from 0 to 2 and subtract it by 1), followed by `x` and a newline.

`xx$_`: Does this 30 times. Using `$_` instead of `30` saves one space before `30`.
> 1 votes

# Answer
# Commodore BASIC (Tested on a Commodore 64, but recommended 128 80 columns mode) 72 tokenised BASIC bytes

```
0X=29:FORI=.TOX:PRINTSPC(X)"O":X%=3*RND(.):ONX%GOSUB1,2:NEXT:END
1X=X-1:RETURN
2X=X+1:RETURN

```

### How it works

`X` is declared as the spacing and is reused in the `FOR/NEXT` loop - the `.` is a slightly faster way of using `0` in Commodore BASIC, so the loop counts from `0` to the initialised value in `X` (30 iterations). `PRINT SPC(X)` will print `X` number of spaces, so on the first iteration, this is 29, and the `"O"` will print the `O` character. `X% = 3 * RND(.)` declares (loosely) an integer variable (the `%` means integer, though internally it's a floating point number) - a number from `0` to `2` inclusive is decided (as a floating point number, but will be used as an integer). the `ON X% GOSUB 1, 2` will branch to lines `1` or `2` depending on the value. a `0` will not branch and fall through to the next instruction (which instigates the next iteration with the `NEXT` command). Finally the `END` will gracefully end the program (otherwise it will continue to line `1` and there will be an error because of a `RETRURN` statement without a `GOSUB` call).

Note that although `X` is manipulated in the loop, the number of iterations is set by the value that it's initialised to. Also, the Commodore C64 screen (as well as the PET, C128 and C16/+4) only has 25 rows of text in BASIC, so that's why you don't see the full 30 character PETSCII Snake.
> 1 votes

# Answer
# \>\<\>, 53 bytes

```
 "+ ␞␞"r4[r}:}>1-$:\
<~x<1 }-1}o:}+^?:$o/oa;!?:{
^ \-

```

(Replace  with the corresponding byte 0x1E; it is replaced with a printable unicode character here for clarity.)

Try it online! The first `+` always starts at position 30.

## Explanation

### Initialization and Iteration Cleanup

```
 "+ ␞␞"r4[r}:}

```

Let's examine this section bit-by-bit, as it's a bit more complicated than a simple stack initialization.

```
 "+ ␞␞"

```

This initializes the stack with `[43, 32, 30, 30]`, which are the `[OutputChar, PadChar, InitialPosition, IterationCount]` respectively.

```
       r4[r

```

This is a no-op on the first iteration, but on each next iteration, it only retrieves the bottom-most four entries on the stack. Our method of repeating the iteration here is to simply return to the first line, which will re-push the initial string. We want to ignore this on every subsequent iteration, hence these four characters. (While I could remove them and simply jump to the corresponding position on line 1, this should require more bytes, given the rather delecate structure of the code.)

```
           }:}

```

The last thing that needs to be done before our output loop is to move the iteration count to the bottom of the stack (`}`), and save a copy of the current horizontal position to the bottom of the stack (`:}`).

### Horizontal Position Output

```
              >1-$:\
              ^?:$o/

```

This is a relatively simple loop. We first subtract 1 from the horizontal position (`1-`), output a copy of our padding character (`$:o$`, which is split across the mirrors to save bytes), and, if the counter has reached zero, we skip repeating this loop; otherwise, we repeat this process (`:?`).

### Post-loop procedures

```
  +                \
<~x<1 }-1}o:}+     /oa;!?:{
^ \-

```

I've kept in only the bits necessary to illustrate the function of the more delicate part of the code. Starting at the `+` in the middle, going left, we do a few things. We discard the 0 counter we do not need anymore (`+`), output a copy of the snake character (`}:o`), subtract 1 from the copy of the iteration counter we saved earlier (`}1-`), and then we prepare to do the random procedure `}1`. This pushes a 1 to the stack, which we will randomly add, subtract, or ignore relative to the horizontal position we saved earlier.

```
  +
<~x<1
^ \-

```

Remember the `+` is part of the initialization string from earlier. The `x` instruction is \>\<\> source of randomness; it chooses a random direction and sets the IP to go that way. This means we have four options: left, right, up, and down. If it goes right, it simply encounters the `<` instruction and we are redirected back to the `x`, once again obtaining a random direction. Effectively, we limit the random directions to be only left, up, or down.

If we go left, we'll simply pop the 1; the horizontal position does not change. We then continue left and wrap around to the rest of the post-loop procedures.

If we go up, we encounter the `+` from earlier, adding 1 to the horizontal position. We will then continue up and wrap around to the mirror, reflecting left, then following the arrows to the rest of the post-loop procedures.

If we go down, we find that same mirror, but reflect right instead, encountering the `-`, and subtracting 1 from the horizontal position. We continue and wrap around to the right, following the arrows as before and continuing on.

```
                   \
                   /oa;!?:{

```

After modifying the horizontal position, we now want to examine the loop counter (`{`). If it is 0, we terminate (`:?!;`). Otherwise, we continue on, outputting a newline (`ao`), hitting the mirror from before, going down, wrapping around, hitting the other mirror, and going to the left. This brings us back to the very start of the code, and the process begins again.
> 1 votes

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