# Question
Title: Code Golf: Your own horizontal pet ASCII snake
Very heavily inspired by this challenge Code Golf: Your own pet ASCII snake \- I thought making it horizontal would add an extra layer of complexity.

An example horizontal snake:

```
            0 0
  0        0 0 000
00 0     00       000 0      0
    000 0            0 0   00
       0                000

```

And the rules are:

1. Exactly 5 lines of characters are printed
2. Each line is exactly 30 characters long, consisting of a combination of spaces and the character you choose to draw your snake with
3. Your snake starts on line 3
4. The next line to be used for drawing your snake must be randomly chosen from your current line, one line above (if you're not already on line 1) or one line below (if you're not already on line 5).
    * These choices must be equally weighted. So if you are on line 1, you have a 50% chance to stay on line 1 and a 50% chance to move to line 2. If you are on line 2, you have a 33% chance to move to line 1, a 33% chance to stay on line 2 or a 33% chance to move to line 3
5. Your snake **does not** need to visit every single line.

# Answer
# JavaScript (ES6), 98 bytes

*Saved 7 bytes thanks to @KevinCruijssen*

Returns an array of 5 strings.

```
f=(y=2,a=[...'  0  '])=>a[0][29]?a:f(y+=(Math.random()*(y%4?3:2)|0)-!!y,a.map((v,i)=>v+=i-y&&' '))

```

Try it online!

### Commented

```
f = (                       // given:
  y = 2,                    //   y = current line (0-indexed)
  a = [...'  0  ']          //   a[] = array of 5 lines
) =>                        //
  a[0][29] ?                // if all columns have been processed:
    a                       //   stop recursion and return a[]
  :                         // else:
    f(                      //   do a recursive call with:
      y += (                //     the updated value of y, to which we add -1, 0 or 1:
        Math.random() *     //       pick a random value in [0,1)
        (y % 4 ?            //         if y is neither 0 or 4:
          3                 //             multiply it by 3
        :                   //           else:
          2                 //             multiply it by 2
        ) | 0               //       force an integer value
      ) - !!y,              //     subtract either 0 or 1
      a.map((v, i) =>       //     for each value v at position i in a[]:
        v += i - y && ' '   //       append either '0' if i = y or a space otherwise
      )                     //     end of map()
    )                       //   end of recursive call

```
> 11 votes

# Answer
# Charcoal, 28 bytes

```
Ｐ|   Ｆ³⁰«0≡ⅉ²Ｍ‽²↑±²Ｍ‽²↓Ｍ⊖‽³↓

```

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

```
Ｐ|

```

Print some padding to force 5 lines of output.

```
Ｆ³⁰«

```

Repeat 30 times.

```
0

```

Print a zero (and move horizontally).

```
≡ⅉ²Ｍ‽²↑

```

If the Y-coordinate is 2, move up randomly by 0 or 1.

```
±²Ｍ‽²↓

```

If it's -2, move down randomly by 0 or 1.

```
Ｍ⊖‽³↓

```

Otherwise move down randomly by -1, 0 or 1.
> 7 votes

# Answer
# Perl, 68 bytes

```
perl -E '$%=2;s:$:$n++%5-$%&&$":emg,$%-=!!$%+rand!($%%4)-3for($_=$/x4)x30;say'

```

This doesn't feel optimal at all.
> 6 votes

# Answer
# , 138 bytes

```
m=matrix(" ",30,5)
m[1,3]=0
x=3
s=sample
for(i in 2:30)m[i,x<-x+(-1)^(x==5)*s(0:1,1)*x%in%c(1,5)+(s(3,1)-2)*x%in%2:4]=0
write(m,"",30,,"")

```

Try it online!

Handily outgolfed by plannapus
> 5 votes

# Answer
# Python 3, 144 bytes

*@Ruts, @Turksarama, and @mypetlion have been very helpful in reducing bytes*

```
import random
m=[list(' '*30)for y in range(5)]
l=2
for i in range(1,30):
 m[l][i]=0
 l+=random.randint(~-(l<1),l<4)
for j in m:
  print(*j)

```

Will try and improve on this. Fun challenge!
> 5 votes

# Answer
# Jelly, 24 bytes

```
3µ’o1r‘«5¥$Xµ30Ð¡Ṭ€o⁶z⁶Y

```

Try it online!

## Explanation

```
3µ’o1r‘«5¥$Xµ30Ð¡Ṭ€o⁶z⁶Y || Niladic full program.
                         ||
3                        || Starting from 3...
 µ          µ30          || ... Execute 30 times...
               Ð¡        || ... And collect the results in a list.
  ’o1r‘«5¥$X             ||--| Monadic "Helper" function.
  ’o1                    ||--| The current integer, decremented OR 1.
     r     X             ||--| Grab a random item from the range from ^ to...
      ‘«5                ||--| ... The number incremented, capped to 5 (uses maximum).
         ¥$              ||--| Syntax elements. Used for grouping links.
                 Ṭ€      || Untruth each.
                   o⁶    || Logical OR with a single space.
                     z⁶  || Transpose with filler spaces.
                       Y || Join by newlines.

```
> 5 votes

# Answer
# , ~~120~~ 114 bytes

```
m=matrix
r=m(" ",30,5)
x=3
for(i in 1:30){r[i,x]=0;x=x+sample(-1:1,1,,m(c(0,rep(1,13)),3)[,x])}
write(r,"",30,,"")

```

Thanks to @Giuseppe for the additional 6 bytes!

Uses a table of probabilities as follows:

```
> matrix(c(0,rep(1,13)),3)
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    1    1    1    1
[2,]    1    1    1    1    1
[3,]    1    1    1    1    0
Warning message:
In m(c(0, rep(1, 13)), 3) :
  data length [14] is not a sub-multiple or multiple of the number of rows [3]

```

where each columns corresponds to a case, i. e. column 1 is picked if the snake is in row 1, giving probabilities 0, 1/2 and 1/2 to pick respectively -1 \[go down\], 0 \[stay still\] and 1 \[go up\] (`sample` automatically normalize the probabilities to 1), column 2 for row 2 gives probabilities 1/3, 1/3 and 1/3, etc...

Try it online!
> 4 votes

# Answer
# SOGL V0.12, ~~22~~ 21 bytes

```
3ā'∑∫⁵╗ž⁴H1ΧGI5χ⁴-ψ+;

```

Try it Here!

Explanation:

```
3                      push 3
 ā                     push an empty array - the canvas
  '∑∫                  30 times do, pushing counter            | stack = 3, [], 1
     ⁵                   duplicate the Y coordinate            | stack = 3, [], 1, 3
      ╗ž                 at those coordinates insert "+"       | stack = 3, ["","","+"]
        ⁴                duplicate from below                  | stack = 3, ["","","+"], 3
         H               decrease                              | stack = 3, [...], 2
          1Χ             maximum of that and 1                 | stack = 3, [...], 2
            G            get the item 3rd from top             | stack = [...], 2, 3
             I           increase it                           | stack = [...], 2, 4
              5χ         minimum of that and 5                 | stack = [...], 2, 4
                ⁴-       subtract from the larger a copy of the smaller value | stack = [...], 2, 2
                  ψ      random number from 0 to pop inclusive | stack = [...], 2, 2
                   +     add those                             | stack = [...], 4
                    ;    and get the array back ontop          | stack = 4, ["","","+"]

                         implicitly output the top item - the array, joined on newlines

```
> 3 votes

# Answer
# Japt, ~~31~~ 29 bytes

Returns an array of lines.

```
30ÆQùU±[2V=Jõ VVJò]mö i3 gUÃy

```

Test it
> 3 votes

# Answer
# Japt, 26 bytes

```
30ÆQùU=U?5õ f_aU <2Ãö :3Ãy

```

Test it online!
> 3 votes

# Answer
# SmileBASIC, ~~107~~ ~~105~~ ~~103~~ 89 bytes

```
FOR I=0TO 29FOR J=0TO 5LOCATE I,J?" 0"[Y+2==J]NEXT
Y=Y+RND(3)-1D=Y/3>>0Y=Y-D-D*RND(2)NEXT
NEXT

```

This answer is more interesting than the vertical one because of the (literal) edge cases.

## 64 bytes, without printing spaces:

```
FOR I=0TO 29LOCATE,Y+2?0;
Y=Y+RND(3)-1D=Y/3>>0Y=Y-D-D*RND(2)NEXT

```

I also found a few variations of line 2 with the same length:

```
Y=Y+RND(3)-1D=Y/3>>0Y=Y-D-D*RND(2)NEXT
Y=Y+RND(3)-1D%=Y/3Y=Y-D%-D%*RND(2)NEXT
Y=Y+RND(3)-1Y=Y-Y DIV 3*(RND(2)+1)NEXT
Y=Y+RND(3)-1Y=Y/3OR.Y=Y-D-D*RND(2)NEXT

```

The integer division of Y/3 is used to check if Y is outside the valid range, as well as getting the sign.
> 2 votes

# Answer
# Python 2, 127 bytes

```
from random import*
s=['']*5
n=3
r=range(5)
exec"for i in r:s[i]+=' 0'[i==n]\nn=choice(r[n and~-n:n+2])\n"*30
print'\n'.join(s)

```

Try it online!
> 2 votes

# Answer
# Octave with Statistics Package, 99 bytes

It also works in MATLAB with the Statistics Toolbox.

```
p=3;for k=1:29
p=[p;p(k)+fix(randsample(setdiff([1 pi 5],p(k)),1)-3)/2];end
disp(['' (p==1:5)'+32])

```

**Try it online!**
> 2 votes

# Answer
# Java 8, ~~177~~ 170 bytes

```
v->{int a[][]=new int[5][30],c=0,r=2;for(;c<30;r+=Math.random()*(r%4>0?3:2)-(r>0?1:0))a[r][c++]=1;String R="";for(int[]y:a){for(int x:y)R+=x<1?" ":"~";R+="\n";}return R;}

```

-7 bytes thanks to *@OlivierGrégoire*.

**Explanation:**

Try it online.

```
v->{                // Method with empty unused parameter and String return-type
  int a[][]=new int[5][30],
                    //  Integer-matrix of size 5x30
      c=0,          //  Column, starting at index 0
      r=2;          //  Row, starting at index 2
  for(;c<30;        //  Loop `c` 30 times
      r+=Math.random()*(r%4>0?3:2)-(r>0?1:0))
                    //    After every iteration: change `r` with -1,0,1 randomly
                    //     If `r` is 0: random [0;2)-0 → 0,1
                    //     If `r` is 4: random [0;2)-1 → -1,0
                    //     If `r` is 1,2,3: random [0:3)-1 → -1,0,1
    a[r][c++]=1;    //   Fill the cell at indices `r,c` from 0 to 1
  String R="";      //  Result-String, starting empty
  for(int[]y:a){    //  Loop over the rows of the matrix
    for(int x:y)    //   Inner loop over the individual column-cells of the matrix
      R+=x<1?       //    If the value of the cell is still 0:
          " "       //     Append a space
         :          //    Else (it's 1):
          "~";      //     Append the character
    R+="\n";}       //   After every row, Append a new-line
  return R;}        //  Return the result-String

```
> 2 votes

# Answer
# Japt, 28 bytes

*Saved 9 bytes thanks to ETHproductions*

```
3k
29Æp5õ f_aUgY)<2Ãö
¡QùXÃy

```

Try it online!
> 2 votes

# Answer
# C (gcc), 134 130 bytes

```
r,x,y=3,a[31],m;f(){for(x=0;x<31;x++){m?putchar(x==30?10:a[x]-m?32:48):(a[x]=y);r=rand();y+=y==1?r%2:y==5?-r%2:1-r%3;}++m<6&&f();}

```

Try it online!
> 2 votes

# Answer
# Perl, ~~83~~ 101 bytes

```
perl -E '$l=3;map{map$s[$_-1].=/$l/?0:" ",1..5;$l-=1-int 3*rand;$l=~y/60/51/}1..30;say for@s'

```

New: Without probability issue at the borders:

```
perl -E '$l=3;map{map$s[$_-1].=/$l/?0:" ",1..5;$l=int($l<2?1+2*rand:$l>4?6-2*rand:$l-1+3*rand)}1..30;say for@s'

```

Ungolfed:

```
$l=3;                             #start line
map{
  map $s[$_-1].=/$l/?0:" ",1..5;  #0 at current char and line, space elsewhere
  $l-=1-int 3*rand;               #up, down or stay
  $l=int( $l<2 ? 1+2*rand
        : $l>4 ? 6-2*rand
        :        $l-1+3*rand )    #border patrol
}
1..30;                            #position
say for@s                         #output result strings/lines in @s

```
> 1 votes

# Answer
# Scala, 207 Bytes

```
val b=Array.fill(150)('.')
def s(y:Int,x:Int)={val r=Random.nextInt(6)
val z=y+(if(y>3)-r%2
else if(y<1)r%2
else r/2-1)
b(z*30+x)='$'
z}
(3/:(0 to 28))(s(_,_))
b.mkString("").sliding(30,30).foreach(println)

```

sample:

```
...................$$$...$.$$.
.$$$..............$...$.$.$...
$...$$$..$...$$.$$.....$......
.......$$.$.$..$..............
...........$..................

```

degolfed:

```
val buf = List.fill(150)('.').toBuffer
def setRowCol (y:Int, x:Int): Int = {
  val r = Random.nextInt(6)
  val z = y + (
    if (y>3)
        -(r%2)
    else if (y<1)
        (r%2)
    else
        r/2-1
  )
  buf (z * 30 + x) = '$'
  z
}
(3 /: (0 to 28)(setRowCol (_, _))
println
buf.mkString ("").sliding(30,30).foreach(println)

```

My unique invention - well, I haven't read the other solutions so far, is, to generate a Random (6) which is implicitly two Randoms, (2\*3). If away from the border, I use the values of r/2 (0,1,2) and → (-1,0,1) tell me, to go up or down. If at the border, I can avoid the character costly call of another random, and just take the modulo(2), to decide, should I stay or should I go.

Let's see the other solutions. :)
> 1 votes

# Answer
# Ruby, ~~98~~ 77 bytes

```
->{a=(0..4).map{" "*30}
x=2
30.times{|i|a[x][i]=?@
x+=rand(3-17[x])-30[x]}
a}

```

Try it online!

A lambda returning an array of strings.

My initial impulse was to generate the columns and transpose them, but it's much easier to just avoid that step.

I would have liked to initialize `a` with `[" "*30]*5`, but that would make shallow copies of the strings, resulting in a very fat, non-slithery snake.

~~I could have used a constant like `D` as the increment (for the same byte count), but Ruby would have complained every time I assigned it. I decided I prefer decreasing readability by reusing `i` mid-loop to having a bunch of Debug warnings to ignore.~~

~~I also would have liked to save a few bytes with `loop{x+=rand(3)-1;(0..4)===x&&break}`, but that would have caused a bias on the edges: 1/3 chance to turn back inward, 1/3 chance to stay, and 1/3 chance to go out of bounds for a while before eventually random-walking back in (that is, "stay").~~

*-20 bytes:* Use Ruby's `Integer#[]` to create tiny conditionals, ensuring correct movement weightings for all 5 positions. This replaces a loop-break pattern (with a nonzero chance of failing to halt) for a huge savings. *Thanks, Eric Duminil!*

-1 byte: Initialize `a` with `(0..4).map` instead of `5.times`, thanks again to Eric Duminil.

```
->{
  a = (0..4).map{ " " * 30 }      # a is the return array: 5 strings of 30 spaces
  x = 2                           # x is the snake position
  30.times{ |i|                   # For i from 0 to 29
    a[x][i] = ?@                  #   The ith position of the xth row is modified
    x += rand(3 - 17[x]) - 30[x]  #   Using bit logic, add rand(2 or 3) - (0 or 1)
  }
  a                               # Return the array of strings
}

```
> 1 votes

# Answer
# Python 3, 123 bytes

```
from random import*
i,*a=2,
exec("a+=i,;i+=randint(-(i>0),i<4);"*30)
for x in range(5):print(''.join(' 0'[x==i]for i in a))

```

Try it online!

Generate an array of integers, then convert it to each row.

# Python 2, 120 bytes

```
from random import*
i=2;a=[]
exec"a+=i,;i+=randint(-(i>0),i<4);"*30
for x in range(5):print''.join(' 0'[x==i]for i in a)

```

Try it online!

For Py2, redundant parens for `exec` and `print` can be removed, but the syntax in the 2nd line is invalid.

Outgolfing both Py2 submission by Rod and Py3 submission by linemade.
> 1 votes

# Answer
# Perl 6, 85 bytes

```
.join.say for [Z] ((' ',' ',0,' ',' '),{.rotate(set(0,+?.[0],-?.[4]).pick)}...*)[^30]

```

Try it online!

The long parenthesized expression is a lazy sequence generated from the initial element `(' ', ' ', 0, ' ', ' ')`, the first vertical strip of the output. Each successive strip/list is generated from the preceding one by calling its `rotate` method, with the offset randomly chosen from a set containing `0`, `1` (if the first element is nonzero), and `-1` (if the fifth element is nonzero).

The matrix of horizontal strips is transposed with the `[Z]` operator, turning it into a list of vertical strips, each of which is then `join`ed into a single string and output with `say`.
> 1 votes

# Answer
# PowerShell, 133 bytes

```
$a=(,' '*30),(,' '*30),(,' '*30),(,' '*30),(,' '*30);$l=2;0..29|%{$a[$l][$_]=0;$l+=0,(1,($x=1,-1),$x,$x,-1)[$l]|Random};$a|%{-join$_}

```

Try it online!

Constructs a 2D array of 30 spaces wide by 5 lines tall. *(NB - if someone can come up with a better effective way to initialize this array, I'll \<3 you forever.)* Sets helper variable `$l` to `2` (this is used for what line the previous snake segment was on). Then loops from `0` to `29`.

Each iteration, we set our snake element to `0`. Then we index into a complicated array with `Get-Random` that selects out whether we go up or down or stay the same. That's added back into `$l`.

Finally, we loop through the five elements of `$a` and `-join` their inner elements into a single string each. Those five strings are left on the pipeline, and the implicit `Write-Output` gives us newlines for free.
> 0 votes

# Answer
# Clojure, 123 bytes

Here come the parens:

```
(let[l(take 30(iterate #(max(min(+(-(rand-int 3)1)%)4)0)3))](doseq[y(range 5)](doseq[x l](print(if(= y x)0" ")))(println)))

```

Ungolfed version:

```
(let [l (take
       30
       (iterate
        #(max
          (min
           (+ (- (rand-int 3) 1) %)
           4)
          0)
        3))]
(doseq [y (range 5)]
  (doseq [x l]
    (print (if (= y x) 0 " ")))
  (println)))

```

Builds a list of the different heights of the snake body, then iterates from 0 to 4. Whenever a height matches the current row it prints a 0, otherwise a blank. Not letting the heights exceed the boundary really costs bytes. Also recognizing when a new line is in order is more byte-intensive as it should be. One could easily write a single `doseq`, making a cartesian product of the x's and y's but then one does not know when to print a new line.
> 0 votes

# Answer
# Python3 +numpy, ~~137~~ 132 bytes

Not the shortest python submission, not the longest, and definitely not the fastest.

```
from pylab import*
j=r_[2,:29]
while any(abs(diff(j))>1):j[1:]=randint(0,5,29)
for i in r_[:5]:print(''.join(' #'[c] for c in j==i))

```

**update** Using `numpy`'s diff command saved 5 bytes for testing if the snake is a valid pattern, compared to calculating the difference manually with `j[1:]-j[:-1]`.
> 0 votes

# Answer
# C (gcc), 80 76 72 71 bytes

```
a[5][30],i,r;f(){for(r=2;i<30;r+=rand()%3-1)a[r=r>4?4:r<0?0:r][i++]=1;}

```

Try it online!
> 0 votes

# Answer
# , 95 bytes

```
x=3;l=1:5
write(t(replicate(30,{y=ifelse(x-l,' ',0);x<<-sample(l[abs(x-l)<2],1);y})),'',30,,'')

```

Next line `x` is always chosen from lines that are no more than 1 away from current line (`l[abs(x-l)<2]`). Using `replicate` instead of a `for` cycle saves some bytes needed for matrix initialization and manipulation and requires the use of the `<<-` operator when assigning to the global variable `x`.

Try it online!
> 0 votes

# Answer
# 05AB1E, 25 bytes

```
Y30F©ð5×0®ǝs<DÌŸ4ÝÃΩ}\)ζ»

```

Try it online!

**Explanation**

```
Y                           # push the initial value 2
 30F                        # 30 times do
    ©                       # store a copy of the current value in register
     ð5×                    # push 5 spaces: "     "
        0®ǝ                 # insert 0 at the position of the current value
           s<DÌŸ            # push the range [current-1 ... current-1+2]
                4ÝÃ         # keep only numbers in [0 ... 4]
                    Ω       # pick one at random
                     }\     # end loop and discard the final value
                       )ζ   # transpose the list
                         »  # join by newlines

```
> 0 votes

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


title: Print me a scale

text:
# Question
Title: Print me a scale
Oh no! I have a theory test soon and I don't remember the scales yet! Help me remember my major scales by printing the following:

```
7♯ - C♯ D♯ E♯ F♯ G♯ A♯ B♯ C♯
6♯ - F♯ G♯ A♯ B  C♯ D♯ E♯ F♯
5♯ - B  C♯ D♯ E  F♯ G♯ A♯ B
4♯ - E  F♯ G♯ A  B  C♯ D♯ E
3♯ - A  B  C♯ D  E  F♯ G♯ A
2♯ - D  E  F♯ G  A  B  C♯ D
1♯ - G  A  B  C  D  E  F♯ G
0  - C  D  E  F  G  A  B  C
1♭ - F  G  A  B♭ C  D  E  F
2♭ - B♭ C  D  E♭ F  G  A  B♭
3♭ - E♭ F  G  A♭ B♭ C  D  E♭
4♭ - A♭ B♭ C  D♭ E♭ F  G  A♭
5♭ - D♭ E♭ F  G♭ A♭ B♭ C  D♭
6♭ - G♭ A♭ B♭ C♭ D♭ E♭ F  G♭
7♭ - C♭ D♭ E♭ F♭ G♭ A♭ B♭ C♭

```

This is code-golf, so shortest code wins. You may use `#` and `b` symbols instead of  and  respectively.

Edit: If you are using  and  signs, you only have to count them as a single byte each. This is to not give an unfair disadvantage.

# Answer
> 8 votes
# Charcoal, ~~66~~ 65 bytes (if using # and b)

```
↑⮌…0¦8‖Ｏ⸿×⁷♭Ｍ→×⁷♯→⸿⸿¹⁵ＦＥ⁸﹪⊕⊗ι⁷«⸿⸿✂×³FCGDAEBι⁺¹⁵ι→⸿✂⭆♭ ♯×⁷κι⁺¹⁵ι»⟲

```

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

```
↑⮌…0¦8‖Ｏ

```

Print the characters `0` to `7` reversed, then reflect with overlap. Lists normally print downwards, so printing upwards actually prints rightwards; we'll rotate everything into place at the end.

```
⸿×⁷♭Ｍ→×⁷♯

```

Start a new line and print 7 flats and 7 sharps with a gap in between.

```
→⸿⸿¹⁵

```

Leave a blank line and print 15 `-`s.

```
ＦＥ⁸﹪⊕⊗ι⁷«

```

Take the numbers 0 to 7, double them, add 1, then reduce modulo 7. Loop over the result.

```
⸿⸿✂×³FCGDAEBι⁺¹⁵ι

```

Leave a blank line and then take a 15-character slice of the triplicated string of notes starting at the current value.

```
→⸿✂⭆♭ ♯×⁷κι⁺¹⁵ι

```

On the next line take a 15-character slice of flats, spaces and sharps, each repeated 7 times.

```
»⟲

```

After printing all the notes, rotate everything into place.

# Answer
> 6 votes
# Python 3, 135 bytes

*counting ♯ and ♭ as 1 byte each*

thanks to Zacharý for -6 bytes.

```
for i in range(15):k=' ♯♭'[(i<7)-(i>7)]+' -';print(str(i-7)[-1]+k,*[v+k[a+8>i>a]for a,v in zip([1,3,5,0,2,4,6,1],('CDEFGAB'*8)[i*3:])])

```

Try it online!

# Answer
> 6 votes
# Ruby, 113 bytes (~~131 126 108~~ 105 with # and b)

```
-7.upto(7){|i|print i.abs," ♭♯"[i<=>0]," - ",(4..11).map{|j|("FCGDAEB"*3)[k=j*2%7-i]+"♭♯ "[~k/7]}*" ",$/}

```

Try it online!

# Ruby, 116 bytes (108 with # and b)

Try it online!

# Ruby, 126 bytes (118 with # and b)

Try it online!

# Ruby, 131 bytes with # and b

Try it online!

# Answer
> 5 votes
# GNU sed, ~~148~~ 144 + 1 = 145 bytes

+1 byte for `-r` flag.

```
s/^/ 7# - C# D# E# F# G# A# B# \n65432101234567/
:
s/((.).(. - )((\S..){3})([^-]+)..\n)([0-7])/\1\2\7\3\6\2 \4\n/
s/ 0#/b0b/
t
s/^.//gm
s/0b/0 /

```

Try it online!

## Explanation

First, insert a template of sorts:

```
 7# - C# D# E# F# G# A# B#
65432101234567

```

Note the leading and trailing space on the first line.

In a loop, take the first number from the last line and replace it with parts of the second-to-last line like so:

```
 7# - C# D# E# F# G# A# B#
│ └┬─┘└───┬───┘└───┬────┘
2  3      4        6
│  │      └────────│──┐
├──│────────────┐  │  │
│  │      ┌─────│──┘  │
│ ┌┴─┐┌───┴────┐│ ┌───┴───┐
 6# - F# G# A# B  C# D# E#

```

As you can see, the initial space (capture 2) is used to replace the character after the `B`.

When the `0` is reached, replace the initial space with `b`. The loop continues, but instead of replacing `#`s with spaces, on each subsequent line a space is replaced with a `b`.

Finally, do a little cleanup: Remove the leading character from each line and replace `0b` with `0`.

# Answer
> 4 votes
# Befunge, ~~134~~ ~~132~~ 130 bytes

```
<v:,,," - ",g2+!!\`0::,+*86*-1*2`0::p00:<75
@>4*65*+81v>55+,$$\:00g0`!\9p3+7%\1-:8+#^_
 b#"A"%7:\_^#:-1,*84,g2*+1`0g00!!g9%7:\+1,+

```

Try it online!

**Explanation**

* We begin with an outer loop counting down from 7 to -7. We'll call this the *row* number.
* For each row, we start by writing out `'0'+abs(row)` (the scale number), and then calculate `(row>0)+(row!=0)` to lookup whether it's natural, sharp, or flat in the table  `#b` (you'll see this at the start of the third line of code).
* We then calculate the scale's start note, *n*, as `30 + row*4`. This will ultimately be mod 7, so think of it as the repeating sequence 2,5,1,4,0,3,6 (i.e. CFBEADG).
* Our inner loop, *i*, then counts down from 8 to 1, for the eight notes in the scale, incrementing *n* on each iteration.
* The letter of the note is simply `'A' + n%7`. Whether it is sharp or flat is determined by looking up `i%7` in a table. The table is initially all true, since the first scale is all sharps.
* After each row is output, though, we update the table by toggling one value. On the first iteration we'll toggle the value at offset 5, but each loop the offset is adjusted by `(offset+3)%7`.
* On the first half of the output, when the *row* is greater than zero, we're toggling these table values to false. On the second half of the output, when the *row* is less than or equal to zero, we're setting them back to true.

# Answer
> 3 votes
# Bubblegum, 107 bytes

Bubblegum threshold

```
00000000: 4dca a90d 0301 1443 41ee 2a9e f4b1 a5ec  M......CA.*.....
00000010: 8d73 f7e1 fe8b 48a0 e968 aec1 3c87 d7f0  .s....H..h..<...
00000020: 1e3e c377 b80f 8ff9 a3ce c165 74d4 31b8  .>.w.......et.1.
00000030: 8c8a da07 1751 4fdb e022 ea69 1d5c 443d  .....QO..".i.\D=
00000040: 2d83 8ba8 a71b b888 7a5a 828b 524f 6b70  -.......zZ..ROkp
00000050: 51fa 690b 2e4b 47ed c165 e9a8 23b8 2c1d  Q.i..KG..e..#.,.
00000060: 7506 97a5 a3ae e0b2 74d4 0f              u.......t..

```

Try it online!

# Answer
> 3 votes
# C,  ~~212~~   ~~189~~   ~~186~~  185 bytes

*Thanks to @Jonathan Frech for saving a byte!*

```
#define N n>0?35:98:32);
f(i,n){for(n=8;--n+8;puts(""))for(i=-1,printf("%d%c -",abs(n),n?N++i<8;)printf(" %c%c",(n*4+65+i)%7+65,"\377\277\273\233\231\211\10\0@Ddfv\367\377"[n+7]&1<<i?N}

```

Try it online!

**Unrolled:**

```
#define N n>0 ? 35 : 98 : 32);
f(i, n)
{
    for (n=8; --n+8; puts(""))
        for (i=-1, printf("%d%c -", abs(n), n?N ++i<8;)
            printf(" %c%c",
                (n*4+65+i)%7 + 65,
                "\377\277\273\233\231\211\10\0@Ddfv\367\377"[n+7] & 1<<i ? N
}

```

# Answer
> 3 votes
# JavaScript (ES6), ~~130~~ 124 bytes

Or ~~128~~ **121 bytes** with a leading newline.

```
f=(y=14,x=8)=>x?f(y,x-1)+' '+'BCDEFGA'[(y*3+x)%7]+'# b'[(x*5%7+y)/7|0]:(y?f(y-1)+`
`:'')+`${y<7?7-y+'#':y>7?y-7+'b':'0 '} -`

O.innerText = f()
```

```
<pre id=O style="font-size:11px"></pre>
```

# Answer
> 2 votes
# Jelly,  ~~57 56 55~~  54 bytes

-1 byte thanks to EriktheOutgolfer (use `7ŒR` to replace `-7r7`)

```
_Ṃị“ b#”
=”B+\Çż
×3⁵+€ịØAḣ7¤ḊḊÇ€Z
7ŒRµṠÑżAW€żÇj€”-UK€Y

```

A full program printing the desired output (using `#`, `b`).

**Try it online!**

### How?

```
_Ṃị“ b#” - Link 1, getSharpsFlatsOrSpaces: list of integers
 Ṃ       - minimum (of the input list)
_        - subtract (from the input list) -- for our purposes this resets whatever our
         -       1st value is to 0, since our inputs are always monotonically increasing
   “ b#” - literal list of characters = [' ', 'b', '#']
  ị      - index into (1-based and modular)

=”B+\Çż - Link 2, addSharpsFlatsOrSpaces: list of characters  e.g."CFBEADGCFBEADGC"
 ”B     - literal character 'B'
=       - equals? (vectorises)                      [0,0,1,0,0,0,0,0,0,1,0,0,0,0,0]
    \   - cumulative reduce with:
   +    -   addition                                [0,0,1,1,1,1,1,1,1,2,2,2,2,2,2]
     Ç  - call the last link (1) as a monad                       "##       bbbbbb"
      ż - zip (with input) ["#C","#F"," B"," E",...," F","bB","bE","bA","bD","bG","bC"]

×3⁵+€ịØAḣ7¤ḊḊÇ€Z - link 3, getNoteLetters: list of integers          e.g. [-7,-6,...,6,7]
×3               - multiply by three       [-21,-18,-15,-12,-9,-6,-3,0,3,6,9,12,15,18,21]
  ⁵              - literal ten                                                         10
   +€            - add for €ach (in [1,10])   [[-20,...,22],[-19,...,23],...,[-11,...31]]
          ¤      - nilad followed by link(s) as a nilad:
      ØA         -   yield uppercase alphabet                "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        ḣ7       -   head to index seven                                        "ABCDEFG"
     ị           - index into ["ADGCFBEADGCFBEA","BEADGCFBEADGCFB","CFBEADGCFBEADGC",...]
           Ḋ     - dequeue    ["BEADGCFBEADGCFB","CFBEADGCFBEADGC","DGCFBEADGCFBEAD",...]
            Ḋ    - dequeue    ["CFBEADGCFBEADGC","DGCFBEADGCFBEAD","EADGCFBEADGCFBE",...]
             Ç€  - call the last link(2) as a monad for €ach
                 -    [[["#C","#F"," B"," E",...," F","bB","bE","bA","bD","bG","bC"],...]
               Z - transpose           [["#C","#D",...,"#C"],["#F",..." B",...,"#F"],...]

7ŒRµṠÑżAW€żÇj€”-UK€Y - Main link: no arguments
7ŒR                  - absolute range of seven     [-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7]
   µ                 - start a new monadic chain (call that r)
    Ṡ                - sign (of r)                 [-1,-1,-1,-1,-1,-1,-1,0,1,1,1,1,1,1,1]
     Ñ               - call the next link (1) as a monad                "####### bbbbbbb"
       A             - absolute value (of r)              [7,6,5,4,3,2,1,0,1,2,3,4,5,6,7]
      ż              - zip                      [[7,'#'],[6,'#'],...,[0,' '],...,[7,'b']]
        W€           - wrap €ach        [[[7,'#']],[[6,'#']],...,[[0,' ']],...,[[7,'b']]]
           Ç         - call the last link (3) as a monad (with r)      see link 3 example
          ż          - zip                     [[[['#',7]],["#C","#D",...,"#C"]],
                                                [[['#',6]],["#F",...," B",..."#F"]], ...]
              ”-     - literal character '-'
            j€       - join for €ach            [[['#',7],'-',"#C","#D",..."#C"],
                                                 [['#',6],'-',"#F",...," B",..."#F"],...]
                U    - upend (reverse each)     [[[7,'#'],'-',"C#","D#",..."C#"],
                                                 [[6,'#'],'-',"F#",...,"B ",..."F#"],...]
                 K€  - join €ach with spaces            [[7+"# - C# D# ... C#"],
                                                         [6+"# - F# ... B  ... F#"], ...]
                   Y - join with newlines
                     - implicit print to STDOUT

```

# Answer
> 0 votes
# CJam, ~~109~~ ~~106~~ 94 bytes

```
{_0={_z/}|" b#"=a}:A;15,{X7-_zs\A+" - "+o7,0+{YX+7%65+c"2461357"Y=aiX\-_7,#){;0}&AS++o}fYNo}fX

```

Try it online

# Answer
> 0 votes
# Java 8, 255 bytes

*Counting ♯ and ♭ as 1 byte each.*

```
v->{String r="",t="GABCDEF";for(int i=-8;++i<8;r+="\n"){r+=(i<0?-i+"♯":i>0?i+"♭":"0 ")+" - ";for(String c:((t=t.substring(3)+t.substring(0,3))+t.charAt(0)).split(""))r+=c+("BEADGCF".substring(i<0?7+i:i).contains(c)?i<0?"♯":" ":i>0?"♭":" ")+" ";}return r;}

```

**Explanation:**

Try it online.

```
v->{                   // Method with empty unused parameter and String return-type
  String r="",         //  Result-String, starting empty
         t="GABCDEF";  //  Temp-String `t`, starting at "GABCDEF"
  for(int i=-8;++i<8;  //  Loop from -7 to 7 (inclusive); range (-8;8) == [-7;7]
      r+="\n"){        //    After every iteration: append the result with a new-line
    r+=                //   Append the result-String with:
       (i<0?           //    If `i` is negative:
         -i+"♯"        //     Append the absolute value of `i` + a literal "♯"
        :i>0?          //    Else-if `i` is positive:
         i+"♭"         //     Append `i` + a literal "♭"
        :              //    Else (`i` is 0):
         "0 ")         //     Append a literal "0" + space
     +" - ";           //   And then append a literal " - "
  for(String c:((t=t.substring(3)+t.substring(0,3))
                       //  Split String `t` in the middle,
                       //  and swap the two parts (i.e. "GABCDEF" becomes "CDEFGAB")
                +t.charAt(0))
                       //  Then append the first character
                .split(""))
                       //  And loop over each character:
     r+=c+             //   Append the result-String with this character, plus:
          ("BEADGCF".substring(i<0?
                       //    If `i` is negative
            7+i        //     Take the last `-i` characters of "BEAFGCF"
           :           //    Else (`i` is 0 or positive)
            i)         //     Take the last `7-i` characters of "BEAFGCF"
          .contains(c)?//    And if these last characters contain the current character:
            i<0?       //     And `i` is negative:
             "♯"       //      Append a literal "♯"
            :          //     Else (`i` is 0 or positive)
             " "       //      Append a space
          :i>0?        //    Else-if `i` is positive
            "♭"        //     Append a literal "♭"
          :            //    Else:
           " ")        //     Append a space
      +" ";}           //   And then append a space
  return r;}           //  Return the result-String

```

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


title: JAxH obfuscated method, not text

text:
# Question
Title: JAxH obfuscated method, not text
A JAPH is a grand tradition of making a program that prints "Just another Perl hacker,". We already have a question about JAPH on this site but they seem more concerned with hiding the text, but JAPH has always been more about hiding the method by which it does what it does. Therefore I challenge you to show off your favorite language's cool features, and don't worry too much about hiding the text (unless you want to).

Here's mine, in Perl, which shouldn't be to hard for an experienced velociraptor to understand, but may be interesting for others.

```
(*STORE,*TIESCALAR)=map{eval"sub{$_}"}qw'map{print&&sleep$|}split//,pop bless\$|++';tie$t,main;$t="Just another Perl hacker,\n"

```

Judged subjectively on votes by you guys, lets see some mind-benders!

# Answer
# C

Must be compiled to 32bit. On 64bit machines use `gcc -m32` or such.

```
#include <stdlib.h>

int main() {
    char *c = "echo Just another C hacker";
    int foo=123; //unused                          /* Warning: there's a
    int k=(int)1                                    * (long) system
    //now for the fun part!                         * of chinese boxes
    //behold:                                       * in this code. */
    +0;
    -1;
    ((int(*)(char *))k)(c);
}

```

Disclaimer: not my idea. I found it years ago hidden in some piece of code. Seriously. Theirs was even better, I forgot several little details. But the gist is there.

When you see it, you'll sh\*t bricks.
> 30 votes

# Answer
# Mathematica:

```
TextRecognize@
 ImageAssemble@
  Transpose@
   ImagePartition[Import@"https://i.stack.imgur.com/S9fci.png", 5]

```
> 6 votes

# Answer
## Dart

```
class Print{
  var PrinT,print,prinT;
  get PRint() => PrinT;
  get pRInt() => 'A$prinT';
  get pRint() => print;
  set pRInt(PrinT){print=PrinT;}
  set prInt(pRInt){prinT='n$pRInt';}
  Print(prinT,PRINT){
    PrinT = prinT;
    prInt = PRINT;
  }
  PRINT(print,PrinT){
    pRint.PRint('$print ${pRint.pRInt} $PRint $PrinT');
  }
  Print.print(print,prinT){
    pRInt = new Print(print,'other');
    PrinT = prinT;
  }
}
main(){
  Print print = new Print.print(print,'Dart');
  print.PRINT('Just','Hacker');
}

```

Edit : less boring setter, less boring getter.

I have studied this language for a day, so I think other people may think this as a child's mess... :(
> 6 votes

# Answer
## PRNG

It's in C, but it actually shows off that you can do cool things using PRNGs and outputs `Just another PRNG hacker`:

```
#include <stdio.h>

#define P 0x3A4B5C6D

char s[6];
int j, t;

void r(int d) {
  t = ((P * d + P) << 17) + ((P * d - P) >> 15) + P;
  for (j = 0; j < 5; j++) {
    s[j] = (t % 51) + 67;
    t /= 51;
    if ((s[j] >= 91) && (s[j] <= 96)) s[j] = 32;
  }
  printf("%s", s);
}

int main() {
  r(0x444C725);
  r(0x2D65DD4B);
  r(0x6C5C71A);
  r(0xB2A4BBD);
  r(0x275BD6F);
  return 0;
}

```

Using the built-in PRNG (srand, rand) would be possible, too, but less portable.
> 6 votes

# Answer
# C

```
int main(int _)
{
    putchar(~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
    putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~
    putchar(~-~-~-~-~-~-
    putchar(-~-~-~-~-~-~-~-~
    putchar(-~-~
    putchar(~-~-~-~-~-~-~-
    putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
    putchar(~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
    putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
    putchar(~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
    putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~
    putchar(~-~-~-
    putchar(~-~-~-~-~-~-~-~-~-~-~-~-
    putchar(-~-~-~-~-~
    putchar(-~
    putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~
    putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
    putchar(~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
    putchar(-~
    putchar(~-~-
    putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
    putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~_
    ))))))))))))))))))))));
}

```
> 5 votes

# Answer
# Python

```
credits.__class__(0,'Just another Python hacker')()

```
> 4 votes

# Answer
## Javascript

```
eval('Acy419yt=12-14;'.split('').map(function(x){return String.fromCharCode(
0240-x.charCodeAt(0))}).join(''))[_]((___='splitulengthureverseujoinufilter'
.split('\x75'),function __(_){return _[___[1]]?__(_[___[0][0]+___[___[3]](''
)[___[0]]('')[___[4]](function(_,__){return ~~(__/2)==1})[___[3]]('')+'ce'](
1))+_[0]:_}("Just Another JavaScript Hacker"))[___[0]]('')[___[2]]()[___[3]](''));

```

In my code, JAJSH text was encrypted by reversing it, not only once, but twice!! Ha! Can you find it?
> 3 votes

# Answer
# QBasic

Here's my implementation in QBasic. The program must be called "JAQBH.BAS" in or for this to execute properly, as it reads its own source as part of the program. And I couldn't find any sane way of determining the name of the currently running script.

```
COMMON SHARED JAQBH$
COMMON SHARED F$
IF F$ = "" THEN F$ = "A.BAS"
OPEN F$ FOR OUTPUT AS #1
PRINT #1, JAQBH$
DATA 20,16,28,24,16
DATA "Just Another QBasic Hacker"
OPEN "JAQBH.BAS" FOR INPUT AS #2
FOR i% = 1 TO 5
        READ l%
        y$ = INPUT$(l%, #2)
        PRINT #1, y$
        y$ = INPUT$(2, #2)
NEXT
CLOSE #1
CLOSE #2
F$ = "CON"
READ JAQBH$
CHAIN "A.BAS"

```
> 2 votes

# Answer
## Haskell

I did this one with some help.

```
{-# LANGUAGE ForeignFunctionInterface #-}

import Control.Applicative
import Control.Monad
import Foreign
import Foreign.C

foreign import ccall "stdio.h puts"
    puts :: CString -> IO ()

main :: IO ()
main = liftM2 allocaBytes length
       ((<*> puts) . ((>>) .) . flip (flip zipWithM_ [0..] . pokeElemOff))
     $ map (fromIntegral . fromEnum) "Just another Haskell hacker\0"

```

And just for fun:

```
{-# LANGUAGE ForeignFunctionInterface #-}

import Control.Exception
import Control.Monad
import Data.Bits
import Data.Word
import Foreign
import Foreign.C

foreign import ccall "stdlib.h realloc"
    c_realloc :: Ptr a -> CSize -> IO (Ptr a)

foreign import ccall "stdlib.h free"
    c_free :: Ptr a -> IO ()

foreign import ccall "stdio.h puts"
    c_puts :: CString -> IO ()

-- | Write a UTF-8 character into a buffer.
--
-- Return the length of the character in bytes, which will be a number from 1-4.
pokeUtf8 :: Ptr Word8 -> Char -> IO Int
pokeUtf8 ptr char =
    case (fromIntegral . fromEnum) char :: Word32 of
        c | c <= 0x7F -> do
            put ptr c
            return 1
        c | c <= 0x7FF -> do
            put ptr                 (0xC0 .|. c `shiftR` 6)
            put (ptr `plusPtr` 1)   (0x80 .|. c .&. 0x3F)
            return 2
        c | c <= 0xFFFF ->
            if c >= 0xD800 && c <= 0xDFFF
                then replacement
                else do
                    put ptr                 (0xE0 .|. c `shiftR` 12)
                    put (ptr `plusPtr` 1)   (0x80 .|. c `shiftR` 6 .&. 0x3F)
                    put (ptr `plusPtr` 2)   (0x80 .|. c .&. 0x3F)
                    return 3
        c | c <= 0x10FFFF -> do
            put ptr                 (0xF0 .|. c `shiftR` 18)
            put (ptr `plusPtr` 1)   (0x80 .|. c `shiftR` 12 .&. 0x3F)
            put (ptr `plusPtr` 2)   (0x80 .|. c `shiftR` 6 .&. 0x3F)
            put (ptr `plusPtr` 3)   (0x80 .|. c .&. 0x3F)
            return 4
        _ -> replacement
    where
        put p c = poke p (fromIntegral c :: Word8)
        replacement = pokeUtf8 ptr '\xFFFD'

withUtf8 :: String -> (CStringLen -> IO a) -> IO a
withUtf8 string action = expand nullPtr 64 0 string where
    expand buf bufsize pos str = do
        buf' <- c_realloc buf (fromIntegral bufsize)
        when (buf' == nullPtr) $ do
            c_free buf
            ioError $ userError "Out of memory"
        write buf' bufsize pos str

    write buf bufsize pos str
        | bufsize - pos < 4 = expand buf (bufsize * 2) pos str
        | otherwise = do
            case str of
                (c:cs) -> do
                    len <- pokeUtf8 (buf `plusPtr` pos) c
                    write buf bufsize (pos + len) cs
                [] -> do
                    pokeByteOff buf pos (0 :: Word8)
                    finish buf pos

    finish buf len =
        finally (action (buf, len)) (c_free buf)

puts :: String -> IO ()
puts str = withUtf8 str (c_puts . fst)

main :: IO ()
main = puts "\x266B Just another C hacker using Haskell \x266B"

```
> 2 votes

# Answer
# JavaScript

Run in console

```
({}+[])[!''+!''+!![]] + (!![]+[])[!''+!''] + (![]+[])[!''+!''+!''] + (!![]+[])[+![]] + ({}+[])[!![]+!''+!''+!''+!''+!''+!''] + (![]+[])[+!![]] + ([][{}]+[])[+!![]] + ({}+[])[+!''] +
(!![]+[])[+![]] + 'h' + (![]+[])[!''+!''+!![]+!![]] + (!![]+[])[+!![]] + ({}+[])[!![]+!![]+!''+!''+!''+!''+!''] + ({}+[])[!![]+!''+!![]] + (![]+[])[!![]+!''+!![]] +
({}+[])[!![]+!![]+!![]+!![]+!''+!![]+!![]] + 'h' + (![]+[])[+!![]] + ({}+[])[!![]+!![]+!''+!![]+!![]] + 'k' + (![]+[])[!''+!![]+!![]+!''] + (!![]+[])[+!'']

```
> 2 votes

# Answer
# Python 2.x (single expression)

Now, while this is quite easy to figure out for Pythoneers, others might find it at least interesting. If you wonder why there's so many lambdas, I wanted to have maximum underscoreness, but minimal repetition. Who doesn't love underscores? Ideone

```
(lambda ______________:(lambda ______,_______,________:(lambda _____:(lambda _,___,__,____,_____________:(lambda _________,__________:(lambda ___________,____________:___________(____________,____[_________**(_________+__________)-__________::_________+_________+_________]+_[__________::_________]+__[_________+__________])(____________,______________))((lambda _,__:________(______(_))[__]),(________(__import__(_[_________]+__[_________*_________+__________]+_[_________]))[_[_________:_________+_________]+___[__________/_________]+__[__________]+_____(u'')[__________/_________]+_[_________+__________]])))((_____________(_)+_____________(_))/_____________(_),_____________(_)/_____________(_)))(_____([]),_____({}),_____(None),_____({}.__iter__),lambda _:len(_)))(lambda _:_______(______(_))))((lambda _:_.__class__),(lambda _:_.__name__),(lambda _:_.__dict__)))('Just another Python Hacker\n')

```

An indented version if you prefer:

```
(lambda ______________:
    (lambda ______,_______,________:
        (lambda _____:
            (lambda _,___,__,____,_____________:
                (lambda _________,__________:
                    (lambda ___________,____________:
                        ___________(____________,____[_________**(_________+__________)-__________::_________+_________+_________]+_[__________::_________]+__[_________+__________])(____________,______________)) (
                        (lambda _,__:________(______(_))[__]),
                        (________(__import__(_[_________]+__[_________*_________+__________]+_[_________]))[_[_________:_________+_________]+___[__________/_________]+__[__________]+_____(u'')[__________/_________]+_[_________+__________]]))) (
                    (_____________(_)+_____________(_))/_____________(_),
                    _____________(_)/_____________(_))) (
                _____([]),
                _____({}),
                _____(None),
                _____({}.__iter__),
                lambda _:len(_))) (
            lambda _:_______(______(_)))) (
        (lambda _:_.__class__),
        (lambda _:_.__name__),
        (lambda _:_.__dict__)))('Just another Python Hacker\n')

```

This defines a function and calls it with 'Just another Python Hacker'. Now, it didn't have to be a function, but I thought it would be more elegant.

```
f = (lambda ______________:(lambda ______,_______,________:(lambda _____:(lambda _,___,__,____,_____________:(lambda _________,__________:(lambda ___________,____________:___________(____________,____[_________**(_________+__________)-__________::_________+_________+_________]+_[__________::_________]+__[_________+__________])(____________,______________))((lambda _,__:________(______(_))[__]),(________(__import__(_[_________]+__[_________*_________+__________]+_[_________]))[_[_________:_________+_________]+___[__________/_________]+__[__________]+_____(u'')[__________/_________]+_[_________+__________]])))((_____________(_)+_____________(_))/_____________(_),_____________(_)/_____________(_)))(_____([]),_____({}),_____(None),_____({}.__iter__),lambda _:len(_)))(lambda _:_______(______(_))))((lambda _:_.__class__),(lambda _:_.__name__),(lambda _:_.__dict__)))
f('Hello.\n')
f('Just another Python Hacker here.\n')

```
> 2 votes

# Answer
# Python

My JAPH in Python

```
class Foo:
    def __init__(s, t='Just another Python hacker'):
        def g():
            return [100,101,102,32,102,
                    40,120,41,58,112,114,
                    105,110,116,32,120],t
        s.g = g()
        class Z():
            def __add__(s,x):return x
        s.z = sum((chr(i)for i in s.g[0]),Z())
    def __call__(s,t):
        return t.join(map(chr,s))
    def __iter__(s):
        return (ord(i) for i in `s`)
    def __repr__(s):
        return s.g[-1]
    def __getitem__(s, x):
        exec s.z
        f(s(x))
Foo()['']

```
> 1 votes

# Answer
# Haskell

Fun with monad transformers:

```
import Control.Monad.State
import Control.Monad.Writer

newtype A a = A (Maybe a)
newtype B = B { c :: String }

instance Show a => Show (A a) where
   show (A x) = show x

instance Show B where
   show = c

s = [97, 13, 1, 5, -12, -3, 13, -82, 40, 25, 18,
     -8, -6, 7, 0, -76, 72, -7, 2, 8, -6, 13]

main = print . A . fmap B . execWriterT . flip evalStateT 0 . mapM f $ s
  where f x = modify (+x) >> get >>= tell . return . toEnum

```
> 1 votes

# Answer
## Scala

```
val bi = BigInt ("467385418330892203511763656169505613527047619265237915231602")
bi.toByteArray.map (_.toChar).mkString

```
> 1 votes

# Answer
## Postscript.

Creates a custom font with which to display the text.

```
%!
100 200[>>begin
(Encoding{}FontType 3
 BuildChar{exch begin 10 0 setcharwidth load exec stroke end}
 FontMatrix .1 0 0 .1 0 0 FontBBox 0 0 10 10)
{token{exch}{exit}ifelse}loop
{4 6}{array astore def}forall
/c{1 string cvs 0 get}4{def}repeat
/J c{7 9 moveto 7 2 lineto 6 4 1 360 190 arcn}
/A c{2 2 moveto 5 8 lineto 8 2 lineto}
/P c{3 2 moveto 3 8 lineto 3 6 2 90 270 arcn}
/s c{5 7 2 0 270 arc 5 3 2 90 180 arcn}
/H c{2 2 moveto 2 8 lineto 8 8 moveto 8 2 lineto 2 4 moveto 8 4 lineto}5{def}repeat
/F currentdict end definefont 20 scalefont setfont
moveto(JAPsH)show

```
> 1 votes

# Answer
## Ruby

Had two ideas and ended up combining them.

```
def Object.const_missing(const)
  define_method(:method_missing) do |meth,*args|
    "#{meth}"['i'] ? ->a{not$*<<a.pop} :print(meth)
  end[const,$\=' ']
end

Begin

case %w[Just another ruby hacker]
when tick
  puts 'tock'
when tick
  puts 'tock'
when tick
  puts 'tock'
when tick
  puts 'tock'
else
  eval($**$\)
end

```
> 1 votes

# Answer
## Ruby 1.9

Cheesy, highly implementation-dependent, but I hope you find it spooky.

```
class Object
    define_method(:!) do |n=3|
        send(methods.find{|la|la[/[slappy]{#{n}}/]})
    end
end

(!!!:!).!(5) unless respond_to?('Just another ruby hacker,')

```

Edit: Proof
> 1 votes

# Answer
# JavaScript

```
eval (atob("ZnVuY3Rpb24gcHJpbnQoKSB7CmZ1bmN0aW9uIHRyKGEsYikgewogICAgcmV0dXJuIGEubWFwKGZ1bmN0aW9uKHgpewogICAgICAgIHJldHVybiB4LnRvU3RyaW5nKGIpOwogICAgfSkuam9pbignICcpOwp9CgoKdmFyIGEgPSJXemt5TmpNNE1Td3lNekl3TURJek1UYzNPU3d4TVRnMU5UTTNMREV3TkRVek1EYzBOelZkIjsKYSA9IGF0b2IoYSk7CmEgPSBKU09OLnBhcnNlKGEpOwphID0gdHIoYSwzNik7CmNvbnNvbGUubG9nKGEpOwp9"));
print();

```
> 0 votes

# Answer
# Perl on OSX 10.7+ (requires Xcode)

```
#!/usr/bin/perl
use Inline C=>q{int g(){atexit("j\31\350\31\0\0\0Just \
another Perl hacker\n1\300@\220\17\204\n\0\0\0j\1k\4\x\
cd\x80\203\304\20\303^j\1_Z\270\4\0\0\2\17\5\303");}};g

```
> 0 votes

# Answer
# Lua/RProgN

```
print "Just "           --                         Write Just to the Console--
print "Another "        --                      Write Another to the Console--
print "Lua "            --           Write Lua, definitely NOT  [ 'RProgN' ]--
print "Hacker "         -- Do u really thing u r an hacker like i [ ur NOT ]--

```

I'm sure there's a better and sneakier way to combine these two languages. Hiding in comments is just so overused.

Try the Lua Out

Try the RProgN Out
> 0 votes

# Answer
# Operation Flashpoint scripting language

```
removeAllWeapons player
s = primaryWeapon player
call = "scripting " else "language "

a = [if true, if false]
b = ["s=s+(call select 0)", format["s=s+(call select 1)%1%2=%3", {;}, "call", {nil}]]

a select 0 then b
a select 1 then b

a = a + getPos player + [{Just another} + format ([" %1 %2 "] + ("Operation" ELSE "Flashpoint"))]

"b = format[""%2%1%3."", s, _x, call""""""hacker""""""]" count a

titleText (b else "plain")

exit

```

Save as `ofp.sqs` (or any other name), and call with `[] exec "ofp.sqs"`.

**Output:**
> 0 votes

# Answer
# Canvas

```
³｛┤：js nte avshce＠；utaohrcna akr＠｝）∑╷

```

...which **should** work, but  on strings hasn't been implemented yet. <sup> Hooray for dead projects!</sup> The working version uses the same logic, but is a bit... less obfuscated.

Try it online! (working version)
> 0 votes

---
Tags: obfuscation, popularity-contest
---


title: Show me the nearest demon

text:
# Question
Title: Show me the nearest demon
A demonic number is a positive integer whose decimal representation consists of only 6. The list of demonic numbers starts with 6, 66, 666, 6666.

Given a positive integer, output the nearest demonic number. If there are two, output the bigger one.

Testcases:

```
n   output
1   6
2   6
3   6
6   6
35  6
36  66
37  66
100 66
365 66
366 666
666 666
999 666

```

This is . Shortest answer in bytes wins.

# Answer
# Python 2, 28 bytes

```
lambda n:'6'*len(`-~n*3/11`)

```
> 50 votes

# Answer
# JavaScript (ES6), ~~31~~ 29 bytes

```
f=(x,s='6')=>x<3+s?s:f(x,s+6)

```

```
f=(x,s='6')=>x<3+s?s:f(x,s+6)

;[1,2,3,6,35,36,37,100,365,366,666,999,1000].forEach(x=>console.log(x,f(x)))
```

“That is why, I delight in weaknesses \[…\] For when I am weak, then I am strong.”
> 14 votes

# Answer
# Brachylog, 8 bytes

```
;I≜+{6}ᵐ

```

Try it online!

### Explanation

```
;I          The list [Input, I]
  ≜         Assign a value to I: 0, then 1, then -1, then 2, etc.
   +        Sum Input with I
    {6}ᵐ    All its digits must be 6

```
> 8 votes

# Answer
# Java 7, ~~96~~ ~~93~~ 66 bytes

```
String c(int n){String r="";for(n*=11/3;n>1;r+=6,n/=10);return r;}

```

Port of *@orlp* amazing Python 2 answer.

Try it here.

I guess my **66**-byte-count is a demon as well. ;)
(Not the shortest Java answer btw, see *@JollyJoker*'s answer for that instead.
> 5 votes

# Answer
# Jelly, 9 bytes

```
Ẇa6ḌạÐṂ⁸Ṫ

```

A monadic link.

**Try it online!** \- Almost no point in this link (see below)!

### How?

In true golfer's style this is truly inefficient - it hits the 60s time out at TIO for the **365** test case! Locally this finishes in 37s.

```
Ẇa6ḌạÐṂ⁸Ṫ - Main link: n
Ẇ         - all sublists - this has an implicit make_range on it's input
          -   so, for example, an input of 3 yields [[1],[2],[3],[1,2],[2,3],[1,2,3]]
          -   the important things are: that it contains both a list of the length of the
          -   decimal number, and a list 1 shorter; and that it's lists only contain
          -   non-zero numbers and are monotonically increasing in length.
  6       - literal 6
 a        - and (vectorises), this changes all the values to 6s
          -    so, the example above becomes [[6],[6],[6],[6,6],[6,6],[6,6,6]]
   Ḍ      - convert to decimal (vectorises)  [ 6,  6,, 6,  66,   66,   666   ]
       ⁸  - link's right argument, n
     ÐṂ   - filter keep those with minimal:
    ạ     -   absolute difference (for 366 this keeps 66 AND 666; same goes for 3666; etc.)
        Ṫ - tail - get the rightmost result (for 366 keeps 666, since it's longer)

```

A patch to make the same algorithm run within the 60s limit for **365** and **366** on TIO is to avoid the implicit vectorisation of  with `Ẇa6Ḍ€ạÐṂ⁸Ṫ` (try that), however this will now seg-fault for an input of **999** (**Triangle(999)** is only **499,500** but each is a list of integers, making a total of **Tetrahedral(999) = 166,666,500** integers, not memory efficient, at least in Python).
> 4 votes

# Answer
# Jelly, 10 bytes

```
RD6ṁḌạÐṂ¹Ṫ

```

Try it online!
> 3 votes

# Answer
# C, 118 bytes

**Try Online**

```
a;b;d(n,m){return(m*6)+(n>0?d(n-1,m*10):0);}
f(n){a=d((int)log10(n)-1,1);b=d((int)log10(n),1);return(n-a<(b-a)/2)?a:b;}

```
> 3 votes

# Answer
## JavaScript (ES6), 41 bytes

```
f=(n,i=0,j=6)=>n*2<j?i||6:f(n-j,i+j,j*10)

```

### Test cases

```
f=(n,i=0,j=6)=>n*2<j?i||6:f(n-j,i+j,j*10)

console.log(f(1))   // 6
console.log(f(2))   // 6
console.log(f(3))   // 6
console.log(f(6))   // 6
console.log(f(35))  // 6
console.log(f(36))  // 66
console.log(f(37))  // 66
console.log(f(100)) // 66
console.log(f(365)) // 66
console.log(f(366)) // 666
console.log(f(666)) // 666
console.log(f(999)) // 666
```
> 3 votes

# Answer
## Mathematica, 36 Bytes

Pure function:

```
Max[NestList[6+10#&,6,#]~Nearest~#]&

```

Explanation:

```
    NestList[6+10#&,6,#]

```

Iterative create a list of length equal to the input using `NestList` following the pattern `6+10x(previous_value)` starting from the value of `6`.

```
                        ~Nearest~#

```

Then find the value in this list closest to the input.

```
Max[                              ]

```

Lastly take the maximum value from the list of nearest values.

Whilst the list length is super inefficient as mathematica can work with arbitrary precision length numbers this program is only limited by physical memory.
> 3 votes

# Answer
# Templates Considered Harmful, 118 bytes

```
Fun<Ap<Fun<If<lt<A<1>,Add<A<2>,A<3>>>,A<3>,Ap<A<0>,A<1>,Mul<A<2>,I<10>>,Add<Mul<A<3>,I<10>>,I<6>>>>>,A<1>,I<30>,I<6>>>

```

Try it online!

Ungolfed:

```
Fun<Ap<Fun<If<lt<A<1>, Add<A<2>, A<3>>>,
           A<3>,
           Ap<A<0>, A<1>, Mul<A<2>, I<10>>, Add<Mul<A<3>, I<10>>, I<6>>>>>,
       A<1>, I<30>, I<6>>>

```
> 3 votes

# Answer
# 05AB1E, ~~10~~ 9 bytes

\- 1 byte thanks to Riley

```
6×ŒΣI-Ä}¬

```

Try it online!

The above code can have performance issues, here is a slightly more efficient version with 10 bytes: TIO alternative

## Explanation

```
6×ŒΣI-Ä}¬   Main link. Argument n
6×          Push string containing '6' n times
  Œ         Push substrings
   Σ   }    Sort by result of code
    I-Ä     Absolute difference between n
        ¬   Head, implicit output

```
> 3 votes

# Answer
# Neim, ~~12~~ 10 bytes (non-competing)

-1 byte thanks to steenbergh

```
Γ6Θℝ)₁>

```

Explanation:

```
               Implicit input: [366]
               Push the length of the input
                [3]
               Inclusive range
                [[1, 2, 3]]
   Γ            For each
       ℝ         Repeat
    6            6
     Θ           currently looped value times
                 [[6, 66, 666]]
          )     End for each
               Get the closest value to
           ₁    The first line of input...
            >   ...incremented by one
                [666]
                Implicitly print entire stack

```

Unfortunately,  will return the lower value in a list if two numbers have the same difference, so we had to add 2 bytes to account for that.

Non-competing as `>`, `<` and  were added after this question was asked (and  was fixed to work with numbers, not just lists)

Note: Will not work for numbers with a length equal to 19 or more - as they get too big for Java's longs to handle. (but this is quite a large value, and should be fine)

Try it
> 2 votes

# Answer
## Mathematica, 76 bytes

```
Max[Take[LinearRecurrence[{11,-10},{0,6},IntegerLength[#]+1],-2]~Nearest~#]&

```
> 2 votes

# Answer
## QBIC, ~~37~~ 27 bytes

```
≈!@36`!<=:|A=A+!6$]?_sA,2,a

```

Instead of using Maths™ this now uses string manipulation to find the breaks in the Demonic Domains (36, 366, ...). Inspired by @eush77 's JS answer.

Explanation

```
≈         |  WHILE <condition>
 !    !        a numerical cast of
  @  `         the string literal A$
   36          starting out as "36"
       <=    is smaller than or equal to
         :   cmd line argument 'a'
A=A+ 6       Add a 6 to the end of A$ (36 ==> 366 ==> 3666)
    ! $         as a string-cast
]            WEND (ends the WHIOLE loop body)
?_sA         PRINT a substring of A$            n=37, A$ = 366
  ,2           starting at index 2                          ^
  ,a           running well past the end of the string      66

```
> 1 votes

# Answer
# dc, 46 bytes

```
dsxZ1-10r^d11*2-3/dsylx[0r-]s.<.3*ly+d[6]s.0=.

```

Try it online!

```
dsxZ1-10r^d11*2-3/dsylx[0r-]s.<.3*ly+d[6]s.0=.
   Z1-10r^                                      Nearest power of 10
           11*2-3/                              The number in between 6ⁿ and 6ⁿ6
          d          lx[0r-]s.<.                Check which side we're on
                                3*ly+           Get the answer for x≥3
                                     d[6]s.0=.  Return 6 for x<3

```
> 1 votes

# Answer
## C#, 142 bytes

```
a=>{var c=(a+"").Length;return int.Parse(a<int.Parse(3+new string('6',c==1?2:(c==10?1:c)))?new string('6',c-1):new string('6',c==10?c-1:c));};

```

It uses the fact, that we need to jump to the next deamonic number at every 36666... In a more readable form:

```
var c = (a + "").Length;
    return int.Parse(a < int.Parse(3 + new string('6',
        c == 1 ? 2 : (c == 10 ? 1 : c)))
        ? new string('6', c - 1)
        : new string('6', c == 10 ? c - 1 : c));

```
> 1 votes

# Answer
# PHP, 49 Bytes

trim the character 6

```
for(;trim($x=$argn+$i,6)>"";)$i=($i<1)-$i;echo$x;

```

Try it online!

Instead of `trim($x=$argn+$i,6)>""` you can use a Regex solution `!preg_match("#^6+$#",$x=$argn+$i)` +11 Bytes or a string length equal to count `6` comparision `strlen($x=$argn+$i)-strspn($x,6)` +10 Bytes
> 1 votes

# Answer
# braingasm, 15 bytes

```
;3*11/z+[6:10/]

```

Using the arithmetic from orlp's Python solution:

```
;                   Read an integer from stdin
 3*11/              Multiply by 3 and divide by 11
      z+            If result is zero, add one
        [6:10/]     While not zero, print '6' and divide by 10

```
> 1 votes

# Answer
I didn't see this question in the feed, and only stumbled over it by accident. Here's my answer anyway:

## JavaScript (ES6), 34 bytes

```
n=>`${-~n*3/11|0}`.replace(/./g,6)

```

Add 1 byte for a numeric answer. Originally based on this ungolfed ES7 answer (37 bytes, already numeric):

```
n=>(10**(Math.log10(-~n*3/11)|0)*2-2)/3

```

Annoyingly OP wants 36 to be nearer to 66 than 6. Explanation: 11/3=3.666..., so dividing by this scales the ranges 7..36, 37..366 etc. to the ranges 1..9.9, 10..99.9 etc. This can be solved purely numerically by taking 2/3 of one less than the next higher power of 10, although it's golfier to truncate, convert to string, then change all the characters to the digit 6. (Although still not as golfy as that really clever recursive answer.)
> 1 votes

# Answer
## CJam, 25 bytes

Not as slow as the Jonathan Alan's Jelly submission, but requires *O(n²)* memory, where *n* is the input number. Yeah.

```
ri)__{)'6*i}%f-_:z_:e<#=-

```

This is equivalent to the following Python:

```
num = int(input()) + 1                                      # CJam: ri)__
demondiffs = [int("6" * (i + 1)) - num for i in range(num)] # CJam: {)'6*i}%f-
absdiffs = [abs(i) for i in demondiffs]                     # CJam: _:z
mindex = absdiffs.index(min(absdiffs))                      # CJam: _:e<#
print(num - demondiffs[mindex])                             # CJam: =-

```

## Alternative solution, 12 bytes

```
ri)3*B/s,'6*

```

This is a translation of orlp's algorithm into CJam.

Explanation:

```
ri           e# Read integer:       | 36
  )          e# Increment:          | 37
   3*        e# Multiply by 3:      | 111
     B/      e# Divide by 0xB (11): | 10
       s     e# Convert to string:  | "10"
        ,    e# String length:      | 2
         '6  e# Push character '6': | 2 '6
           * e# Repeat character:   | "66"
e# Implicit output: 66

```
> 1 votes

# Answer
# Java 8, 37 bytes

```
 n->(""+-~n*3/11).replaceAll(".","6");

```

Going by Kevin Cruijssen's example and just returning a String.

Do the \*3/11 trick to get the right length, then replace all with sixes.
> 1 votes

# Answer
# LOLCODE 1.4, 471 bytes

```
HAI 1.4
CAN HAS STRING?
I HAS A i
GIMMEH i
I HAS A l ITZ I IZ STRING'Z LEN YR i MKAY
I HAS A s ITZ "3"
IM IN YR a
BOTH SAEM I IZ STRING'Z LEN YR s MKAY AN l
O RLY?
YA RLY
GTFO
OIC
s R SMOOSH s AN 6
IM OUTTA YR l
I HAS A o
DIFFRINT i AN BIGGR of i AN 4
O RLY?
YA RLY
VISIBLE 6
NO WAI
BOTH SAEM i AN SMALLR of i AN s
O RLY?
YA RLY
o R DIFF OF l AN 1
NO WAI
o R l
OIC
I HAS A f
IM IN YR b UPPIN YR k TIL BOTH SAEM k AN o
f R SMOOSH f AN 6
IM OUTTA YR b
VISIBLE f
OIC
KTHXBYE

```

Wow. Here's that Ungolfed and Explained:

```
HAI 1.4
CAN HAS STRING?
I HAS A input
GIMMEH input
I HAS A length ITZ I IZ STRING'Z LEN YR input MKAY BTW this is using the length function of the STRING library.
I HAS A sixes ITZ "3" BTW the average of for example [6...] and 6[6...] is 3[6...].
IM IN YR foreverloop BTW this loop fills the sixes variable.
    BOTH SAEM I IZ STRING'Z LEN YR sixes MKAY AN length # In LOLCODE, a statement containing only an expression assigns the implicit variable IT.
    O RLY? # Tests the current value in IT.
      YA RLY
        GTFO
    OIC
    sixes R SMOOSH sixes AN 6 BTW SMOOSH automatically casts things to YARN. It also does not need a MKAY unless there's something after it on the line.
IM OUTTA YR foreverloop
I HAS A outputlength
DIFFRINT input AN BIGGR of input AN 4 BTW LOLCODE doesn't have a built-in inequality operator. This just means input < 4
O RLY?
  YA RLY
    VISIBLE 6 BTW If it's less than 4, the algorithm of comparing to the nearest 3.6*10^n.
  NO WAI
    BOTH SAEM input AN SMALLR of input AN sixes BTW input<=sixes
    O RLY? BTW This if statement makes sure that if the input is less than 3.6*10^length, it goes to the previous place value's demon number.
      YA RLY
        outputlength R DIFF OF length AN 1
      NO WAI
        outputlength R length
    OIC
    I HAS A final
    IM IN YR forloop UPPIN YR iterator TIL BOTH SAEM iterator and outputlength
        final R SMOOSH final AN 6
    IM OUTTA YR forloop
    VISIBLE final
OIC
KTHXBYE

```

Still wow. Here's some pseudojavascrython for you.

```
hello()
import string
var i
i=input()
var l=string.len(i)
var s="3"
while True:
  if(string.len(s)==l):
    break
  s=s+6
var o
if(i!=max(i,4)): # Basically if(i<4)
  print 6
else:
  if(i==min(i,s)): # Basically if(i<=s)
    o=l-1
  else:
    o=l
  var f
  for(var k=0;k<o;k++):
    f=f+6
  print(f)
exit()

```

Still don't get it? This program basically just (excluding inputs 1-3) compares the input to the 3.6\*10^n, n being the length of the input. If it is smaller than that number, it prints the number of 6s one less than the length. If it is greater than or equal to that number, the number of sixes is the current length.

Would love some help golfing!
> 1 votes

# Answer
# Haxe, 70 bytes

```
function(x){x*=3;x/=11;do{Sys.print('6');}while((x=Std.int(x/10))>0);}

```

Input has to be passed as type `Float` despite being an integer, otherwise Haxe will complain about trying to divide an integer (yes haxe will refuse to compile if you divide an integer by anything)

Same as all the other answers. Multiply by 3, divide by 11, print 1 `6` for every digit.
> 0 votes

# Answer
# Brainfuck, 315 bytes

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

```

**Run it here**. Select a cell size that can handle values of 3\*(n+1), so for all of the test cases to work, select 16. **Dynamic (infinite) Memory** must be turned on for this to work. This allows the tape to expand to the left. To input an integer, type the input like `\366` for n=366.

### Ungolfed:

Uses the same algorithm as this solution. The algorithms used for each individual step are taken from this page. All algorithms used are non-wrapping, so that the program won't break for larger inputs.

```
,+ # n = n plus 1
>+++ # 3
[>>+<<-]>>[<<<[>+>+<<-]>>[<<+>>-]>-] # n = n*3
<+++++++++++ # 10
<[>>+<<-]>>[<[>>+>+<<<-]>>>[<<<+>>>-]<[>+<<-[>>[-]>+<<<-]>>>[<<<+>>>-]<[<-[<<<->>>[-]]+>-]<-]<<<+>>] # n = n/10
<[-]+<[>-]>[<+>->] # if (n == 0) { n = n plus 1 }
++++++[<+++++++++>-] # '6' (54)
<<<[-]++++++++++> # 10
[ # while (n above 0)
  >.< # print '6'
  [<<+>>-]<<[>[<<+<+>>>-]<<<[>>>+<<<-]>[<+>>-[<<[-]<+>>>-]<<<[>>>+<<<-]>[>-[>>>-<<<[-]]+<-]>-]>>>+<<]>> # n = n/10
]

```
> 0 votes

# Answer
# C#, 102 bytes

```
string a(int j,int k=0)=>(j+"|"+(k=k==0?j:k)).Split('|').Where(s=>s.All(c=>c=='6')).Max()??a(j+1,k-1);

```

Kinda disappointed in the length of this, could do exactly the same as the shorter answer in Java but I did not really understand it because I am a lazy, stupid .NET developer :)
> 0 votes

# Answer
# Japt, 9 bytes

```
_ì e¥6}cU

```

Try it
> 0 votes

# Answer
# 05AB1E, 7 bytes

```
6s×ηs.x

```

Try it online!

---

```
Program # Input ====================|> 2
--------#---------------------------+--------
6s×     # Push N 6's as a string.   | 66
   ηs   # Prefixes of this.         | [6, 66]
     .x # Closest element to input. | 6

```
> 0 votes

---
Tags: code-golf, number, arithmetic
---


title: Take a stand against long quine lines

text:
# Question
Title: Take a stand against long quine lines
# or: Build a vertical quine

Inspired by Take a stand against long lines.

Your task is to build a vertical quine with as short a line length as possible.

## Scoring

Shortest line length (excluding newlines) wins, with criteria as a tie-breaker.

Line length is determined as the longest line in your program excluding the line break character.

For example:

```
$_=
Q.
P

```

has a line length of 3 and a byte count of 8, whilst:

```
Q
$
_
P

```

Has a line length of 1 and a byte count of 7 (assuming no trailing newline).

## Rules

Quines must meet the community definition of a quine.

Standard loopholes are forbidden.

# Answer
# Lenguage, line length 0, ≈ 1.01 × 10805 bytes

The source code consists of

> 10124204951141713202533972929121310016060433092338061822344361345785088607872212687519180665846846689047959498775873817205954910072327976407177053174071436371843670134990737172675632938993247496933911137703773908536875512359091727633452506044935740750830240213878294804481182083555147915724921824921475110508228264569693355158523956426011218344830576542194309867719995259333487662608933990607888012376767799159279952780093033761421596267435996052643805835600325453580090964941176722519904997142820547696122795384058768166716813179490118821654787005844786013890425692181280317909786461426684986082270532414940905922244777135016193088362341771414388821075092853157152933099269703875111747946164773211049512395358715902962437487134522781505709420586981997748912591875626029183292826655753251235587052422561943

linefeeds, which encodes the brainfuck program that follows.

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

```

The source code is mostly identical to @jimmy23013's radiation-softened Lenguage quine, minus the `.` at the end, with `++++++++++.[-]` replacing `.` to print linefeeds instead of null bytes, and the corresponding changes to the data section on line 1.
> 32 votes

# Answer
# JavaScript, line length 1, ~~960~~ ~~956~~ 928 bytes

```

[
t
,
r
,
u
,
e
,
f
,
a
,
l
,
s
]
=
!
0
+
[
!
1
]
;
[
,
n
,
d
,
,
q
,
i
]
=
t
.
a
+
t
V
=
[
]
[
f
+
i
+
n
+
d
]
;
[
,
,
,
c
,
,
,
o
,
,
_
,
,
,
,
,
y
,
z
]
=
V
+
0
F
=
V
[
E
=
c
+
o
+
n
+
s
+
t
+
r
+
u
+
c
+
t
+
o
+
r
]
P
=
(
1
+
e
+
2
+
3
-
4
+
t
)
[
2
]
f
=
F
(
r
+
e
+
t
+
u
+
r
+
n
+
_
+
a
+
t
+
o
+
(
0
+
{
}
)
[
3
]
)
(
)
(
3
*
4
+
[
]
[
E
]
[
n
+
a
+
(
0
[
E
]
+
0
)
[
9
+
2
]
+
e
]
)
[
1
]
F
(
a
,
a
+
l
+
e
+
r
+
t
+
y
+
a
+
P
+
q
+
P
+
a
+
P
+
q
+
z
)
`
[
t
,
r
,
u
,
e
,
f
,
a
,
l
,
s
]
=
!
0
+
[
!
1
]
;
[
,
n
,
d
,
,
q
,
i
]
=
t
.
a
+
t
V
=
[
]
[
f
+
i
+
n
+
d
]
;
[
,
,
,
c
,
,
,
o
,
,
_
,
,
,
,
,
y
,
z
]
=
V
+
0
F
=
V
[
E
=
c
+
o
+
n
+
s
+
t
+
r
+
u
+
c
+
t
+
o
+
r
]
P
=
(
1
+
e
+
2
+
3
-
4
+
t
)
[
2
]
f
=
F
(
r
+
e
+
t
+
u
+
r
+
n
+
_
+
a
+
t
+
o
+
(
0
+
{
}
)
[
3
]
)
(
)
(
3
*
4
+
[
]
[
E
]
[
n
+
a
+
(
0
[
E
]
+
0
)
[
9
+
2
]
+
e
]
)
[
1
]
F
(
a
,
a
+
l
+
e
+
r
+
t
+
y
+
a
+
P
+
q
+
P
+
a
+
P
+
q
+
z
)
`
```

More readable version which also happens to be a quine (extraneous newlines removed):

```

[t,r,u,e,f,a,l,s]=!0+[!1];[,n,d,,q,i]=t.a+t
V=[][f+i+n+d];[,,,c,,,o,,_,,,,,y,z]=V+0
F=V[E=c+o+n+s+t+r+u+c+t+o+r]
P=(1+e+2+3-4+t)[2]
f=F(r+e+t+u+r+n+_+a+t+o+(0+{})[3])()(3*4+[][E][n+a+(0[E]+0)[9+2]+e])[1]
F(a,a+l+e+r+t+y+a+P+q+P+a+P+q+z)`
[t,r,u,e,f,a,l,s]=!0+[!1];[,n,d,,q,i]=t.a+t
V=[][f+i+n+d];[,,,c,,,o,,_,,,,,y,z]=V+0
F=V[E=c+o+n+s+t+r+u+c+t+o+r]
P=(1+e+2+3-4+t)[2]
f=F(r+e+t+u+r+n+_+a+t+o+(0+{})[3])()(3*4+[][E][n+a+(0[E]+0)[9+2]+e])[1]
F(a,a+l+e+r+t+y+a+P+q+P+a+P+q+z)`
```

### Explanation

Whew. Settle in for a ride here, because this is gonna be a treacherous journey...

I spent a long time trying to figure out how to solve this challenge with length 1—no built-ins (directly, anyway), keywords, or even arrow functions—before realizing that it is easily possible with JSF\***, which can evaluate any JavaScript code while avoiding any multi-byte tokens. But a JSF solution would easily be thousands of bytes long, if not tens or hundreds of thousands. Thanksfully, we aren't limited to just `()[]+!`—we have all of ASCII at our disposal!

I decided to start by golfing the essential building blocks of JSF—the characters that can be built up into strings to "unlock more features," so to speak. We can't use strings directly to get characters, as that would require lines of length 3. So instead, we steal a trick from JSF, getting a few chars from literals that can be built up with single-byte tokens:

```
JSF***   Used here   Value        Chars unlocked
!![]     !0          true         true
![]      !1          false        fals
[][[]]   t.a         undefined    ndi

```

From these we can expand outward, starting with `[].find`, which is a Function object. Converting this to a string `function find() { ...` gives us access to `c`, `o`, space (`_`), and parentheses (`y` and `z`). Perhaps more importantly, we now have access to its `constructor`, the `Function` function—which, inceptional as it may sound, gives us the ability to execute code by building a string, passing it to `Function()`, and then calling the function generated.

I should probably mention the overall method used by the program itself. As of 2015, JavaScript has this really cool feature called "tagged templates," which not only allows unescaped newlines in strings, but also lets us call a function with a string literal directly (in a way; `myFunc`abc`;` is roughly equivalent to `myFunc(["abc"])`). If we put the function call as the last thing in the program, the general structure will look like this:

```
code;func`code;func`

```

All `func` has to do then is output its argument, followed by a backtick, then its argument again, and a second backtick. Assuming we have the argument in `a` and a backtick stored in `f`, we can accomplish this with the code `alert(a+f+a+f)`. However, at the moment, we are missing `+` and the backtick itself. `+` (stored in `P`) isn't hard; we steal another trick from JSF, building the string `1e23`, converting to a number, then back to a string, giving `"1e+23"`.

Getting a backtick is a bit more complicated. At first, I tried obtaining `String.fromCharCode`, but finding a `C` turned out to be nearly as difficult. Fortunately, `atob` is easy enough to obtain (`Function("return atob")()`; `b` is generated from `0+{}`, which gives `[object Object]`) and can give any ASCII char, if a proper magic string is found. A short script gave me `12A` as one of the options, which can conveniently be found in `12Array` (a bit shorter to generate, thanks to `[].constructor[n+a+m+e]`; `m` is found in `0 .constructor+0`: `"function Number() { ..."`).

Finally, we stick everything together. We assign the backtick to variable `f`, but since we can't use it directly in the function string, we instead set variable `q` to the letter `f` and use that instead. This makes our final string `a+l+e+r+t+y+a+P+q+P+a+P+q+z`, or `"alert(a+f+a+f)"`. We then feed this to `Function()`, feed the our finished code to the result, and voila, we have a JavaScript quine with no more than one char per line!

---

My head feels terrible at the moment, so please inquire about any mistakes I've made or things I've missed in this explanation, and I'll get back to you after I've had some rest...
> 29 votes

# Answer
# Haskell, line length 6, ~~400~~ ~~343~~ 336 bytes

```
{main=
putStr
$s++(s
>>=(++
":\n")
.show)
++
"[]}";
s='{':
'm':
'a':
'i':
'n':
'=':
'\n':
'p':
'u':
't':
'S':
't':
'r':
'\n':
'$':
's':
'+':
'+':
'(':
's':
'\n':
'>':
'>':
'=':
'(':
'+':
'+':
'\n':
'"':
':':
'\\':
'n':
'"':
')':
'\n':
'.':
's':
'h':
'o':
'w':
')':
'\n':
'+':
'+':
'\n':
'"':
'[':
']':
'}':
'"':
';':
'\n':
's':
'=':
[]}

```

Try it online! I'm not aware of a way around `putStr`, thus the line length of 6. The outer curly braces allow to get rid of the otherwerwise required indention after a newline within a single declaration.
> 15 votes

# Answer
# \>\<\>, 22 bytes, line length 1

```
/
v
o
a
o
^
}
-
d
:
"

```

Try it online!

-6 bytes thanks to Emigna.
> 12 votes

# Answer
# CJam, line length 1, ~~16~~ 13 bytes

```
"
_
p
"

_
p

```

Try it online!

It's a small miracle that inserting newlines into the ~~standard quine `{"_~"}_~`~~ even shorter standard quine `"_p"␊_p` does the right thing. (Thanks, Martin!) The trailing newline is necessary.

## Explanation (with • as newline)

```
"•_•p•"        Push that string.
       ••      Do nothing.
         _     Duplicate the string.
          •    Do nothing.
           p   Pop it and print it with quotes and a newline: "•_•p•"•
            •  Do nothing.

```

On termination, what's left on the stack is printed (`•_•p•`), yielding total output `"•_•p•"••_•p•`.
> 12 votes

# Answer
# Haskell \+ CPP, line length 2, ~~705~~ 237 bytes

```
m\
a\
i\
n\
=\
p\
u\
t\
S\
t\
r\
$\
(\
:\
"\
\\
\\
\\
n\
"\
)\
=\
<\
<\
s\
+\
+\
s\
h\
o\
w\
 \
s\
;\
s\
=\
"\
m\
a\
i\
n\
=\
p\
u\
t\
S\
t\
r\
$\
(\
:\
\\
"\
\\
\\
\\
\\
\\
\\
n\
\\
"\
)\
=\
<\
<\
s\
+\
+\
s\
h\
o\
w\
 \
s\
;\
s\
=\
"\

```

Try it online! Using the flag `-CPP` which enables the C pre-processor allows us to use a backslash at the end of a line to continue it on the next line.

The actual code is `main=putStr$(:"\\\n")=<<s++show s;s="<data>"`.

*Edit: A casual -468 bytes thanks to Ørjan Johansen!*
> 6 votes

# Answer
# Rust, line length: 5, bytes: ~~301~~ 299

Try it online

Despite how it looks, this isn't an esoteric programming language, there is just a lot of format line noise.

Vertical length of 5 was chosen to be able to use `print`. I don't think there is a way to print that would have shorter vertical length, declaring C functions uses `extern` keyword, `stdout` is 6 bytes long, `write` is 5 bytes long, `no_main` is 7 bytes long (main is usually a function ;)).

```
fn
main
(){
let
t=(
r#"fn
main
(){
let
t=("#
,r#")
;
print
!(
r#"{}
r#"{
}"{}
,r#"{
}"{},
r#"{
}"{}
{}{}{
}{
}""#,
r#"
,t.0,
t.0,
'#',
t.1,
'#',
t.2,
'#',
t.1,
'#',
t.2,
'}'
)"#
)
;
print
!(
r#"{}
r#"{
}"{}
,r#"{
}"{},
r#"{
}"{}
{}{}{
}{
}"#
,t.0,
t.0,
'#',
t.1,
'#',
t.2,
'#',
t.1,
'#',
t.2,
'}'
)}

```
> 5 votes

# Answer
# 05AB1E, Line length: 1, Byte count: 43

```
2
"
D
3
4
«
ç
¶
ì
ý
Ô
"
D
3
4
«
ç
¶
ì
ý
Ô

```

Try it online!
> 4 votes

# Answer
# Japt, line length 1, 20 bytes

Based off the standard Japt quine by ETHproductions.

```
"
i
Q

²
"
i
Q

²

```

**Try it here!**
> 2 votes

# Answer
# JavaScript (ES6), line length 3, 17 bytes

```
f=
_=>
`f=
${f
}`

```
> 2 votes

# Answer
# Red, line-length: 10, 49 bytes

```
s: [prin [
    "s:"
    mold s
    "do s"
]] do s

```

Try it online!

This in fact is a Rebol quine

Explanation: Red/Rebol's `mold` follows the coding style of putting 4 spaces offset.

```
s: [prin [     ; s is a block; print the following:
    "s:"       ; literal "s:"
    mold s     ; the representation of the block itself - all between []
    "do s"     ; literal "do s"
]] do s        ; evaluate the block

```
> 2 votes

# Answer
# RProgN, 3 bytes, line length 1

```
0
0

```

Try it online!

A copy of Dennis' answer here (go upvote him too)

This is a conforms to our current definition of a proper quine, as the first 0 encodes the second 0 and vice-versa.
> 2 votes

# Answer
# RProgN 2, L = 1, B = 15 bytes

```
«
Ø
.
`
-
S
`
.

```

This is equivilent to the program:

```
«Ø.`
-S`
.

```

## Breakdown

`«` first pushes a function representing implicitly the rest of the program to the stack, and then continues execution. `Ø.` appends an empty string to the function, which stringifies it. This will always stringify like the equivilent program, due to newlines being no-ops. ``\n-` Removes all newlines from the string, now looking like `«Ø.`=S`.`. `S` then converts it to a stack of single characters, and ``\n.` joins the stack by newlines, returning the expected program.

Try it online!
> 2 votes

# Answer
# Underload, line length 1, 20 bytes

```
(
:
a
S
S
)
:
a
S
S

```

Try it online!

This is just the standard Underload quine with newlines appended. Requires an implementation like the TIO one which ignores unknown command characters.

The part in `()` is a string literal put on the stack, `:` duplicates it, `a` wraps the top stack entry in parentheses, and `S` prints.
> 2 votes

# Answer
# Perl 5, 259 bytes

```

$
_
=
p
.
r
.
i
.
n
.
t
.
q
{

'
$
_
=
p
.
r
.
i
.
n
.
t
.
q
{
'
,
&
{
I
.
"
X
0
y
h
~
"
^
"
E
O
0

y
"
.
x
}
(
$
_
,
6
,
-
1
)
,
'
}
;
&
{
I
.
"
X
0
o
k
h
~
"
.
(
Y
|
p
)
^
"
E
O
0
|
f
s
o
"
}
'
}
;
&
{
I
.
"
X
0
o
k
h
~
"
.
(
Y
|
p
)
^
"
E
O
0
|
f
s
o
"
}

```

Try it online!

Verification.
> 2 votes

# Answer
# Javascript (ES6 REPL), full-program, line-length: 3, byte-count: 31

```
(
f=
_=>
`(
f=
${f
}
)
()`
)
()

```

This is a port of @kamoroso94's answer to a self-contained full program.

If anybody finds a way to strip off some bytes without adding more to the line-length feel free to comment :)
> 1 votes

# Answer
# Pip, line length 1, 35 bytes

```

V
Y
"
[
`
V
Y
`
y
]
.
C
:
3
.
4
"

```

Try it online!

Based on the shortest known Pip quine, `V Y"`V Y`.RPy"`. The main difficulty in squishing it to line length 1 is `RP`, which can't be split over two lines. But in this case, all `RP` (repr) does is wrap the string in double quotes, which we can do directly.

Here's an explanation based on a horizontal version:

```
V Y"[`V Y`y].C:3. 4"
  Y"               "  Yank this string into the variable y
V                     and eval it
                      The code that is eval'd:
    [      ]           Build a list containing:
     `V Y`              this Pattern object (used for regex, but here useful as a
                          string-like object that doesn't need double quotes)
          y             y, the whole string
               3. 4    Concatenate 3 and 4 to make 34 (since the 2-digit number won't work
                         in the vertical version)
             C:        Convert to ASCII character (: forces the precedence lower than .)
            .          Concatenate the " to the end of each list element
                      The resulting list is printed, concatenated together, with a
                        trailing newline

```
> 1 votes

# Answer
# Befunge-98, 41 bytes

```
^
@
,
,
a
-
1
*
5
7
|

#
!
a
#
:
,
^
$
"

```

Try it online!

Really just a normal quine turned sideways, with some extra stuff to print newlines.
> 1 votes

---
Tags: code-challenge, quine, source-layout
---


title: Transpose quine

text:
# Question
Title: Transpose quine
In this quine variant, your program must output its source code transposed across the diagonal from the top left to the bottom right. For example:

```

your program
on
four lines

```

outputs

```
 yof
 ono
 u u
 r r

 p l
 r i
 o n
 g e
 r s
 a
 m

```

The whitespace in the output is not arbitrary. Spaces appear in two situations: where there is a space in the original (e.g. between `r` and `l` in the fourth column) and where it's necessary to pad characters (e.g. all the spaces in the first column.) Both are required, and spaces cannot appear anywhere else in the output.

A single trailing newline in the output can optionally be ignored. Trailing newlines in the source code have no effect on the output, and leading newlines in the source code must be handled as in the example above. Assume that every character that is not a newline is one column wide and one row tall, even though for characters like tab this may lead to an ugly output.

Your solution must have at least two lines with at least two non-newline characters each, and must not be its own transpose (the output cannot be identical to the source.)

Cheating quines that read from the file that contains their source code, pull data from a URL, use quining built-ins, and so on are not permitted.

This is code golf: shortest code in bytes wins.

# Answer
## CJam, 14 bytes

```
{`"_~".+N*}
_~

```

Test it here.

While shorter, probably a bit less interesting than the Fission solution.

### Explanation

```
{       e# Quine framework. Runs the block while another copy of it is on the stack.
  `     e# Stringify the block.
  "_~"  e# Push the remaining code as a string.
  .+    e# Element-wise append... essentially puts the two strings in a grid and
        e# transposes it.
  N*    e# Join with linefeeds.
}_~

```
> 5 votes

# Answer
## Fission, 17 bytes

Still my favourite language for quines...

```
'"
!0
0+
;!
DN
"!

```

Try it online!

### Explanation

This quite similar to the basic Fission quine. In fact, if it wasn't for the "must have at least two lines with at least two non-newline characters each" rule, I simply could have transposed that and replace `R` with `D`. That rule makes things a bit more interesting though, because we need to print another line.

Control flow starts at the `D` with a single atom going south. Since it hits the `"` it will wrap around and print

```
'!0;D

```

to STDOUT, similar to how it would in the normal quine. `'!` then sets the atom's mass to the character code of `!`. The `0` is a teleporter which transports the atom to the second column, where it's still moving south.

With `+` we increment the atom's mass to the value of `"`. `!N!` the prints quote, linefeed, quote. STDOUT now looks like this:

```
'!0;D"
"

```

After wrapping around, the atom hits another `"` and now prints the second line verbatim:

```
'!0;D"
"0+!N!

```

We're done now. The atom uses the teleporter once again, and lands in the `;` which destroys it and thereby terminates the program.

I suppose the neatest bit here is putting one `"` at the bottom and the other at the top so that I can print them in one go without having to set the value of `!` once more (because it would get overwritten by entering string mode again).
> 10 votes

# Answer
# Javascript ES6, 90 bytes

```
$=_=>[...(_=`$=${$};$()`.split`
`)[0]].map((x,y)=>_.map(v=>[...
v][y]).join``).join`
`;$()

```

Not bad, not bad.

# Explanation

Here's the standard quine framework:

```
$=_=>`$=${$};$()`;$()

```

To modify, I just split the quine string along newlines and chars to create a matrix of chars, transposed using 2 map functions, and joined to create the output.
> 3 votes

# Answer
# Stax, 23 bytes

```
"34bL:f2MMm
"34bL:f2MMm

```

Try it online!

Adaptation of the `"34bL"34bL` quine, which is based on an idea used in quines in many languages.
> 3 votes

# Answer
# Befunge-93, 57 bytes

```
^
_^
,@
+,
5*
52
,+
*9
28
+|
9
8#
|!
 ,
##
!:
,^
#
:
^
""

```

This works by putting each character in the first column on the stack (except the quote itself), then printing each item off of the stack. After that, it prints the quote, prints a newline, and then moves over to the second column. It does the same thing sans print a newline.

You can test it in the link in the title, but you'll need to copy-paste the code into the window yourself. If you hit the 'slow' button, it will show you the path the pointer takes and the stack at the time.
> 2 votes

# Answer
# Python 2, ~~91~~ ~~75~~ 69 bytes

```
s='#%r;print"s#\\n="+"\\n".join(s%%s)';print"s#\n="+"\n".join(s%s)
##

```

**Try it online**

### Explanation:

This uses a modification of the standard quine:

```
s='s=%r;print s%%s';print s%s

```

After modification:

```
s='s=%r;print"\\n".join(s%%s)';print"\n".join(s%s)

```

This would be enough if a single line was allowed. Then, I added two characters to the 2nd line to fulfill that requirement. The `#` chars on the second line can be replaced with anything, so long as you change them in the first line, too, and it makes the program syntactically valid.

To print it correctly now, I have to print `#` at the end of the first two lines. So I remove the first two characters from the string `s`, and print those with `#` before printing `s%s`. I put one of the `#` at the start of `s` to save some bytes by removing a newline literal.
> 1 votes

---
Tags: code-golf, quine
---


title: Build a half cardinal cyclic quine

text:
# Question
Title: Build a half cardinal cyclic quine
A half cardinal cyclic quine is a cyclic quine with two states, one perpendicular to the other.

## Rules

You can decide which rotation you want to implement, clockwise or counter-clockwise.

Once rotated, any gaps in your code should be replaced with spaces to preserve the positioning.

Your program must satisfy the community definition of a quine.

This is so the shortest program in each language wins. Your *first* program is used for your byte count.

Standard loopholes are forbidden.

## Examples

If your program is:

```
$_='print';eval

```

Then the next iteration must be either:

```
$
_
=
'
p
r
i
n
t
'
;
e
v
a
l

```

or

```
l
a
v
e
;
'
t
n
i
r
p
'
=
_
$

```

which must output the original program:

```
$_='print';eval

```

If your program is:

```
;$_=';
;$_=';
print

```

Then the next iteration must be either:

```
;;
''t
==n
__i
$$r
;;p

```

or:

```
p;;
r$$
i__
n==
t''
 ;;

```

which must output the original program:

```
;$_=';
;$_=';
print

```

# Answer
## CJam, ~~19~~ ~~17~~ 15 bytes

```
{s"_~"+N*""-}_~

```

Try it online! Try the rotation.

### Explanation

```
{s"_~"+  e# Standard quine framework. Puts a string representation of the entire
         e# program on the stack.
  N*     e# Riffle linefeeds into the string, which is effectively a clockwise
         e# rotation by 90°.
  ""-    e# Does nothing.
}_~

```

In the rotated code, we've got linefeeds everywhere:

```
{
s
"
_
~
"
+
N
*
"
"
-
}
_
~

```

As Lynn noticed on Dom's earlier quine challenge inserting linefeeds actually still forms valid quine, because the linefeeds inside the block will just be retained verbatim anyway, and there will also be linefeeds in the `"_~"` string to make those two characters at the end show up on their own line. So `{s"_~"+...}_~` (with linefeeds) is still a valid quine framework (although there'll be an additional linefeed at the end of the string). `N*` now inserts even more linefeeds into that string, but we don't really care: because now `""-` has a linefeed inside that string so it actually removes all linefeeds from the program representation. So we end up with the horizontal form of the code again, undoing the rotation.
> 14 votes

# Answer
# Stax, 28 bytes

```
"8H^Hs+2*A]/Mm"8H^Hs+2*A]/Mm

```

Run and debug the first form

Run and debug the second form
> 5 votes

# Answer
# \>\<\>, 22 bytes

```
 "2+}>oao#ov*48}}*d3'v

```

Try it online!

Rotated anti-clockwise:

```
v
'
3
d
*
}
}
8
4
*
v
o
#
o
a
o
>
}
+
2
"

```

Try it online!

The first one prints the line in reverse with newlines interspersed, and the second prints it in reverse without the newlines.
> 5 votes

# Answer
# 05AB1E, ~~36~~ 34 bytes

```
4"D6Ø·çýD¶åi¶KëS»"D6Ø·çýD¶åi¶KëS»

```

Try first iteration or Try next iteration
> 4 votes

---
Tags: code-golf, quine, source-layout
---


title: Plumbing Random Paths

text:
# Question
Title: Plumbing Random Paths
Write a program or function that takes in three integers, a width `w`, a height `h`, and a step count `s`. You will be drawing a non-self-intersecting random walk `s` steps long on a `5*w` by `5*h` pixel image where every 5 by 5 pixel cell is either empty (pure beige) or one of these twelve simple "pipes":

The image above is enlarged to show detail. Here are the pipes at actual size:

(The gray lines are just to separate the pipe types.)

The random walk will be a single continuous pipe path that starts at one pipe endpoint (one of the bottom four pipe types) and ends at another pipe endpoint.

Start with an empty `w` by `h` grid and randomly choose one cell to be the starting point. Then randomly choose one of the four directions to start in and draw the corresponding pipe endpoint. This starting cell marks the first step in your walk and every time you draw a new cell or overwrite an existing one it counts as another step taken.

Now, repeatedly, randomly choose to go right, left, or straight, drawing the appropriate pipe cell if the direction chosen is valid. Backtrack and re-choose if a direction is not valid until the complete `s` step path is formed. The path should end with a pipe endpoint, which might be anywhere on the grid, depending on the course the path took.

It is very important to note that only the two straight pipe cells can be overwritten, and only by the straight pipe cell of the opposite orientation, the result being an intersection cell. **Otherwise, all pipes must be placed in empty cells.**

When an intersection is drawn, the part of the path that is further along from the starting cell should be drawn on top.

It is up to you whether or not the grid has periodic boundary conditions (PBC), i.e. whether a pipe exiting one side of the grid will come out on the other side. Without PBC the grid boundary counts as a barrier that you can run into just like other pipes.

### Special Cases

* When `s` is 0 no pipes should be drawn and the output should be a blank `5*w` by `5*h` image (i.e. all beige).
* When `s` is 1 a single pipe stub

(Actual size: )

should be drawn at the randomly chosen starting cell.

### Other Details

* You may assume that `s` is at most `w*h` so a path will always be possible. (Though longer paths are possible due to intersections.)
* `w` and `h` will always be positive.
* All random choices must be *uniformly* random. e.g. you shouldn't avoid making intersections when they are possible even if it makes the problem easier. Pseudo-random number generators are allowed.
* Any three visually distinct colors may be used in place of the black, blue, and beige.
* Your output images may be enlarged so that they are really `5*w*k` by `5*h*k` pixels where `k` is a positive integer. (Enlarging any examples you post is advised even if your `k` is 1.)
* Any common lossless image file format may be used and the image may be saved to a file, displayed, or spewed raw to stdout.

**The shortest code in bytes wins.**

# Examples

(All enlarged by 500%.)

If the input is `w=2, h=1, s=0` then the output will always be:

If the input is `w=2, h=1, s=1` then the output will be one of these images with equal chance:

If the input is `w=2, h=1, s=2` then the output will be

or possibly

if the grid is assumed to have PBC.

(Note that starting the path like  would make a second step impossible.)

---

Here are some possible outputs for `w=3, h=2, s=6`, assuming PBC:

---

Here is a possible output for `w=3, h=3, s=9`, assuming PBC:

Notice that the path didn't need to cover all the cells due to the intersection counting as two steps. Also, we can deduce that the corner endpoint was the starting cell since the intersection overpass must have been drawn afterwards. Thus we can infer the sequence of random choices that were made:

```
start at top left, facing east
go straight
go right
go right
go right
go straight
go left
go right
end

```

---

Finally, here are examples of `w=4, h=5, s=20` and `w=4, h=5, s=16`:

# Answer
# CJam, 274

```
q~:K;:B;:A;{0aA*aB*:M5*5f*:I;K{[Bmr:QAmr:P]5f*:R;3Ym*{R.+:)2{1$0=I=2$W=@tI@0=@t:I;}:F~}/R2f+1FK({MQ=P=:EY4mr:D#&1{{MQMQ=PE2D#+tt:M;}:G~7,1>[W0_1_0_W]2/D=:Off*{[QP]5f*2f+.+_:H1F_OW%.+2FOW%.m2F}/H2FO~P+:P;Q+:Q;MQ=P=:E_5YD2%-*=!JK2-=+*1{D2+4%:D;G}?}?}fJ]}0?}g'P2NA5*SI,N2NI:+N*

```

Try it online

Uses PBC, outputs in PGM format. You can remove the `:+` near the end to get a nicer visual output in the browser.

It's very slow for larger input, especially if the step count is close to the area.

Example result for input `4 3 10` (scaled 500%):

**Brief explanation:**

The general approach is:

* repeat all the following steps until successful:
* initialize 2 matrices: one recording which sides are being used in each cell, and one for the image
* if s=0, we're done, else:
* pick a random cell and draw a square, then do the following s-1 times:
* pick a random direction; if that side is already used, fail and start over
* mark the side as used and draw the actual pipe in the image (drawing 3 adjacent lines of length 6, starting right "after" the center pixel of the current cell, then adding a dot to cap the end of the pipe)
* update the current position (moving to the next cell)
* check if the cell is empty or it's a valid crossing; if not, fail and start over
* mark the side in the opposite direction as used in this cell, then continue the loop
> 4 votes

# Answer
# QBasic, ~~517~~ 516 bytes

```
RANDOMIZE TIMER
SCREEN 9
INPUT w,h,s
1CLS
IF s=0GOTO 9
x=5*INT(RND*w)
y=5*INT(RND*h)
GOSUB 7
FOR k=1TO s-1
r=INT(RND*4)+1
a=x+5*((r=2)-(r=4))
b=y+5*((r=1)-(r=3))
c=(POINT(a,b+2)*POINT(a+4,b+2)+POINT(a+2,b)*POINT(a+2,b+4))*(0=POINT((a+x)\2+2,(b+y)\2+2))
IF((0=POINT(a+2,b+2))+c)*(a>=0)*(b>=0)*(a<5*w)*(b<5*h)=0GOTO 1
x=a
y=b
GOSUB 7
o=1AND r
p=x-2+3*o-5*(r=2)
q=y+1-3*o-5*(r=1)
u=p+3-o
v=q+2+o
LINE(p,q)-(u,v),7,B
LINE(p+o,q+1-o)-(u-o,v-1+o),1
NEXT
9IF c GOTO 1
END
7LINE(x+1,y+1)-(x+3,y+3),7,B
PSET(x+2,y+2),1
RETURN

```
* Takes `w`, `h`, and `s` from user input, comma-separated.
* Output is drawn on the screen. While the program is searching for a solution, you may see partial solutions flickering past.
* Does not use periodic boundary conditions. I found it easier to draw and test for connecting pipes without having to worry about half of the pipe being on one side of the grid and half on the other.

The approach here is to try a random direction at each step and start over from the beginning if it results in an invalid move. We draw the pipes as the directions are decided, and use `POINT` to test points on the screen for our validity conditions. A move is valid if it doesn't go outside the boundaries of the grid and:

1. The moved-to cell is empty; or
2. Both
    1. The moved-to cell contains a pipe going straight through, either horizontally or vertically, and
    2. The new pipe section does not double up an existing pipe section

Like aditsu's CJam answer, this code is very slow, and can be mind-numbingly slow if `s` is a significant fraction of `w*h`. On my QB64 setup, it comes up with an answer for `5,5,19` fairly promptly, but takes longer than I was willing to wait on `5,5,20`.

If you want to run larger/more densely packed examples, here's my original approach using a depth-first search. It's much more efficient, at the cost of a whopping 300 extra bytes.

```
RANDOMIZE TIMER
SCREEN 9
INPUT w,h,s
DIM t(s),m(s)
0
FOR z=1TO s
t(z)=-1
NEXT
i=5*INT(RND*w)
j=5*INT(RND*h)
k=1
1CLS
IF s=0GOTO 9
x=i
y=j
GOSUB 7
FOR z=1TO k-1
r=m(z)
GOSUB 6
x=a
y=b
GOSUB 7
o=1AND r
p=x-2+3*o-5*(r=2)
q=y+1-3*o-5*(r=1)
u=p+3-o
v=q+2+o
LINE(p,q)-(u,v),7,B
LINE(p+o,q+1-o)-(u-o,v-1+o),1
NEXT
IF c*(k=s)THEN k=k-1:GOTO 1 ELSE IF k=s GOTO 9
IF k<1GOTO 0
IF t(k)>=0GOTO 4
t(k)=0
f=30
WHILE f
r=INT(RND*4)+1
IF f AND 2^r THEN t(k)=t(k)*5+r:f=f-2^r
WEND
4r=t(k)MOD 5
m(k)=r
t(k)=t(k)\5
GOSUB 6
c=(POINT(a,b+2)*POINT(a+4,b+2)+POINT(a+2,b)*POINT(a+2,b+4))*(0=POINT((a+x)\2+2,(b+y)\2+2))
IF((0=POINT(a+2,b+2))+c)*(a>=0)*(b>=0)*(a<5*w)*(b<5*h)THEN k=k+1 ELSE IF t(k)>0GOTO 4 ELSE t(k)=-1:k=k-1
GOTO 1
6a=x+5*((r=2)-(r=4))
b=y+5*((r=1)-(r=3))
RETURN
7LINE(x+1,y+1)-(x+3,y+3),7,B
PSET(x+2,y+2),1
RETURN
9

```

Example output for inputs `10, 10, 100`, actual size:

A still fancier version can be found in this gist. Besides being ungolfed and thoroughly commented, it scales up the output by a constant factor and allows for a set delay between steps, enabling you to watch the DFS algorithm at work. Here's an example run:
> 2 votes

---
Tags: code-golf, graphical-output, random, grid
---