title: Print the alphabet four times

text:
# Question
Title: Print the alphabet four times
The program must print the alphabet four times: first in the normal alphabetical order, second in the order of a qwerty keyboard, third in the order of a dvorak keyboard, and lastly in reverse alphabetical order. The output should resemble this:

```
abcdefghijklmnopqrstuvwxyz
qwertyuiopasdfghjklzxcvbnm
pyfgcrlaoeuidhtnsqjkxbmwvz
zyxwvutsrqponmlkjihgfedcba

```

The output is not case-sensitive, and you can add or omit newlines or spaces wherever you wish.

**The catch**: the program must be less than 104 characters, or, in other words, smaller than the length of the alphabet times four.

I will accept the answer with the shortest code, unless I see something really clever or interesting that I am more impressed with.

EDIT: I will accept the shortest answer on Wednesday, 4/27/2011.

EDIT2: **And the winner is** (as usual) Golfscript in 64 chars! Second place, which is behind by only three chars, is also in Golfscript, with 67 chars, followed by Bash in third place with 72 chars.

But there were a few others I wanted to mention, such as this one, which, depending on your definition, only used 52 "characters", and this one where he wrote it in a language he created.

There were a few people who broke an unwritten rule and did not qualify, but I will mention them just for their way of thinking without the box.

# Answer
> 16 votes
# PHP, 99 bytes

As ISO 8859-1:

```
<?=base64_encode("i·yø!9%z)ª»-ºü1Ë:°z»rº*)jÇ_ä<\½¹æ§'àr¹Z¡ë¢vg²¨äÅ¹°¿<òÇî¶Êê¦æHâÞuÆÚ");

```

To reproduce reliably,

```
printf '<?=base64_encode("' >| 4times.php
printf abcdefghijklmnopqrstuvwxyzqwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvzzyxwvutsrqponmlkjihgfedcba | base64 -d >> 4times.php
printf '");' >> 4times.php

```

# Answer
> 16 votes
# Python 2, 97 characters

```
q="qwertyuiopasdfghjklzxcvbnm"
a="".join(sorted(q))
print a,q,"pyfgcrlaoeuidhtnsqjkxbmwvz",a[::-1]

```

Sorting QWERTY and converting back from list to string is shorter than the alphabet itself!\*

Another option for generating the alphabet in fewer characters than the alphabet itself:

```
print map(chr,range(65,91))

```

Although this prints a Python list of characters.

There's not much to be done here in the way of data compression; jamming the letters into 5 bits only saves 39 characters, which isn't a lot if you then have to un-jam them (and you still have to represent the bytes literally); it looks like zlib (just as an example) saves fewer than 20 bytes; encoding the sequence as a list of deltas to the next letter still takes 5 bits for each delta, because the largest in this sequence is -22:

```
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
 1, 1, 1, 1, 1, 1, 1, -9, 6, -18, 13, 2, 5, -4, -12, 6,
 1, -15, 18, -15, 2, 1, 2, 1, 14, -2, -21, 19, -20, 12,
 -1, 3, 9, -19, 1, -4, 15, -6, -11, 14, -10, 16, -12, -5,
 4, 12, -6, 5, -2, -7, 1, 13, -22, 11, 10, -1, 4, 0, -1,
 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]

```

---

<sub>* Although only slightly.</sub>

# Answer
> 10 votes
## Ruby 1.9, 88 87 84 80

```
puts b=[*?a..?z],:qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz,b.reverse

```

# Answer
> 10 votes
## Bash, 82

```
echo {a..z}
echo qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz
echo {z..a}

```

# Answer
> 9 votes
## Python, 97 96 "characters"

Taking your use of the word "characters" liberally, here's some python that uses 16-bit unicode characters to encode 3 normal characters each. The program is a total of 96 characters, 35 of which are the weirdest unicode characters I've ever seen.

```
for i in range(104):print chr((ord(u'ࠠᒃ⃦ⵉ��割廕��匓�เ᳅ⵉૹ�懬ࣅű傎ᱨ�⤰〷�弙劶��ⶍKᓇࡤ^A'[i/3])>>i%3*5&31)+97),

```

I'm not sure the unicode garbage will come though correctly, so here's a python program to generate the above python program:

```
#!/usr/bin/python
import codecs
f=codecs.open('alpha.py','w','utf-8')
f.write('#!/usr/bin/python\n')
f.write('# coding=utf-8\n')
f.write('for i in range(104):print chr((ord(u\"')
S='''abcdefghijklmnopqrstuvwxyzqwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvzzyxwvutsrqponmlkjihgfedcbaa'''
for i in xrange(0,104,3):
 n=32*32*(ord(S[i+2])-97)+32*(ord(S[i+1])-97)+ord(S[i+0])-97
 f.write(u'%c'%n)
f.write('"[i/3])>>i%3*5&31)+97),\n')

```

# Answer
> 9 votes
### Golfscript, 64 chars

```
"qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz".$2%\1$-1%

```

Note: also 64 bytes. Actually, playing with Unicode and base changes seems counterproductive because `base` is too long a keyword.

# Answer
> 8 votes
## Bash, 72

```
echo {a..z} qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz {z..a}

```

EDIT: removed `tr -d`.

Credits: Alexander, Roger.

# Answer
> 6 votes
## Windows PowerShell, 89

Not particularly good, but at least shorter than the output string:

```
[char[]](65..90)
'qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz'
[char[]](90..65))

```

Way shorter now that I saw that there is a relaxation on whitespace. And a little shorter still, if I ignore case which I'm allowed to.

# Answer
> 5 votes
## Golfscript, ~~76~~, 67 chars

```
123,97>+."qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz"\-1%

```

# Answer
> 4 votes
## CI \- 92 chars

```
'a(1p'z((,0(4d)(.$)<)$)(0c0c.1+2p$.)>)$)qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz

```

CI ("Compiler/Interpreter") is a simple stack-based language I created for the "Self-Interpreting Interpreter" challenge (link to answer). I posted that answer about two hours before this challenge was posted. It's no GolfScript (which I still haven't gotten around to learning), as my goal was to make the interpreter short.

This program must be passed to the `ci` interpreter through standard input. The interpreter treats characters after a terminating `)` as input to the program. My language doesn't support string literals, so stdin is taking its place.

# Answer
> 3 votes
Python 2.7.X - 103 characters ironically...

```
a='abcdefghijklmnopqrstuvwxyz'
print a,'qwertyuiopasdfghjklzxcvbnm pyfgcrlaoeuidhtnsqjkxbmwvz',a[::-1]

```

As it turns out, generating the alphabet in python takes more characters than hard-coding it. As does importing the alphabet. Gotta love a readability-centered language sometimes.

# Answer
> 3 votes
# C - 163 135 chars

This doesn't meet the requirements as it clocks in at over 104 characters, but it was fun to make. Maybe someone will have some suggestions.

```
main(i){char a[105];strcpy(&a[26],"qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz");for(i=0;i<26;)a[i]=a[103-i]=i+++65;puts(a);}

```

This compiles on GCC 4.5.1 (others untested). Yay for omitting #includes, return types, and variable declarations! Hardcoding would've resulted in a shorter program, but that isn't any fun.

Whitespaced version:

```
main(i) {
    char a[105];
    strcpy(&a[26], "qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz");
    for(i=0;i<26;)
        a[i]=a[103-i]=i+++65;
    puts(a);
}

```

## C - 124 122 lame

Here is the lame hardcoded version, and it still doesn't make the cut.

```
main(){puts("abcdefghijklmnopqrstuvwxyzqwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvzzyxwvutsrqponmlkjihgfedcba");}

```

# Answer
> 3 votes
# C — 133 chars

Shortened version from Casey:

```
main(i){char a[105];strcpy(a+26,"qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz");for(i=0;i<26;)a[i]=a[103-i]=i+++65;puts(a);}

```

Whitespaced:

```
main(i) {
    char a[105];
    strcpy(a+26, "qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz");
    for(i=0;i<26;)
        a[i]=a[103-i]=i+++65;
    puts(a);
}

```

### Transposed output

Here is a version that does transposed output, for fun. 134 chars.

```
main(i){char*a="qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz";for(i=0;i<26;i++,a++)printf("%c%c%c%c\n",i+65,*a,*(a+25),90-i);}

```

Whitespaced:

```
main(i){
  char*a="qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz";
  for(i=0;i<26;i++,a++)
    printf("%c%c%c%c\n",i+65,*a,*(a+25),90-i);
}

```

Prints:

```
AqmZ
BwpY
CeyX
DrfW
EtgV
FycU
GurT
HilS
IoaR
JpoQ
KaeP
LsuO
MdiN
NfdM
OghL
PhtK
QjnJ
RksI
SlqH
TzjG
UxkF
VcxE
WvbD
XbmC
YnwB
ZmvA

```

# Answer
> 3 votes
# Lua — 111 characters

Beats C and C++! :-)

```
print'abcdefghijklmnopqrstuvwxyzqwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvzzyxwvutsrqponmlkjihgfedcba'

```

### "Clever" version in Lua

129 characters

```
q='qwertyuiopasdfghjklzxcvbnm'a={q:byte(1,-1)}table.sort(a)a=q.char(unpack(a))print(a,q,'pyfgcrlaoeuidhtnsqjkxbmwvz',a:reverse())

```

Whitespaced:

```
q='qwertyuiopasdfghjklzxcvbnm'
a={q:byte(1,-1)}
table.sort(a)
a=q.char(unpack(a))
print(a,q,'pyfgcrlaoeuidhtnsqjkxbmwvz',a:reverse())

```

# Answer
> 3 votes
**J**

```
x=:(97+/i.26){a.
x
261329910883437428257896643x A.x
247073478763191548160234722x A.x
(_1+/-i.26){x

```

My first experience with J. The idea is simply to use the canonical (lexicographic) number of the required permutation; unfortunately this takes more characters than hard-coding it. But if one could find some arithmetic expression (using powers and whatnot) yielding the magic numbers, it could be shortened.

# Answer
> 3 votes
## Python, 90 unicode chars

```
#coding:u8
print u"扡摣晥桧橩汫湭灯牱瑳癵硷穹睱牥祴極灯獡晤桧歪穬捸扶浮祰杦牣慬敯極桤湴煳歪扸睭究祺睸當獴煲潰浮歬楪杨敦捤慢".encode("u16")[2:]

```

run at ideone - http://ideone.com/R2dlI or codepad - http://codepad.org/lp77NL9w

# Answer
> 3 votes
**Javascript 139 121**

new:

```
q='qwertyuiopasdfghjklzxcvbnm'
a=q.split('').sort()
alert(a.join('')+q+'pyfgcrlaoeuidhtnsqjkxbmwvz'+a.reverse().join(''))

```

old:

```
a=[]
a[26]='qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz'
for(i=0;i<26;i++)a[i]=a[52-i]=String.fromCharCode(i+65)
alert(a.join(''))

```

# Answer
> 3 votes
# Vyxal `j`, 26 bytes

```
kak•ṅ«
ċ↓U→u°⟇Ȯ≤Ṙ]1biẊ«kzW

```

Try it Online!

-3 thanks to @A username

# Answer
> 2 votes
## PHP 88 bytes

```
<?=$a=join(range(a,z)),~Žˆš‹†Š–žŒ›™˜—•”“…‡œ‰‘’†™˜œ“žšŠ–›—‹‘ŒŽ•”‡’ˆ‰…,strrev($a);

```

# Answer
> 2 votes
# J - 69 char

```
'pyfgcrlaoeuidhtnsqjkxbmwvz'(,~|.)&(,\:~)'mnbvcxzlkjhgfdsapoiuytrewq'

```

Explanation:

* `(,\:~) y` \- Sort `y` in descending order (`\:~`), and append (`,`) that to `y`.
* `x (,~|.) y` \- Reverse (`|.`) `y`, and append that to the front of `x`.
* `x F&G y` \- Execute `(G y) F (G y)`, that is, perform `F` on the results of applying `G` to the arguments.

So, all together, we append the alphabet, backwards, to both the Dvorak and reverse-QWERTY strings, then reverse the QWERTY/alphabet one and put that in front of the Dvorak/alphabet one.

# Answer
> 2 votes
# Bash, 64

I'm very late to the party, but I have a 64 character solution. Program needs to be saved to disk to work

```
echo {a..z} $(sed 1d $0|base64) {z..a};exit
««·+¢¢–¬uø!ŽIsÅËÛžjr~+•ªº'a¶{*ŽL[›ó

```

**How it works:**

`{a..z}` and `{z..a}` are pretty self explanatory, but basically that just prints every character in that respective range.

`$(sed 1d $0|base64)` outputs the program, ignores the first line, then passes it through a base64 encoder (as some other examples have done).

**The reason this is shorter than other similar examples...**

...is because the `{a..z}` ranges are shorter than base64 encodings, so I only need to base64 encode half the string. And because I'm reading the binary data from file rather than storing it in a string, I don't need to escape any character in code.

**How to recreate this script:**

If the code doesn't copy/paste correctly from Stack Exchange to your text editor then run the following in your command line (shell agnostic):

```
echo 'echo {a..z} $(sed 1d $0|base64) {z..a};exit' > alphabetgolf
echo 'qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz' | base64 -d >> alphabetgolf

```

Then to run:

```
bash alphabetgolf

```

# Answer
> 2 votes
# Deorst, 39 bytes

```
EfEuE|'pyfgcrlaoeuidhtnsqjkxbmwvz'EfVE;

```

Try it online!

How on Earth is Deorst beating everything bar Jelly???

## How it works

```
Ef             - Push the lowercase alphabet
  EuE|         - Push 'qwerty…vbnm'
      '…'      - Push that string
         Ef    - Push the alphabet
           VE; - Reverse and concatenate

```

# Answer
> 2 votes
# 05AB1E, 25 bytes

```
AžW.•8t”a$äJÚ₁вƒüu¯Cê•AR»

```

Try it online!

## Explanation

```
A                          # Push alphabet
 žW                        # Push qwerty string
   .•8t”a$äJÚ₁вƒüu¯Cê•     # Push compressed dvorak string
                      AR   # Push reversed alphabet
                         » # Join entire stack with newlines

```

# Answer
> 1 votes
## C++

It's kind of sad when the shortest way to do something in a language is to hard-code it.

```
#include <iostream>

int main()
{
 std::cout<<"abcdefghijklmnopqrstuvwxyzqwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvzzyxwvutsrqponmlkjihgfedcba";
}

```

# Answer
> 1 votes
# J (77)

```
(,|.@(26&{.))(,~/:~@(26&{.))'qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz'

```

Shaved off 3 characters by using a variable:

```
(,|.@a)(,~/:~@(a=.26&{.))'qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz'

```

Shaved off 2 more characters by using a value-level approach:

```
(|.a),~t,~a=./:~26{.t=.'qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz'

```

# Answer
> 1 votes
# Haskell (95)

```
main=putStr$['a'..'z']++"qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz"++['z','y'..'a']

```

# Perl (51)

There's no rule that says I can't.

```
use LWP::Simple;print get("http://bit.ly/fGkflf");

```

# Answer
> 1 votes
## Q (68)

```
.Q.a,"qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz",(|:).Q.a

```

Outputs:

```
"abcdefghijklmnopqrstuvwxyzqwertyuiopasdfghjklzxcvbnmpyfg
crlaoeuidhtnsqjkxbmwvzzyxwvutsrqponmlkjihgfedcba"

```

Tried to find an improvement on hard-coding the middle two but didn't come up with one.

# Answer
> 1 votes
# K - 69 char

```
b,a,|b:a@<26#a:"qwertyuiopasdfghjklzxcvbnmpyfgcrlaeouidhtnsqjkxbmwvz"

```

Explanation:

* `26#a:` \- Assign the two keyboard layouts to `a`, and then take the first 26 characters.
* `b:a@<` \- Sort `a` and assign that to `b`: `<` provides the permutation for an ascending sort, and `@` lets us index `a` in order to sort it.
* `b,a,|` \- Append in a row `b`, then `a`, then the reverse (`|`) of `b`.

# Answer
> 1 votes
# Pyth, 57

```
G"qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz"VG

```

Alphabet, string, reversed alphabet. G is the alphabet. Print is implicit.

# Answer
> 1 votes
# Dyalog APL, 60 bytes

```
⎕A'QWERTYUIOPASDFGHJKLZXCVBNMPYFGCRLAOEUIDHTNSQJKXBMWVZ',⌽⎕A

```

Prints:

```
  ABCDEFGHIJKLMNOPQRSTUVWXYZ  QWERTYUIOPASDFGHJKLZXCVBNMPYFGCRLAOEUIDHTNSQJKXBMWVZ ZYXWVUTSRQPONMLKJIHGFEDCBA

```

Which is permitted as per OP:

> The output is not case-sensitive, and you can add or omit newlines or spaces wherever you wish.

# Answer
> 1 votes
# Jelly, 36 bytes

```
Øa;Øq;“pyfgcrlaoeuidhtnsqjkxbmwvz”;U

```

Try it online!

**Explanation:**

```
Øa;Øq;“pyfgcrlaoeuidhtnsqjkxbmwvz”;U    |
Øa;                                     | alphabet
   Øq;                                  | list with all rows of the qwerty keyboard
      “pyfgcrlaoeuidhtnsqjkxbmwvz”;     | string
                                   U    | reverse

```

# Answer
> 1 votes
# 05AB1E, ~~60~~ 59 bytes

```
AÂ"qwertyuiopasdfghjklzxcvbnm""pyfgcrlaoeuidhtnsqjkxbmwvz"»

```

Try it online!

\- pushes the bifurcated alphabet.

`"qwertyuiopasdfghjklzxcvbnm""pyfgcrlaoeuidhtnsqjkxbmwvz"` \- Pushes qwerty and drovak.

`»` \- Prints stack.

# 05AB1E, 57 bytes (If you don't care about random \n)

```
AÂ"qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz"»

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 24 bytes

```
AžWDS•{2εFƵIƶsðÖz•.IJAR»

```

Try it online!

# Answer
> 1 votes
# Scratch, 103 bytes (w/ Costume Names)

Try it Online!
It would be impossible to do within the constraints without costume or backdrop names, so this is what you get! The sprite has 5 costumes, whose names are , `abcdefghijklmnopqrstuvwxyz`, `qwertyuiopasdfghjklzxcvbnm`, `pyfgcrlaoeuidhtnsqjkxbmwvz`, and `zyxwvutsrqponmlkjihgfedcba`. Being at the byte limit was a complete coincidence, but with such methods, it's as small as it can be! Alternatively, 7 blocks.

```
when gf clicked
delete all of[A v
switch costume to[ v
repeat(4
next costume
add(costume[name v])to[A v

```

## Explanation

```
when gf clicked             Initiates code
delete all of[A v           Clears the list of alphabets
switch costume to[ v        Switches to the first costume
repeat(4                    Loops code for each alphabet
next costume                Changes the costume, and therefore the costume name
add(costume[name v])to[A v   Adds the name of the current costume to the list

```

# Answer
> 0 votes
# Bash, 109

```
a(){ printf "$@";}
v=`a "\%o" {97..122}`
a $v
a qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz
a $v|rev

```

Output:

```
abcdefghijklmnopqrstuvwxyzqwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvzzyxwvutsrqponmlkjihgfedcba

```

# Answer
> 0 votes
# Mouse-2002, 99 bytes

```
65i:(i.h.<^i.!'i.1+i:)"qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz"(i.64>^i.!'i.1-i:)

```

Self-explanatory.

# Answer
> 0 votes
# RProgN, 62 Bytes Noncompeting

```
a S . "qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz" a

```

I'm a bit disappointed RProgN didn't exist at the time of this question. It could have won something!

Try it Online!

# Answer
> 0 votes
**Scala, 128 Bytes**

*Not golfy enough, but readable :)*

```
val l=("qwertyuiopasdfghjklzxcvbnm","pyfgcrlaoeuidhtnsqjkxbmwvz");List(l._1,l._1.sorted,l._2,l._2.sorted.reverse).mkString("\n")

```

# Answer
> 0 votes
# Jelly, 25 bytes

```
Øa;Øq;“¡®×Ṫ}Æ¬#Q>Ẉṛ’œ?$;Ṛ

```

Try it online!

# Answer
> 0 votes
# Subleq (8-bit word), 87 bytes,

```
4  52 6
52 -1 3
4 27 0
32 -1 12
4  9 15
4 30 9
52 -1 21
31  52 24
4  28 18
-25 -25 -1
-54 1
10
113 119 101 114 116 121 117 105 111 112  97 115 100
102 103 104 106 107 108  96 120  99 118  98 110 109 10
112 121 102 103  99 114 108  97 111 101 117 105 100
104 116 110 115 113 106 107 120  98 109 119 118 122 10

```

Subleq Emulator

Could shave 3 bytes off removing the line feeds but I like it better this way.

## Explanation

```
  4  52  6   ' 0: 52: = 52: + 1 # 52: is the z in the qwerty string and is serving double duty
             '    as the output letter for the 1st and 4th lines
 52  -1  3   ' 3: output char(52:) # This line will output the 1st line
  4  27  0   ' 6: 27: = 27: + 1 if 27: <= 0 goto 0 # 27: is initialized to -25
 32  -1 12   ' 9: output char(32:) # the 32 will be incremented every time through the loop.
             '    This line will output the 2nd and 3rd lines
  4   9 15   '12: 9: = 9: + 1
  4  30  9   '15: 30: = 30: + 1 if 30: <= 0 goto 9 # 30: is initialized to -54
 52  -1 21   '18: Output char(52:) # This line will output the 4th line
 31  52 24   '21: 52: = 52: - 1
  4  28 18   '24: 28: = 28: + 1 if 28: <= 0 goto 18 # 28: is initialized to -25
-25 -25 -1   '27: When execution reaches this point this instruction will be 1 1 -1 which will exit
-54   1      '30: & 31: data for loops
 10          '32: to 86: data for the 2nd and 3rd lines
113 119 101 114 116 121 117 105 111 112  97 115 100
102 103 104 106 107 108  96 120  99 118  98 110 109 10
112 121 102 103  99 114 108  97 111 101 117 105 100
104 116 110 115 113 106 107 120  98 109 119 118 122 10

```

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


title: Make a move on a Go board

text:
# Question
Title: Make a move on a Go board
You are given a board position for a Go game and a move to play. You need to output whether the move is legal or not, and the new board position if it is legal.

A brief explanation of Go moves: the game consists of alternatively placing black and white pieces ("stones") in empty places on a square board. Sets of pieces of the same color that are connected to each other (4-way) are called groups. Empty places on the board that are adjacent to a group (also 4-way) are considered to be that group's "liberties". A group with 0 liberties is captured (removed from the board). A move that would cause its own group to be captured ("suicide") is illegal, unless it is capturing one or more opponent's groups (gaining liberties in the process so it is not actually captured).

For those concerned, you don't need to deal with ko (and superko), i.e. you can assume a ko capture is legal. If you don't know what that means, just follow the rules above and it will be fine.

**Input:** a number n between 2 and 19 (inclusive) representing the board size, followed by n lines of n numbers between 0 and 2 (inclusive) representing the board position, followed by 3 numbers separated by space, representing the move to make. In the board position, 0 means empty place, 1 means black stone and 2 means white stone. The move gives the column, the row and the color (1 or 2) of the stone to place. The column and row are 0-based, ranging from 0 to n-1 (inclusive) and counted in the same order as the board input.

You can assume that the given board position is legal (all groups have at least one liberty).

**Output:** a line containing 1 or 0 (or true/false if you prefer) if the move is legal or not, followed (only in case of a legal move) by the new board position in the same format as the input.

**Score:** Number of bytes of the complete source code, smaller is better. 20% additional penalty for use of non-ascii characters, and 20% additional penalty if your code can't be tested in Linux using freely available software.

**Rules:** No network connections and no 3rd party libraries. Your program should use the standard input and output streams, or the standard equivalent for your programming language.

**Examples:**

```
1) Input:

2
10
01
1 0 2

Output:

0

2) Input:

2
10
11
1 0 2

Output:

1
02
00

3) Input:

5
22122
22021
11211
02120
00120
2 1 1

Output:

1
00100
00101
11011
02120
00120

4) Input:

6
000000
011221
121121
122221
011110
000000
4 0 1

Output:

1
000010
011221
121121
122221
011110
000000

```

# Answer
> 3 votes
# Python 3 (~~557~~ ~~504~~ 488)

```
import sys
s=sys.stdin
M=int(next(s))+1
j=Z=M*M-M
S=s.read(Z)
P=0
b=[0]*3
while j>0:j-=1+(j%M<1);b[int(S[j])]|=1<<j;P|=1<<j
N=lambda x:(x<<1|x>>1|x<<M|x>>M)&P&~x
def h(a,b):t=a|N(a)&b;return h(t,b)if t!=a else a
c,r,m=map(int,next(s).split())
o=m%2+1
p=1<<M*r+c
b[m]|=p
for n in(p<<1,p>>1,p<<M,p>>M):
 e=h(n&P,b[o])
 if~b[m]&N(e)<1<=n&b[o]:b[o]&=~e
_,B,W=b
g=~b[o]&N(h(p,b[m]))>=1>~_&p
print(+g)
q=''
while j<Z:
 r=1<<j
 if g*j%M>M-2:print(q);q=''
 else:q+='012E'[(r&B>0)+(r&W>0)*2]
 j+=1

```

Uses 3 bitfields to represent the board - one each for black, white, and empty spaces. Makes the find neighbors `N` and get chain `h` operations very concise.

An ungolfed version with lots of comments: https://gist.github.com/airfrog/8429006

# Answer
> 2 votes
## Python (~~912~~1004)

```
def o():
 n=int(raw_input(''))
 i=[raw_input('') for r in range(n+1)]
 b=[map(int,list(r)) for r in i[:n]]
 u,v,w=map(int,i[n].split(' '))
 if b[v][u]!=0:return 0
 b[v][u]=w
 if w==1:q=2
 elif w==2:q=1
 else:return 0
 f=[[],[],[]]
 h=[[],[],[]]
 g=[range(z*n,(z+1)*n) for z in range(n)]
 d=[(1,0),(-1,0),(0,1),(0,-1)]
 m=lambda z:max(0,min(n-1,z))
 t=[0,1,2,0,1]
 for j,s in enumerate(t):
  for r in range(n):
   for c in range(n):
    for y,x in map(lambda p:(m(r+p[0]),m(c+p[1])),d):
     if s==0:
      if b[y][x]==b[r][c]:
       if g[y][x]!=min(g[y][x],g[r][c]):
        t.insert(j+1,0)
       g[y][x]=g[r][c]=min(g[y][x],g[r][c])
     elif s==1:
      if g[r][c] not in h[b[r][c]]:
       h[b[r][c]].append(g[r][c])
      if b[y][x]==0 and g[r][c] not in f[b[r][c]]:
       f[b[r][c]].append(g[r][c])
    if s==2:
     if b[r][c]==q and g[r][c] not in f[b[r][c]]:
      b[r][c]=0
 h[w].sort()
 f[w].sort()
 if h[w]!=f[w]:return 0
 return "1\n"+'\n'.join([''.join(map(str,r)) for r in b])
print o()

```

Walk through: parse input, check if move is on an empty spot, make move, init "group" grid, simplify/minimize group grid by checking color of adjacant stones (s=0) **and keep repeating until it is fully minimized**, check for group liberties (s=1), remove opponent stones for groups with no liberties (s=2), repeat s=0 and s=1, check that all player groups have liberties, return result.

This can probably be shortened significantly...

~~Interactive~~ Example runs:

```
2
10
01
1 0 2
0

2
10
11
1 0 2
1
02
00

5
22122
22021
11211
02120
00120
2 1 1
1
00100
00101
11011
02120
00120

6
000000
011221
121121
122221
011110
000000
4 0 1
1
000010
011221
121121
122221
011110
000000

```

# Answer
> 2 votes
# Python 3.8: 480 479 424 359/366 344/351 bytes

Inspired by airfrog's accepted answer. Try it online!

```
o=open(0)
r=o.read
m=int(o.readline())+1
C=[*r(m*m-m)]+[' ']*m
y,x,c=map(int,r().split())
N=lambda p:[p+1,p-1,p+m,p-m]
p=x*m+y
C[p]=c
s=lambda P,c:[S(P,'0'),any((C[R]=='0')|(t[R]==str(c)and[S(R,'0'),s(R,c)][1])for R in N(P))][1]
for P in N(p):
 if C[P]==str(3-c):t=C[:];S=t.__setitem__;s(P,3-c)or(C:=t[:])
print(n:=s(p,c))
if n:print(*C,sep='')

```

(change last line to `if n:print(*C[-m-1],sep='')` if trailing spaces not allowed)

## Older/slightly-different ungolfed version with comments:

```
from copy import deepcopy
n = int(input())

in_ = lambda x,y: x>=0 and x<n and y>=0 and y<n
neighbors = lambda x,y: [(x+dx, y+dy) for dx, dy in ((0,1),(0,-1),(1,0),(-1,0)) if in_(x+dx,y+dy)]

chars = [[*map(int, input())] for i in range(n)]
y,x,c = map(int, input().split())
chars[x][y] = c

def search(xx,yy,c):
    global chars
    tmp = deepcopy(chars)
    cue = [(xx, yy)]
    tmp[xx][yy] = 0
    nolib = True  # no liberty?
    while cue:
        xx,yy = cue.pop()
        for xxx,yyy in neighbors(xx,yy):
            if tmp[xxx][yyy]==c:
                cue.append((xxx,yyy))
                tmp[xxx][yyy] = 0
            elif chars[xxx][yyy]==0:
                nolib = False

    if nolib: chars = deepcopy(tmp)
    return nolib

for xx,yy in neighbors(x,y):
    if chars[xx][yy]==3-c: search(xx,yy,3-c)

if search(x,y,c):
    print(0)
else:
    print(1)
    for row in chars: print(*row, sep='')

```

---
Tags: code-golf, game, board-game, go
---


# Question
Title: Ways to arrange the integers 1 to 9 with operators so that the result is 100
# **Prelude:**

This task is taken from Five Problems Every Software Engineer Should Be Able to Solve in Less Than an Hour, which I really recommend.

# **The task:**

> Write a program that outputs all possibilities to put + or - or nothing between the numbers 1, 2, ..., 9 (in this order) such that the result is always 100.

# **Winning Criteria:**

Shortest code in bytes wins.

# Answer
> 13 votes
# Perl 5.10.0 - ~~50~~ ~~46~~ 45B

```
say for grep{eval==100}glob join'{,+,-}',1..9

```

Usage: `perl -M5.10.0 scratch.pl` (I think I get the version for free)

# Answer
> 4 votes
# CJam, ~~43~~ 40 bytes

```
"-"SL]8m*{A,2>.+1\+s}%{~]:+100=},N*S/'+*

```

Here is how it works:

```
"-"SL]                     e# This is an array containing -, space and empty character
                           e# This represents -, + and joints correspondingly
      8m*                  e# Get all cartesian products of these 3 strings of length 8
                           e# For instance, all cartesian products of length 2 are:
                           e# [["-" " "] ["-" "-"] ["-" ""] [" " " "] [" " "-"] [" " ""]
                           e# ["" " "] ["" "-"] ["" ""]]
         {          }%     e# Map these cartesian products over this loop
          A,2>             e# Get array [2, 3, 4, 5, 6, 7, 8, 9]
              .+           e# In-order concatenation of the above two arrays
                1\+s       e# Prepend 1 to the result from above and convert it to string
{        },                e# Now we have all possible strings of 1 to 9 with all possible
                           e# operators as well as joins (things like 567). Its time to
                           e# filter out what add up to 100
 ~                         e# Evaluate the string. This leaves some numbers on stack.
  ]:+                      e# Wrap those numbers in an array and take their sum
     100=                  e# Check if the sum is equal to 100
           N*              e# Join all filtered strings by newline
             S/'+*         e# We used space instead of +. So now we replace space with +

```

Try it online here

# Answer
> 3 votes
My shot at this:

# Python 2, 93 bytes

```
def a(e,i):
 if i<=9:[a(e+x+`i`,i+1)for x in("+","-","")]
 elif eval(e)==100:print e
a("1",2)

```

# Answer
> 2 votes
# Mathematica, ~~93~~ 92 bytes

```
Print/@Select[""<>ToString/@Range@9~Riffle~#&/@{"+","-",""}~Tuples~{8},ToExpression@#==100&]

```

Fairly straightforward: generates all possible strings using `Tuples` and then filters them.

For reference, I get:

```
1+2+3-4+5+6+78+9
1+2+34-5+67-8+9
1+23-4+5+6+78-9
1+23-4+56+7+8+9
12+3+4+5-6-7+89
12+3-4+5+67+8+9
12-3-4+5-6+7+89
123+4-5+67-89
123+45-67+8-9
123-4-5-6-7+8-9
123-45-67+89

```

# Answer
> 2 votes
# Pyth, 26 bytes

```
fqvT100m+ssC,r1Td9^c3"+-"8

```

First, we generate all 8 element combinations of \["+", "-", ""\]. `c3"+-"` chops `"+-"` into 3 rougly equal sied pieces, giving the appropriate list. `^c3"+-"8` gives the 8 element combinations.

Then, we greate the arithmetic sequences. `C,r1Td` zips together the operators with the numbers 1 through 8, which are then summed twice to give the string, and `+ ... 9` puts a 9 at the end.

Finally, `fqvT100` filters for those expressions which evaluate to 100.

---

The update to the interpreter which allowed this code to work was this one, which was made about a day before this question was asked, so this code would have only worked on the command line compiler, not the online one, when the question was asked.

Demonstration.

# Answer
> 1 votes
# JavaScript, 86 ~~92~~

Head to head with the best. That must be an anomalous problem.

**Edit** -6 thx @nderscore

```
for(i=6562;k=--i;eval(o)-100||alert(o))for(j=o=1;j++<9;k=k/3|0)o+=k%3?' +-'[k%3]+j:[j]

```

Test in any browser console, it pops up just 11 times.

Or this snippet:

```
function out(x) { OUT.innerHTML = OUT.innerHTML + '\n' + x; }

// 6562 is 3 powered to 8 +1
for(i=6562;k=--i;eval(o)-100||out(o))
  for(j=o=1;j++<9;k=k/3|0)
    o+=k%3?' +-'[k%3]+j:[j]

```

```
<pre id=OUT></pre>
```

# Answer
> 1 votes
# K, ~~61~~ 50 bytes

```
t@&100=.:'t:{:[x>9;,y;,/_f[x+1]'(y,"+";y,"-";y),\:$x]}[2;"1"]

```

Tested with Kona.

The general approach is to recursively generate all the expressions and then filter out those which eval (`.`) to 100. This is reasonably competitive as written, but I think there's still room for improvement.

## edit:

```
t@&100=.:'t:(,"1"){,/x,/:\:("+";"-";""),\:$y}/2+!8

```

Altering my approach a bit to be iterative rather than recursive, which removes the need for explicit base cases as well as saving me some brackets.

# Answer
> 0 votes
# Python (176)

39 minutes and counting (for all problems that is)

```
from itertools import*
for i in product(('+','-',''),repeat=8):
 s=''.join(''.join(j)for j in chain(izip_longest(map(str,range(1,10)),i,fillvalue='')))
 if eval(s)==100:print s

```

This could probably be shorter, but this was my actual solution for this problem, just golfed down a bit.

# Answer
> 0 votes
# APL(Dyalog Unicode), ~~54 50~~ 48 bytes SBCS

```
↑b/⍨100=⍎¨b←{' '~⍨,(1↓⎕D),⍪⍵,' '}¨(,∘.,)⍣7⍨'-+ '

```

Try it on APLgolf!

A tradfn submission which uses strict right to left evaluation.

---
Tags: code-golf, recursion
---


title: Scramble a Megaminx!

text:
# Question
Title: Scramble a Megaminx!
# Scramble a Megaminx!

A megaminx is a dodecahedral version of the familiar Rubik's cube. Since 2008, the World Cube Association uses Stefan Pochmann's megaminx scrambler. The scrambles look like this:

```
R-- D++ R++ D-- R++ D-- R++ D++ R-- D-- U'
R++ D-- R++ D-- R-- D++ R-- D-- R-- D-- U'
R++ D++ R-- D++ R++ D++ R++ D++ R-- D++ U
R-- D-- R++ D++ R++ D++ R-- D++ R++ D++ U
R-- D++ R++ D-- R++ D-- R++ D++ R++ D++ U
R++ D++ R++ D++ R-- D-- R-- D-- R-- D-- U'
R-- D++ R-- D++ R++ D++ R++ D++ R++ D++ U

```

A scramble has seven lines. Each line has 10 R and D moves, starting with R and alternating R and D moves. Following each letter is randomly chosen direction `++` or `--` with equal probability. At the end of the line is randomly chosen with equal probability `U` (trailing space form `U`  allowed) or `U'`. A trailing newline at the end of the output is permitted.

Your code must take no input and must produce a random scramble.

# Answer
# Ruby, <sup>~~73~~</sup> 71 bytes

*Saved two bytes thanks to @vrintle (one directly and another with further golfing)*

```
77.times{|i|$><<(~i%11>0?:RD[i%2]+'+-'[rand 2]*2+' ':?U+?'*rand(2)+$/)}

```

Try it online!

`$/` is the input record separator, which is a newline by default.

---

In Ruby 2.7 (newer than the version on TIO), we get 70 bytes using numbered block parameters:

```
77.times{$><<(~_1%11>0?:RD[_1%2]+'+-'[rand 2]*2+' ':?U+?'*rand(2)+$/)}

```
> 4 votes

# Answer
# Python 2, 91 bytes

```
from random import*
for C in[choice]*7:print' '.join(c+C('+-')*2for c in'RD'*5),'U'+C("' ")

```

Try it online!

Alternatively:

```
from random import*
C=choice
exec'print" ".join(c+C("+-")*2for c in"RD"*5),"U"+C("\' ");'*7

```

Try it online!

**Python 2, 92 bytes**

```
from random import*
C=choice
for c in('RD'*5+'U')*7:print c+[C("+-")*2,C("' ")+"\n"][c>"T"],

```

Try it online!

**Python 2, 92 bytes**

```
from random import*
for C in[choice]*7:
 for c in'RD'*5:print c+C('+-')*2,
 print'U'+C("' ")

```

Try it online!
> 4 votes

# Answer
# Perl 5, 68 bytes

```
say+(map{map$_.("++ ","-- ")[rand 2],R,D}0..4),U,"'"x rand 2for 0..6

```

Try it online!
> 3 votes

# Answer
# C (gcc), ~~135~~ ~~132~~ ~~124~~ ~~123~~ 119 bytes

* -12 thanks to ceilingcat
* -1 by rearranging the inner `for` terms

For each line, I start with `R++` and then flip `R`=\>`D` and `++`=\>`--` (half the time). This continues ten times and concludes with either `U` or `U'`. Instead of doing string operations, I use XOR for all the manipulations and print the integer as a reinterpreted string.

```
f(j){long i,k=7;for(srand(time(0));k--;puts(rand()%2?"U'":"U"))for(j=10,i=' ++R';j--;printf(&i))i^=22+rand()%2*394752;}

```

Try it online!
> 3 votes

# Answer
# \[Python 3.6\], 144 121 120 111 bytes

*Huge reduction thanks to Sisyphus, and qwr*

```
from random import*
d=choice
for r in range(35):print(end=f"R{d('-+')*2} D{d('-+')*2} "+r%5//4*f"U{d(' !')}\n")

```

Try it online

Each time through the loop prints one pair of entries, one `R` and one `D`. The `r%5//4*f*` control takes care of conditionally printing the `U` entry and the end of line.
> 2 votes

# Answer
# , 87 bytes

```
s=sample;for(i in 1:7)cat(paste0(c("R","D"),s(c("++","--"),10,T)),s(c("U","U'"),1),"
")

```

Try it online!

's `paste0` function (to paste text strings together without separator) is conveniently vectorized, so we can exploit 's element recycling when the two arguments are different lengths: in this case, the 2-element vector `R,D` is automatically recycled 5 times when `paste0`-ed with the 10-element vector created by `sample`-ing `++,--` ten times. The `T` argument to `sample` indicates that sampling with replacement is `T`rue (needed to take 10 samples from 2-elements).
> 2 votes

# Answer
# Retina, 40 bytes

```

7*$(5*$(R-- D-- )U'¶
/--/_?&K`++
%?&`'

```

Try it online! Explanation:

```

7*$(5*$(R-- D-- )U'¶

```

Insert 7 lines consisting of `R-- D--`  repeated 5 times followed by `U'`.

```
/--/_?&K`++

```

Match each `--` and then randomly replace each one with `++`.

```
%?&`'

```

On each line, randomly delete `'`.
> 2 votes

# Answer
# APL (Dyalog Unicode), 56 bytes

```
''' '[?7/2],⍨'U',⍨7 10⍴,/⍉2 70⍴(2/¨'+-')[?70/2],⍨70⍴'RD'

```

Try it online!
> 2 votes

# Answer
# JavaScript (ES6), 92 bytes

```
f=k=>k>69?'':'RD'[k&1]+((r=Math.random()*4)&1?'++ ':'-- ')+(k%10>8?r&2?`U'
`:`U
`:'')+f(-~k)

```

Try it online!

---

# JavaScript (ES6), 93 bytes

A non-recursive approach.

```
_=>`RDRDRDRDRDU
`.repeat(7).replace(/./g,c=>c+[['++ ','-- ',"'"][Math.random()*2|2*(c>'R')]])

```

Try it online!
> 1 votes

# Answer
# Python 3, ~~113~~ ~~97~~ 126 bytes

Saved 6 bytes thanks to qwr!!!
Added 29 bytes to fix an error kindly pointed out by qwr.

```
from random import*
f=lambda n=5,r=choice:n and f"R{r('-+')*2} D{r('-+')*2} "+f(n-1)or'U'+r(" '")
for i in range(7):print(f())

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 25 bytes

**Credit goes to Kevin Cruijssen for coming up with this way shorter program!**

```
„RDÞε„+-Ωº«}Tôε„U'ηΩª}7£»

```

Try it online!

# How this?

```
„RDÞ                                        # Push RDRDRDRDRDRDRDRDRDRD... as a list
    ε      }                                # For every R or D:
     „+-Ω                                   #   Pick random from + and -
         º                                  #   Double the sign
          «                                 #   And join it to the R or D
            Tô                              # Split the list into pieces of 10 elements
              ε      }                      # For each item in the list:
               „U'ηΩ                        #   Choose a random choice between U' & U
                    ª                       #   Append it to the list
                      7£»                   # Join the first 7 lists with linefeeds
                                            # Print the result at the end (implicitly)!

```

---

My old program:

# 05AB1E, 36 bytes

```
8G„RD5×S"++ -- "3ôTи2ô€ΩøJ…U'U2ôΩªJ,

```

Try it online!

# How that?

```
8G                                          # Repeat 7 times the full code
  „RD5×                                     # Push "RDRDRDRDRD"
        "++ -- "3ô                          # Push the list/array ["++ ", "-- "]
                  Tи2ô                      # Repeat the list 10 times
                      €Ω                    # Pick a random item from each list
       S                øJ        J         # Zip the random items with "RDRDRDRDRD"
                                            # e.g => "R++ D-- R++ D-- R++ D-- R++ D-- R++ D-- "
                          …U'U2ôΩ           # Pick random between "U'" and "U"
                                 ª          # Append the result to the last result
                                  ,         # Print it with a linefeed

```
> 1 votes

# Answer
# Charcoal, 26 bytes

```
Ｅ⁷⪫⮌Ｅ¹¹⎇λ⁺§RDλ×²‽+-…U'⊕‽²

```

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

```
 ⁷                          Literal `7`
Ｅ                           Map over implicit range
     ¹¹                     Literal `11`
    Ｅ                       Map over implicit range
           RD               Literal string `RD`
          §  λ              Indexed by inner index
         ⁺                  Concatenated with
                 +-         Literal string `+-`
                ‽           Random character
              ×²            Duplicated
       ⎇λ                   Except for the first entry use
                    U'      Literal string `U'`
                   …        Truncated to length
                       ‽²   Random integer less than 2
                      ⊕     Incremented
   ⮌                        Reversed (so `U` is now last)
  ⪫                         Joined with spaces
                            Implicitly print on separate lines

```
> 1 votes

# Answer
# Jelly, 34 bytes

```
7µ5,6ṁ11ż2Xx¤€$+0¦2ị“+-' RDU”KFṖ)Y

```

**Try it online!**

### How?

```
7µ5,6ṁ11ż2Xx¤€$+0¦2ị“+-' RDU”KFṖ)Y - Link: no argments
7                                  - seven
 µ                              )  - for each (v in [1..7]):
  5,6                              -   [5,6]
     ṁ11                           -   mould like 11 -> [5,6,5,6,5,6,5,6,5,6,5]
              $                    -   last two links as a monad:
             €                     -     for each:
            ¤                      -       nilad followed by link(s) as a nilad:
         2                         -         two
          X                        -         random integer (from [1,2])
           x                       -         repeat (two) times -> [1,1] or [2,2]
        ż                          -     zip together -> [[5,[2,2]],[6,[1,1],...]
                0¦                 -   apply to index 0 (rightmost):
               +  2                -     add two (e.g. [5,[1,1]] -> [7,[3,3]])
                    “+-' RDU”      -   "+-' RDU"
                   ị               -   index into (i.e. 1 -> '+' ... 7 -> 'U')
                             K     -   join with space characters
                              F    -   flatten
                               Ṗ   -   pop (remove the repeated space or quote from the right)
                                 Y - join with newline characters

```
> 1 votes

# Answer
# Pyth, 28 bytes

```
V7jd+m+@"RD"d*2O"+-"T+\UO" '

```

Try it online!

```
V7jd+m+@"RD"d*2O"+-"T+\UO" '
V7                             Perform the following 7 times:
     m              T          Map d over 0-9:
               O"+-"             Choose + or - at random
             *2                  Double it
       @"RD"d                    Choose R for even d, D for odd
      +                          Concatenate the previous two results
                        O" '   Choose space or ' at random
                     +\U       Append to "U"
    +                          Append the previous result to the list of moves
  jd                           Join the list on spaces, implicit print with newline

```
> 1 votes

# Answer
# MathGolf, ~~24~~ 23 bytes

```
7{ûRD5*môû+-w∞ ûU'1w╛╡n

```

Try it online.

Could be 22 bytes if we're allowed to output in lowercase instead of uppercase, by changing the `ûRD` to `╢x` (and `U'` to `u'`): try it online.

**Explanation:**

```
7{                       # Loop 7 times:
  ûRD                    #  Push string "RD"
     5*                  #  Repeat it 5 times: "RDRDRDRDRD"
       m                 #  Map over each character,
        ô                #  using the following six character as inner code-block:
         û+-             #   Push string "+-"
            w            #   Pop and push a random character from this string
             ∞           #   Double it
                         #   Push a space character " "
               ûU'      '#  Push string "U'"
                  1w     #  Push a random integer in the range [0,1]
                    ╛    #  If this integer is truthy (thus 1):
                     ╡   #   Discard the right character of the string
                      n  #  Push a newline character "\n"
                         # (after the loop, the entire stack joined together is output
                         #  implicitly as result)

```
> 1 votes

# Answer
# Actually, 40 bytes

```
7"RD""35"≈*⌠"+-"Jτ+R⌡M╡⌠2"UU'"╡J@+' j⌡Mi

```

Try it online!

```
 "RD"                                    # Push RD,
     "35"≈*                              # and repeat it 35 times.
           ⌠        ⌡M                   # For each turn,
           ⌠"+-"J   ⌡M                   # pick either + or -,
           ⌠     τ  ⌡M                   # double it,
           ⌠      +R⌡M                   # and add it to the end of each turn.
7                     ╡                  # Split the list into 7 sublists (of length 10).
                       ⌠             ⌡M  # For each sublist,
                       ⌠2"UU'"╡J     ⌡M  # pick either U or U',
                       ⌠        @+   ⌡M  # add it to the end of each turn,
                       ⌠          ' j⌡M  # and join with spaces.
                                       i # Push each sublist to the stack.
                                         # Implicitly output the stack joined with newlines.

```
> 1 votes

# Answer
# Python 3.8 (pre-release), 86 bytes

A golfed version of xnor's answer, which he didn't approved. Perhaps, because his answer is in Python 2.

```
from random import*
for C in[choice]*7:print(*(c+C('+-')*2for c in'RD'*5),'U'+C("' "))

```

Try it online!
> 1 votes

# Answer
# \>\<\>, ~~78~~, 75 bytes

Saved **3 bytes** by modifying the jump in the third line and changing how the register was checked and decremented.

```
7_a*&"DR"d1.  >x"-"v
>x"'"oao&:&?!;^\"+">$:o$:oo$" "od1&1-:&a%?.~~"U"o
.>51

```

New link: Try it online!

Old link: Try it online!

This code also runs in \*\>\<\> (Starfish) because \*\>\<\> is a super set of \>\<\>.

\*\>\<\>: Try it online!
> 1 votes

# Answer
# Vyxal, 25 bytes

```
₀(‛RD5*ƛ‛+-℅d+;\U‛U'"℅JṄ,

```

Try it Online!

## Explanation

```
₀(‛RD5*ƛ‛+-℅d+;\U‛U'"℅JṄ,
 (                         For n
₀                          in range(10):
  ‛RD                        Push "RD"
     5*                      Repeat 5 times
       ƛ      ;              Map:
        ‛+-                    Push "+-"
           ℅                   Choose random
            d                  Double
             +                 Concatenate top two
               \U            Push "U"
                 ‛U'         Push "U'"
                    "        Join top two into a pair
                     ℅       Choose random
                      J      Join top two
                       Ṅ     Join with spaces
                        ,    Print

```
> 1 votes

# Answer
# Nim, 129 bytes

```
import random
randomize()
for _ in 0..6:
 var l=["U","U'"].sample
 for i in 0..9:l="RD"[i mod 2]&["++","--"].sample&" "&l
 echo l

```

Try it online!
> 0 votes

# Answer
# Jelly, ~~28~~ 27 bytes

```
⁵µ⁾RDẋ5;⁾+-XḤ¤$€“U“U'”X¤ṭ)G

```

Try it online!

## Explanation

```
⁵µ⁾RDẋ5;⁾+-XḤ¤$€“U“U'”X¤ṭ)G  Main niladic link
⁵                            10 [implicitly casted to [1..10]]
 µ                       )   Map:
  ⁾RD                          "RD"
     ẋ5                        Repeat 5 times
               €               Map
              $                (
       ;                         Join with
             ¤                   (
        ⁾+-                        "+-"
           X                       Choose random
            Ḥ                      Unhalve (double)
             ¤                   )
              $                )
                        ṭ      Append
                       ¤       (
                “U“U'”           ["U", "U'"]
                      X          Choose random
                       ¤       )
                          G  Format as a grid

```
> 0 votes

---
Tags: code-golf, string, rubiks-cube
---


title: Just Enough Ones

text:
# Question
Title: Just Enough Ones
## Challenge

Given a positive integer \\$n\\$, count the number of \\$n\times n\\$ binary matrices (i.e. whose entries are \\$0\\$ or \\$1\\$) with exactly two \\$1\\$'s in each rows and two \\$1\\$'s in each column.

Here are a few examples of valid matrices for \\$n=4\\$:

```
1100        1100        1100
1100        0011        0110
0011        1100        0011
0011        0011        1001

```

And here are a few invalid matrices:

```
1100
0011
0111    <-- three 1's in this row
1100
 ^
 `--- three 1's in this column

```

```
1111    <-- four 1's in this row
0011
1100
0000    <-- zero 1's in this row

```

This sequence is catalogued on OEIS as A001499. Here are a few non-bruteforce ways to compute it (\\$a\_n\\$ denotes the number of valid \\$n\times n\\$ binary matrices).

* The recursive formula $$ 2a\_n-2n(n-1)a\_{n-1}-n(n-1)^2a\_{n-2}=0 $$ with base cases \\$a\_1=0\\$, \\$a\_2=1\\$.
* The explicit formula $$ a\_n=\frac{(n!)^2}{4^n}\sum\_{i=0}^n\frac{(-2)^i(2n-2i)!}{i!((n-i)!)^2}. $$

You may find other ways to compute this sequence on the OEIS page linked above. To be clear, bruteforcing is a perfectly valid way of solving this challenge.

## Rules

As usual in challenges, your task is to write a program/function which does one of the following (consistently across different inputs).

* Take a positive integer \\$n\\$ as input and return \\$a\_n\\$ as output. Because of the combinatorial interpretation of this sequence, it has to be \\$1\\$-indexed (i.e. you are not allowed to take \\$n\\$ and return \\$a\_{n+1}\\$). If you choose this option, you are not required to handle the input \\$n=0\\$.
* Take a positive integer \\$n\\$ as input and return the list \\$\[a\_1,a\_2,\ldots,a\_n\]\\$ as output. Optionally, you may instead choose to return \\$\[a\_0,a\_1,\ldots,a\_{n-1}\]\\$ or \\$\[a\_0,a\_1,\ldots,a\_n\]\\$, where \\$a\_0=1\\$ (consistent with the combinatorial interpretation). The choice has to be consistent across different inputs.
* Take no input and return the infinite list/generator \\$\[a\_1,a\_2,a\_3,\ldots\]\\$. Optionally, you may instead choose to return \\$\[a\_0,a\_1,a\_2,\ldots\]\\$, where \\$a\_0=1\\$.

Your program/function must theoretically work for arbitrarily large inputs, assuming infinite time, memory and integer/floating point precision. In practice, it's ok if if fails because of integer overflow and/or floating point errors.

# Scoring

This is , so the shortest code in bytes wins.

## Testcases

```
Input                     Output
 1                             0
 2                             1
 3                             6
 4                            90
 5                          2040
 6                         67950
 7                       3110940
 8                     187530840
 9                   14398171200
10                 1371785398200
11               158815387962000
12             21959547410077200
13           3574340599104475200
14         676508133623135814000
15      147320988741542099484000

```

# Answer
# , 41 bytes

```
1#.*:=1#.2>[:>@~.@,[:+&,&.>/~i.@!<@A.=@i.

```

Try it online!

A different take on brute force, which handles up to n=6 on TIO.

Since the idea is more interesting than the J mechanics here, I'll explain that.

I could likely save bytes by translating one of the formulas into J, but that seemed less fun.

## the idea

* Generate all `n!` permutations of the identity matrix. Eg, for n=3:

```
┌─────┬─────┬─────┬─────┬─────┬─────┐
│1 0 0│1 0 0│0 1 0│0 1 0│0 0 1│0 0 1│
│0 1 0│0 0 1│1 0 0│0 0 1│1 0 0│0 1 0│
│0 0 1│0 1 0│0 0 1│1 0 0│0 1 0│1 0 0│
└─────┴─────┴─────┴─────┴─────┴─────┘

```
* Create an "addition table" of this list with itself, using matrix addition:

```
┌─────┬─────┬─────┬─────┬─────┬─────┐
│2 0 0│2 0 0│1 1 0│1 1 0│1 0 1│1 0 1│
│0 2 0│0 1 1│1 1 0│0 1 1│1 1 0│0 2 0│
│0 0 2│0 1 1│0 0 2│1 0 1│0 1 1│1 0 1│
├─────┼─────┼─────┼─────┼─────┼─────┤
│2 0 0│2 0 0│1 1 0│1 1 0│1 0 1│1 0 1│
│0 1 1│0 0 2│1 0 1│0 0 2│1 0 1│0 1 1│
│0 1 1│0 2 0│0 1 1│1 1 0│0 2 0│1 1 0│
├─────┼─────┼─────┼─────┼─────┼─────┤
│1 1 0│1 1 0│0 2 0│0 2 0│0 1 1│0 1 1│
│1 1 0│1 0 1│2 0 0│1 0 1│2 0 0│1 1 0│
│0 0 2│0 1 1│0 0 2│1 0 1│0 1 1│1 0 1│
├─────┼─────┼─────┼─────┼─────┼─────┤
│1 1 0│1 1 0│0 2 0│0 2 0│0 1 1│0 1 1│
│0 1 1│0 0 2│1 0 1│0 0 2│1 0 1│0 1 1│
│1 0 1│1 1 0│1 0 1│2 0 0│1 1 0│2 0 0│
├─────┼─────┼─────┼─────┼─────┼─────┤
│1 0 1│1 0 1│0 1 1│0 1 1│0 0 2│0 0 2│
│1 1 0│1 0 1│2 0 0│1 0 1│2 0 0│1 1 0│
│0 1 1│0 2 0│0 1 1│1 1 0│0 2 0│1 1 0│
├─────┼─────┼─────┼─────┼─────┼─────┤
│1 0 1│1 0 1│0 1 1│0 1 1│0 0 2│0 0 2│
│0 2 0│0 1 1│1 1 0│0 1 1│1 1 0│0 2 0│
│1 0 1│1 1 0│1 0 1│2 0 0│1 1 0│2 0 0│
└─────┴─────┴─────┴─────┴─────┴─────┘

```
* Now we note that the valid items are simply those without a 2 anywhere:

```
┌─────┬─────┬─────┬─────┬─────┬─────┐
│     │     │     │1 1 0│1 0 1│     │
│     │     │     │0 1 1│1 1 0│     │
│     │     │     │1 0 1│0 1 1│     │
├─────┼─────┼─────┼─────┼─────┼─────┤
│     │     │1 1 0│     │     │1 0 1│
│     │     │1 0 1│     │     │0 1 1│
│     │     │0 1 1│     │     │1 1 0│
├─────┼─────┼─────┼─────┼─────┼─────┤
│     │1 1 0│     │     │     │0 1 1│
│     │1 0 1│     │     │     │1 1 0│
│     │0 1 1│     │     │     │1 0 1│
├─────┼─────┼─────┼─────┼─────┼─────┤
│1 1 0│     │     │     │0 1 1│     │
│0 1 1│     │     │     │1 0 1│     │
│1 0 1│     │     │     │1 1 0│     │
├─────┼─────┼─────┼─────┼─────┼─────┤
│1 0 1│     │     │0 1 1│     │     │
│1 1 0│     │     │1 0 1│     │     │
│0 1 1│     │     │1 1 0│     │     │
├─────┼─────┼─────┼─────┼─────┼─────┤
│     │1 0 1│0 1 1│     │     │     │
│     │0 1 1│1 1 0│     │     │     │
│     │1 1 0│1 0 1│     │     │     │
└─────┴─────┴─────┴─────┴─────┴─────┘

```
* But these are not necessarily unique. However, after removing dups, we have our answer, which is 6:

```
┌─────┬─────┬─────┬─────┬─────┬─────┐
│     │     │     │1 1 0│1 0 1│     │
│     │     │     │0 1 1│1 1 0│     │
│     │     │     │1 0 1│0 1 1│     │
├─────┼─────┼─────┼─────┼─────┼─────┤
│     │     │1 1 0│     │     │1 0 1│
│     │     │1 0 1│     │     │0 1 1│
│     │     │0 1 1│     │     │1 1 0│
├─────┼─────┼─────┼─────┼─────┼─────┤
│     │     │     │     │     │0 1 1│
│     │     │     │     │     │1 1 0│
│     │     │     │     │     │1 0 1│
├─────┼─────┼─────┼─────┼─────┼─────┤
│     │     │     │     │0 1 1│     │
│     │     │     │     │1 0 1│     │
│     │     │     │     │1 1 0│     │
├─────┼─────┼─────┼─────┼─────┼─────┤
│     │     │     │     │     │     │
│     │     │     │     │     │     │
│     │     │     │     │     │     │
├─────┼─────┼─────┼─────┼─────┼─────┤
│     │     │     │     │     │     │
│     │     │     │     │     │     │
│     │     │     │     │     │     │
└─────┴─────┴─────┴─────┴─────┴─────┘

```
> 16 votes

# Answer
# JavaScript (ES6), 36 bytes

Returns the \\$n\\$th term of the sequence.

```
f=n=>--n<2?n:-~n*n*(f(n)+n*f(n-1)/2)

```

Try it online!

### How?

We decrement \\$n\\$ right away in order to use the following 0-indexed form of the recursive formula:

* \\$a\_n=n\\$ for \\$0\le n\< 2\\$
* \\$a\_n=(n+1)\times n\times \left(a\_{n-1}+\dfrac{n\times a\_{n-2}}{2}\right)\\$ for \\$n\ge2\\$
> 9 votes

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

```
1ÝλsN*;+NN>P

```

Try it online!

-4 thanks to @ovs, which allowed for another -1

Uses the recursive formula.

```
1Ý        0-based range from 1, pushes [0,1]
λ         recursive context
 s        swap the implicit a(n-1),a(n-2) to a(n-2),a(n-1)
 N*       n*a(n-2)
 ;        /2
 +        +a(n-1)
 NN>      n,(n+1)
 P        product of all elements in stack, (n*a(n-2)/2+a(n-1))*n*(n+1)

```
> 8 votes

# Answer
# Jelly, 15 bytes

```
²Ø.ṗs€µ;Z§=2Ạ)S

```

Try it online!

A monadic link taking an integer and returning an integer. Brute forces it.

## Explanation

```
²               | Squared
 Ø.ṗ            | [0,1] Cartesian power of this
    s€          | Split each of these into lists of the original argument in length
      µ         | Start a new monadic chain
             )  | For each of the possible matrices we’ve generated:
       ;Z       | - Append its transpose
         §      | - Sum each list
          =2    | - Equal to 2 (vectorises)
            Ạ   | - All true
              S | Finally, sum to find the number of matrices meeting the criteria

```

---

As an alternative, here’s an implementation of the recursive formula:

# Jelly, 18 bytes

```
L,²H$×‘Ʋ×Fḣ2S;
Ç¡Ḋ

```

Try it online!

A full program that takes n via STDIN and returns the first `n+1` terms in reverse order. I thought I should be able to shorten it by replacing `\nÇ` with `µ` but that’s not working.

---

Finally, a Jelly translation of @Jonah’s J answer:

# Jelly, 15 bytes

```
=þ`Œ!+þ`ẎQ«Ƒ€1S

```

Try it online!
> 5 votes

# Answer
# Oasis, ~~16 12 14 13~~ 11 bytes

```
àn*t+nn>**T

```

Try it online!

Uses the recursive formula, a port of the 05AB1E answer.
> 5 votes

# Answer
# C (gcc), ~~45~~ 41 bytes

```
f(n){n=n--<3?n:-~n*n*(f(n)+n*f(n-1)/2.);}

```

Try it online!

Inputs a positive integer \\$n\\$ and returns \\$a\_n\\$.
> 4 votes

# Answer
# Factor, ~~83~~ 76 bytes

```
:: f ( n! -- m ) n 1 - n! n n 1 > [ n 1 + * n f n n 1 - f 2 / * + * ] when ;

```

Try it online!

*-7 thanks to @Delfad0r*

This is a translation of @Arnauld's excellent answer.

This is the first time I've submitted a Factor golf where it was shortest to make a named function. Recursion is so much shorter than other solutions that the mandatory function signature is worth it.

Here are some other solutions I tried first, which ended up being longer:

**Brute force, 94 bytes**

```
[ { 0 1 } swap '[ _ selections ] twice [ dup flip [ t [ sum 2 = and ] reduce ] both? ] count ]

```

**Explicit formula, 98 bytes**

```
[| n | n n! sq 4 n ^ / n [0,b] [| i | -2 i ^ 2 n * 2 i * - n! * i n! n i - n! sq * / ] map-sum * ]

```
> 4 votes

# Answer
# APL(Dyalog Extended), 32 bytes SBCS

```
{+/∧/¨(2=+/,+⌿)¨⍵ ⍵∘⍴¨↓⍉⊤⍳2*×⍨⍵}

```

Try it on APLgolf!

A dfn submission which takes a single input on the right.

Straight brute force which exceeds workspace size at n=5.

Uses `⎕IO←0` (0 indexing).

-4 bytes from ovs.

## Explanation

```
{+/∧/¨(2=+/,+⌿)¨⍵ ⍵∘⍴¨↓⍉2⊤¯1+⍳2*×⍨⍵}
                                2*×⍨⍵ 2^(n**2)
                            ¯1+⍳        0-range
                          2⊤           convert to base 2 matrix
                        ⍉              transpose
                       ↓                convert to nested list
                ⍵ ⍵∘⍴¨                 reshape each vector to n x n matrix
      (2=+/,+⌿)¨                        2= sums of rows and cols?
   ∧/¨                                 check if all elements of each satisfy that condition
 +/                                    sum

```
> 3 votes

# Answer
# Jelly, 15 bytes

```
⁼þⱮŒ!+þ`ẎḊỊÐṀQL

```

A monadic Link that accepts \\$n\\$ and yields \\$a\_n\\$.

**Try it online!**

### How?

Uses Jonah's idea from their J answer.

```
⁼þⱮŒ!+þ`ẎḊỊÐṀQL - Link: n
   Œ!           - all permutations (of implicit [1..n])
  Ɱ             - map with:
 þ              -   (implicit [1..n]) outer product (permutation) using:
⁼               -     equals?
       `        - use that as both arguments of:
      þ         -   outer product using:
     +          -     addition
        Ẏ       - tighten (to a list of matrices)
         Ḋ      - dequeue (makes the following still work when n=1)
           ÐṀ   - keep those which are maximal under:
          Ị     -   is insignificant (abs(x)<=1?)
             Q  - deduplicate
              L - length

```
> 3 votes

# Answer
# Charcoal, ~~49~~ 36 bytes

```
⊞υ¹⊞υ⁰Ｆ⊖Ｎ⊞υ×÷×Ｌυ⊖Ｌυ²⁺⊗§υ±¹×⊖Ｌυ§υ±²Ｉυ

```

Try it online! Link is to verbose version of code. Outputs the terms `a₀..aₙ`. Explanation:

```
⊞υ¹⊞υ⁰Ｆ⊖Ｎ⊞υ×÷×Ｌυ⊖Ｌυ²⁺⊗§υ±¹×⊖Ｌυ§υ±²Ｉυ

```

Start with `a₀` and `a₁`.

```
Ｆ⊖Ｎ

```

Input `n` and calculate `n-1` more terms...

```
⊞υ×÷×Ｌυ⊖Ｌυ²⁺⊗§υ±¹×⊖Ｌυ§υ±²

```

... apply the recurrence relation to calculate the next term.

```
Ｉυ

```

Output all the terms.
> 2 votes

# Answer
# MATLAB/Octave, 58 bytes

```
c=0
b=1
n=2;while k=n
n=n+1;
a=n*k*b+n*k*k*c/2
c=b;b=a;end

```

Use Octave Online to test it yourself! TIO seems to have problems with infinite nature of the script. It uses recursive formula and it's an infinite generator. The following results are printed to the console. It technically works forever but pretty fast falls into limits of floating precision and all new results are infinity. On MATLAB as I checked the results stay precise up to 13th element of the sequence. After that some floating precision errors appear and then they accumulate with each next element.
The scripts throws a warning due to `while k=n` but it continues to work. If needed to be avoided it can be replaced with `while 1` and `k=n` in next line.

For MATLAB it is also possible to reduce length to **57 bytes** with code like that:

```
c=0
b=1
for n=3:Inf
k=(n-1);a=n*k*b+n*k*k*c/2
c=b;b=a;end

```

But it doesn't work in Octave due to `3:Inf` range.
> 2 votes

# Answer
# Jelly, 15 bytes

```
’ÑH×+Ñ××‘
’¹ÇỊ?

```

Try it online!

Uses the recursive formula.

## Explanation

```
’ÑH×+Ñ××‘ Auxiliary monadic link, taking (n-1) as the argument
’         Decrement:
                (n-2)
 Ñ        Apply next link:
                a(n-2)
  H       Halve:
                a(n-2) / 2
   ×      Multiply by the argument:
                (n-1) a(n-2) / 2
    +     Add
     Ñ      the next link applied to the argument:
                (n-1) a(n-2) / 2 + a(n-1)
      ×   Multiply by the argument:
                (n-1) ((n-1) a(n-2) / 2 + a(n-1))
       ×  Multiply by
        ‘   the argument incremented:
                n (n-1) ((n-1) a(n-2) / 2 + a(n-1))

’¹ÇỊ? Main monadic link, taking n as the argument
’     Decrement: (n-1)
    ? If
   Ị    insignificant: |n-1| ≤ 1
      then
 ¹      identity: (n-1)
      else
  Ç     apply previous link

```
> 2 votes

# Answer
# , 52 bytes

```
f=function(n,k=n-1)"if"(n<3,k,n*k*(f(k)+f(n-2)*k/2))

```

Try it online!

Using formula from OEIS page: `a(n) = n(n-1)/2 [ 2 a(n-1) + (n-1) a(n-2) ] (Bricard)`
> 2 votes

# Answer
# Brachylog, 20 bytes

```
~lṁ{{0|1}ᵐ²\,?+ᵐ=₂}ᶜ

```

Brute-force solution; times out on TIO with any input higher than 4. Try it online!

### Explanation

```
~l                    Generate a list whose length equals the input
  ṁ                   That list is a square matrix
                      At this point, we have a matrix of indeterminate values
   {              }ᶜ  Count how many ways we can satisfy this predicate:
    {   }ᵐ²            For each value in the matrix:
     0|1                It is either 0 or 1
           \           Transpose the matrix
            ,?         Append the non-transposed version
                       We now have a list of all rows and all columns of the matrix
              +ᵐ       Sum each row/column
                =₂     All the results must equal 2

```
> 2 votes

# Answer
# Python 3, 53 bytes

```
a=lambda n:n<1if n<2else~-n*n*(a(n-1)+(n-1)/2*a(n-2))

```

Try it online!

-2 thanks to @Neil

Recursive formula, for input 1 it should output `False` instead of 0
> 1 votes

# Answer
# Pari/GP, 48 bytes

```
a(n)=if(n<2,n<1,(n^2-n)*(a(n-1)+(n-1)/2*a(n-2)))

```

Try it online!

Found it on the OEIS page, just golfed it a bit, uses Recursion
> 1 votes

# Answer
# Desmos, 51 bytes

```
a=n-i
f(n)=n!^2/4^n\sum_{i=0}^n(-2)^i(2a)!/(i!a!^2)

```

Try It On Desmos!

Try It On Desmos!(Prettified)

Desmos doesn't support recursion and has limited ability for loops, so I had to use the explicit formula: $$a\_n=\frac{(n!)^2}{4^n}\sum\_{i=0}^n\frac{(-2)^i(2n-2i)!}{i!((n-i)!)^2}$$
> 1 votes

# Answer
# Ruby, 41 bytes

```
f=->n{(w=n*n-=1)<3?n:w*f[n]+w*n*f[n-1]/2}

```

Try it online!

Using the recursive formula
> 1 votes

# Answer
# Python 3, 195 bytes

```
def f(n):
  if n<2:
    return 1
  return n*f(n-1)
def o(n):
  if n < 2:
    return 0
  p=0
  r=(f(n)**2)/4
  for i in range(n+1):
    p+=(-2)**i*f(2*n-2*i)/(f(i)*(f(n-i)**2))
  return int(p * r)

```

Try it online!

Pretty ungolfed, but hey, it's one of the first to use the standard formula, and it can handle up to 75.
> 0 votes

---
Tags: code-golf, sequence, combinatorics, binary-matrix
---


title: Quack the Angry Duck

text:
# Question
Title: Quack the Angry Duck
No one is quite certain what the emoticon `>:U` is intended to represent, but many scholars believe it looks like an angry duck. Let's assume that's the case.

## Task

Given an integer *n* between 0 and 3 inclusive, print or return

```
quack

```

if *n* = 0,

```
>:U

```

if *n* = 1,

```
     U   U
>  : U   U
 >   U   U
>  : U   U
      UUU

```

if *n* = 2, or

```
                  >:U         >:U
>:U               >:U         >:U
   >:U       >:U  >:U         >:U
      >:U         >:U         >:U
         >:U      >:U         >:U
      >:U         >:U         >:U
   >:U       >:U  >:U         >:U
>:U               >:U         >:U
                     >:U>:U>:U

```

if *n* = 3.

You can assume the input will always be valid. There should be no leading space in the output, but any amount of trailing space is fine. Ducks (with the possible exception of @cobaltduck) have no tolerance for loopholes. Shortest code in bytes wins.

# Answer
> 19 votes
# CJam, ~~108~~ ~~90~~ 85 bytes

```
"quack"">:U":D"scT¦{$ì"{269b22bSf*D}:F~[ZYB].*s.+s5/"ÿ3nÜïS{JÐø¦yûn"F*33/z]ri=zN*

```

Note that some characters are unprintable. Try it online!

### Background

The first two outputs are incompressible in CJam.

Compressing the last output is straightforward. After stripping all linefeeds, we can split the resulting string at occurrences of `>:U`, and compute the length of each resulting string of spaces.

That results in the array

```
[18 9 0 15 9 3 7 2 9 6 9 9 9 6 9 6 9 9 3 7 2 9 0 15 9 21 0 0 0]

```

which we can store efficiently by converting it from base 22 to base 269, yielding the digits

```
[255 12 51 110 220 239 83 123 74 208 248 166 121 251 110 17]

```

Since each digit is less than **256**, we can store it as a single byte.

Finally, compressing the third output becomes easier if we transpose lines and columns:

```
 > >
  >

 : :

UUUU
    U
    U
    U
UUUU

```

Counting once more the spaces between non-whitespace characters, we get the array

```
[1 1 3 8 1 6 0 0 0 5 4 4 0 0 0 0 0]

```

which becomes

```
[115 159 99 84 166 123 36 236 6]

```

when transcoded from base 22 to base 269.

### How it works

```
"quack"   e# Push the first output.

">:U":D   e# Push the second output, and save it in D.

e# Push [115 159 99 84 166 123 36 236 6] as bytes.

"scT¦{$ì"

{         e# Define a code block:
  269b22b e#   Transcode from base 269 to base 22.
  Sf*     e#   Replace each digit with a string of that many spaces.
  D       e#   Push D.
}         e#
:F~       e# Save the block in F. Execute it.
[ZYB]     e# Push [3 2 11].
.*        e# Vectorized repeat; push [">>>" "::" "UUUUUUUUUUU"].
s         e# Flatten the array of strings.
.+        e# Append the nth character to the nth string of spaces.
s5/       e# Flatten and split into chunks of length 5.

e# Push [255 12 51 110 220 239 83 123 74 208 248 166 121 251 110 17] as bytes.

"ÿ3nÜïS{JÐø¦yûn"

F         e# Execute F.
*         e# Join the resulting array of strings of spaces, separating by ">:U".
33/       e# Split into chunks of length 33.
z         e# Zip; transpose rows with columns.

]         e# Wrap the entire stack in an array.
ri        e# Read a token from STDIN and interpret it as an integer.
=         e# Retrieve the element at the corresponding index.
z         e# Zip; transpose rows with columns or map "string" to ["string"].
N*        e# Join, separating by linefeeds.

```

# Answer
> 23 votes
## Java, 303 286 bytes

Saved 17 bytes thanks to @VoteToClose!

Not actually meant to be the shortest, I just thought it would be fun to try in Java.

Creates a list of string variables representing common strings, then creates an array of all the outputs, then prints the right one.

```
String a(int y){String n="\n",d=">:U",A=" ",B=A+A,C=B+B,D=C+C,a="U"+B+" U"+n,G=D+A,H=C+B,c=d+G+d+n,E=B+A,F=C+E;String[]z={"quack",d,C+A+a+">"+B+": "+a+" >"+E+a+">"+B+": "+a+C+B+"UUU",D+D+B+c+d+D+F+c+B+A+d+F+d+B+c+H+d+G+c+G+d+H+c+H+d+G+c+E+d+F+d+B+c+d+D+F+c+D+D+C+A+d+d+d};return z[y];}

```

Ungolfed:

```
String a(int y) {
    String n = "\n", d = ">:U", A = " ", B = A + A, C = B + B, D = C + C,
            a = "U" + B + " U" + n, G = D + A, H = C + B, c = d + G + d + n,
            E = B + A, F = C + E;
    String[] z = { "quack", d, C + A + a + ">" + B + ": " + a + " >" + E + a + ">" + B + ": " + a + C + B + "UUU", D + D + B + c + d + D + F + c + B + A + d + F + d + B + c + H + d + G + c + G + d + H + c + H + d + G + c + E + d + F + d + B + c + d + D + F + c + D + D + C + A + d + d + d };
    return z[y];
}

```

This is my first answer on this site, so please tell me if I have done something wrong.

# Answer
> 9 votes
# 05AB1E, ~~162~~ ~~159~~ 157 bytes

## Code

Dammit, way too long, but it's at least something:

```
">:U"VI3Qið16×7166b1ð:0Y:DUJ,Yð13×JD?X,3838b1ð:0Y:D?X,16255b1ð:0Y:D?X,16367b1ð:0Y:4F?X,}ð21×Y3×J,}¹2Qið4×" U   U"©J,">  :"®JD," >  "?®,,ð6×'U3×J,}¹iY,}"quack

```

Try it online!

---

## Explanation

The first part of the code exists of `">:U"V`, which sets `Y` to that string. After that, we just check if the input is equal to 3. That is done at the `I3Qi` part. If equal, we print the giant magpie:

### N = 3

It first starts with `ð16×` which just pushes 16 space characters. After that, there is a number `7166b`. This covers the `">:U "` part, with a little help from Retina :). I used this script to convert the string to a binary number. After that, we get to the `1ð:0Y:` part, which replaces every `1` with a space character and every `0` with `Y`, which has been set to `>:U`. After that, we `D`uplicate this string, store it in `X` using `U` and `J`oin the stack. We pop this using `,`, which prints the full string with a newline. All the others after that are all based on the same principe. The if statement ends at the second `}`.

The full conversion can be found here.

### N = 2

We now check if the input is equal to 2. This is done at the `¹2Qi` part. After that, if equal, we push the space character 4 times using `ð4×`. After that, we push the `" U U"` string and store it using `©` (idea blatantly stolen from Jelly :p). We again `J`oin the stack and print this with a newline. After that, we push the `"> :"` string, retrieve the `" U U"` using `®`, `J`oin the stack and `D`uplicate this string and print these both on the same line.

Short quiz, what will this do: `" > "?®,`?

After printing the above string, we get the duplicate of the second line of the face, and print this (since it's the same as the 2nd line).

The last part covered by this case is:

```
ð6×'U3×J,

ð6×        # Push the space character × 6
   'U3×    # Push the "U" character three times
       J,  # Join and print pop with a newline

```

### N = 1

This one is easier to explain:

```
¹1QiY

¹1Qi   # Check if the input is equal to 1
    Y  # Push the magpie face
       # This is then implicitly printed

```

### N = 0

```
¹0Qi"quack

¹0Qi        # Check if the input is equal to 0
    "quack  # Weird sound what magpies make
            # Implicitly printed

```

# Answer
> 8 votes
# Vitsy, ~~172~~ ~~171~~ 159 bytes

Oh, geez. If I wanted something to show off the power of methods, I got it.

```
' 'V1+m
'kcauq'Z
'U:>'Z
58m5m6m'   > 'Z5m6m'UUU'68m
f3+bm9mamcm98m2m6bmcmam9mf6+8m3\[2m]
a'U   U'Z
' :  >'Z5m
Z2m98ma2m
\VZ
2mfbm
VVVZ2m78m2mVV7m
8m7m
68m2m9bm
```

Try it Online!

How this works is by calling various methods throughout itself. The explanation is below:

```
' 'V1+m
' 'V      Save character literal ' ' as a permanent variable.
    1+    Add one to the top item of the stack (input + 1)
      m   Go to that index of code.

'kcauq'Z
'kcauq'   Push 'quack' to the stack.
       Z  Output everything in the stack as a char.

'U:>'Z
'U:>'Z    Ouput ">:U" with the same method as the previous line.

Now on to some more... interesting lines.

58m5m6m'   > 'Z5m6m'UUU'68m
5              Push space, push 4
 8m            Call the 8th line index.
               As we will soon see, the 8th line index duplicates the space
               the number of times specified by the number just before the call
               (4 in this case)
   5m          Call the 5th line index.
               The 5th line index outputs the 'U   U' and a newline.
     6m        Call the 6th line index.
               The 6th line index outputs '>  : U   U' and a newline.
'   > 'Z       Output ' >   '.
        5m6m   Same method calls as before.
'UUU'          Push 'UUU'.
     68m       Push 6, then call the 8th line index. This gives us the correct padding.

f3+bm9mamcm98m2m6bmcmam9mf6+8m3\[2m]
f3+              Push 18.
   bm            Call the 11th line index.
                 The 11th line index calls the 8th line index (which we've already seen
                 in action) and then the 7th line index, which you can find and explanation
                 for below (it does a **lot**)
     9m          Call the 9th line index.
                 The 9th line index outputs '>:U               >:U         >:U' (explanation lower)
       am        Call the 10th line index.
                 ...I'm gonna stop explaining these and just tell you to go to the lines now. :P
         cm      Call the 12th line index.
9                Push space, push 9.
 8m              Call the 8th line index (explained below and before).
   2m            Call the 2nd line index.
     6           Push 6.
      bm         Call the 11th line index. We've finished up to '>:U      >:U         >:U' now.
cm               You guessed it! Call the 12th line index. (explanation below)
  am             Call the 10th line index. (explanation below)
    9m           Call the 9th line index. (explanation below)
f6+              Push space, push ~~19~~ 21.
   8m            Call the 8th line index. (explanation below)
     3\[2m]      Call the 2nd line index thrice.

All of the rest of these methods are supporting methods now.

a'U   U'Z       Output 'U   U' followed by a newline.

' :  >'Z5m      Output '>  : U   U' followed by a newline.

Z2m98ma2m
Z               Output everything currently in the stack.
 2m             Call the 2nd line index.
   9            Push space, push 8.
    8m          Call the 8th line index. (explained below)
      a         Push a newline to the stack.
       2m       Call the 2nd line index.
                This handles the biggest angry duck face's faces showing the eyebrows and eyes.

\VZ
\V    Push space as many times as the top item specifies.
  Z   Output everything in the stack.

2mfbm
2m      Call the 2nd line index.
  f     Push space, push 14.
   bm   Go to the 11th line index.
        This handles the mouth and some parts of the eyebrows of the biggest duck face.

VVVZ2m78m2mVV7m
VVVZ              Output 3 spaces (and whatever was pushed before it)
    2m            Call the 2nd line index.
      7           Push space, push 6.
       8m         Call the 8th line index. (explained... above)
         2m       Call the 2nd line index.
           VV     Push 2 spaces.
             7m   Call the 7th line index.

8m7m     This is pretty damn self-explanatory if you've read this far.

68m2m9bm
6            Push space, push 5.
 8m          Call the 8th line index.
   2m        Call the 2nd line index.
     9       Push space, push 9.
      bm     Call the 11th line index.
```

This code is ridiculous. It's verbose form is:

```
toggle single quote;
 ;
toggle single quote;
save top as permanent variable;
push 1;
add top two;
goto top method;
:toggle single quote;
k;
push 12;
push 10;
flatten top two stacks;
q;
toggle single quote;
output stack as chars;
:toggle single quote;
U;
clone current stack;
go forward;
toggle single quote;
output stack as chars;
:push 5;
push 8;
goto top method;
push 5;
goto top method;
push 6;
goto top method;
toggle single quote;
 ;
 ;
 ;
go forward;
 ;
toggle single quote;
output stack as chars;
push 5;
goto top method;
push 6;
goto top method;
toggle single quote;
U;
U;
U;
toggle single quote;
push 6;
push 8;
goto top method;
:push 15;
push 3;
add top two;
push 11;
goto top method;
push 9;
goto top method;
push 10;
goto top method;
push 12;
goto top method;
push 9;
push 8;
goto top method;
push 2;
goto top method;
push 6;
push 11;
goto top method;
push 12;
goto top method;
push 10;
goto top method;
push 9;
goto top method;
push 15;
push 6;
add top two;
push 8;
goto top method;
push 3;
repeat next instruction set top times;
begin recursive area;
push 2;
goto top method;
end recursive area;
:push 10;
toggle single quote;
U;
 ;
 ;
 ;
U;
toggle single quote;
output stack as chars;
:toggle single quote;
 ;
clone current stack;
 ;
 ;
go forward;
toggle single quote;
output stack as chars;
push 5;
goto top method;
:output stack as chars;
push 2;
goto top method;
push 9;
push 8;
goto top method;
push 10;
push 2;
goto top method;
:repeat next instruction set top times;
save top as permanent variable;
output stack as chars;
:push 2;
goto top method;
push 15;
push 11;
goto top method;
:save top as permanent variable;
save top as permanent variable;
save top as permanent variable;
output stack as chars;
push 2;
goto top method;
push 7;
push 8;
goto top method;
push 2;
goto top method;
save top as permanent variable;
save top as permanent variable;
push 7;
goto top method;
:push 8;
goto top method;
push 7;
goto top method;
:push 6;
push 8;
goto top method;
push 2;
goto top method;
push 9;
push 11;
goto top method;
```

# Answer
> 8 votes
# JavaScript (ES6), 163 bytes

```
var solution =

n=>["quack",d=">:U",`5U3U
>2:1U3U
1>3U3U
>2:1U3U
6UUU`,`99090
096090
30702090
609090
906090
609090
30702090
096090
993000`][n].replace(/\d/g,c=>+c?" ".repeat(c):d)
```

```
<input type="number" oninput="R.textContent=solution(+this.value)"><pre id="R"></pre>
```

## Explanation

Uses my go-to compression with JavaScript: run-length encoding. The digits `1` to `9` map to that many spaces, `0` maps to the angry duck face, and any other character stays the same.

# Answer
> 7 votes
# Japt, ~~116~~ ~~105~~ ~~102~~ ~~99~~ 96 bytes

```
["quack""c)`+«öÂ[@=^Gñ`1]o2"mc r'4#¿+R "4z>2:z >2z>2:z6UUU"rz" U3U
" '1]®r'1">:U" r"%d"_SpZ}ÃgU

```

Contains an unprintable. Test it online!

### How it works

The first two strings are not compressed at all. The third is compressed simply by replacing each runs of spaces with its length, then `" U3U"` with `"z"`. The last one is more complex:

1. Replace each run of 2-9 spaces with its length.
2. Replace `>:U` with `1`.
3. Replace `191\n` with `4`. (`4` isn't used anywhere else in the string.)
4. Map each valid byte code (`10`-`255`, or `0A`-`FF`) to the character with that char code.

The resulting string is only ~~21~~ 19 bytes long, but the decompression takes up another ~~31~~ 29.

After decompressing the strings, we simply take the item at position `U`, the input. (The array is arranged `[0,3,2,1]` because there's a bug which makes it count from the *end* of the array instead of the beginning.)

```
[                      // Create an array of the following:
  "quack"              //  "quack".

  "c)`+«öÂ[@=^Gñ`1]o2" //  Take this string (contains an unprintable).
                       //  Map each char to its char code.
                       //  This produces "994196431712461949164619431712419649931112".
  r'4#¿+R              //  Replace each "4" with the char code of "¿" (191) + a newline.

  "4z>2:z >2z>2:z6UUU" //  Take this string.
  rz" U3U\n"           //  Replace each "z" with " U3U\n".

  '1                   //  "1".
]
®              Ã       // Map each item by this function:
r'1">:U"               //  Replace each "1" with ">:U".
r"%d"_SpZ}             //  Replace each remaining digit Z with Z spaces.

gU                     // Get the item at index -U, wrapping.
                       // (This should just be U, but there's a bug which negates it.)

```

# Answer
> 5 votes
# MATL, ~~283~~ 182 bytes

***101*** *bytes saved thanks to @Adnan!*

This uses decimal numbers to encode indices `0`...`3` to the four characters for cases 2 and 3. The decimal numbers could perhaps be compressed using base-64 encoding, but quack!

For the case 3 a very nice trick suggested by @Adnan is used: define binary sequences to encode each row, where `0` and `1` correspond to space and `>:U` respectively.

```
~?'quack'}G1=?'>:U'}G2=?' :>U'12336 8466480h2109488h8466480h4032h4YA47-)}268697600 67174401h16795656h67174464h67174912h67174464h16795656h67174401h14680064h"@BP48+]Xh49'>:U'YX48 32YXc

```

**Try it online!**

# Answer
> 5 votes
# JavaScript ES6, ~~232~~ ~~223~~ ~~203~~ 188 bytes

Saved ~~29~~ 44 bytes thanks to ETHproductions!

```
n=>[`quack`,r=`>:U`,`     U   U
>  : U   U
 >   U   U
>  : U   U
      UUU`,`00022
10022
0100 1  12
00122
20012
00122
0100 1  12
10022
0000211`.replace(/\d/g,N=>[g=`   `,r,g+g+g+r][N])][n]

```

## Test it out!

```
A=n=>[`quack`,r=`>:U`,`     U   U
>  : U   U
 >   U   U
>  : U   U
      UUU`,`0000002
1000002
0100 1  2
0010002
0001002
0010002
0100 1  2
1000002
0000000111`.replace(/\d/g,N=>[g=`   `,r,r+g+g+g+r][N])][n]

(a.onchange=a.onkeydown=a.onkeyup=function(){
 o.innerHTML = A(+a.value);
})();
```

```
*{font-family:"Consolas",monospace;font-size:20px;white-space:pre-wrap}input{left:50%;width:150px;position:absolute;text-align:center;margin-left:-75px;}#o{margin:15px;border:1px solid #00ACDC;padding:15px;}
```

```
<input id=a type=number value=0 min=0 max=3><br><div id=o></div>
```

# Answer
> 5 votes
# Cinnamon Gum, 76 bytes

```
0000000: 6c33 502b 2c4d 4cce b636 54b3 b30a b536  l3P+,ML..6T....6
0000010: 5253 0081 5010 e6b2 5350 b082 3215 ecb0  RS..P...SP..2...
0000020: 8a42 1487 865a 1bab 2960 00a0 79c8 6c2e  .B...Z..)`..y.l.
0000030: 2026 a002 4221 0430 55c0 5938 cd40 9720   &..B!.0U.Y8.@.
0000040: 6c06 6177 90e9 17ac 4102 4100            l.aw....A.A.

```

Non-competing since Cinnamon Gum was created after this challenge.

Try it online.

## Explanation

The first byte `l` specifies the mode: in this case it tells Cinnamon Gum to enter lookup table mode. Cinnamon Gum then decompresses the rest of the string (which has been compressed with `zopfli --deflate`) into this:

```
0&quack;1&>:U;2&     U   U
>  : U   U
 >   U   U
>  : U   U
      UUU;3&                  >:U         >:U
>:U               >:U         >:U
   >:U       >:U  >:U         >:U
      >:U         >:U         >:U
         >:U      >:U         >:U
      >:U         >:U         >:U
   >:U       >:U  >:U         >:U
>:U               >:U         >:U
                     >:U>:U>:U

```

It then splits by `;`, puts each key-value pair (with `&` as delimiter) in a dictionary, and outputs `dictionary[input]`.

# Answer
> 3 votes
# Brainfuck 802 bytes

I know its not very optimal to make this challenges in bf... but its very fun :)

Code:

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

```

Try it yourself

"Beautiful version":

```
READ NUMBER
,>-[<->-----]<+++
WRITE LETTERS FROM SPACE TO LINE JUMP
>>+[--[<]>>+<-]>++[-<++<+>>]
>-[<+>+++++++++]
>-[<+>---]
++++++++++
<<+<<+<<
START A SWITCH CASE
[-
   [-
      [[-]
CASE 3
         >>..................>.>.>.<<<.........>.>.>.>.
         <<<.>.>.<<<...............>.>.>.<<<.........>.>.>.>.
         <<<<...>.>.>.<<<.......>.>.>.<<<..>.>.>.<<<.........>.>.>.>.
         <<<<......>.>.>.<<<.........>.>.>.<<<.........>.>.>.>.
         <<<<.........>.>.>.<<<......>.>.>.<<<.........>.>.>.>.
         <<<<......>.>.>.<<<.........>.>.>.<<<.........>.>.>.>.
         <<<<...>.>.>.<<<.......>.>.>.<<<..>.>.>.<<<.........>.>.>.>.
         <<<.>.>.<<<...............>.>.>.<<<.........>.>.>.>.
         <<<<.....................>.>.>.<<.>.>.<<.>.>.>>
      >+<]>-[
CASE 2
         >.....>>>.<<<...>>>.>.
         <<<.<..>>.<<.>>>.<<<...>>>.>.
         <<<<.>.<...>>>.<<<...>>>.>.
         <<<.<..>>.<<.>>>.<<<...>>>.>.
         <<<<......>>>...>>>-
      +]<
CASE 1
   >+<]>-[ >>.>.>.<<<< +]<
>+<]>-[
CASE 0 (CREATE NEW LETTERS)
   >[>]-[+>+++++[<]>+]>.++++.>+[-[---<]>>-]<-.++.++++++++.>-
+]

```

# Answer
> 0 votes
# GML, 265 bytes

A port of @kittycat3141's excellent answer, with the suggestion to golf it further with two new variables (which I named G and H) by @VoteToClose. I also managed to shorten it further with GML's relatively loose syntax.

```
d=">:U"A=" "B=A+A;C=B+B;D=C+C;G=D+A;H=C+B;a="U"+B+" U"+"#"c=d+G+d+"#"E=B+A;F=C+E;x[0]="quack"x[1]=d;x[2]=C+A+a+">"+B+": "+a+" >"+E+a+">"+B+": "+a+H+"UUU"x[3]=D+D+B+c+d+D+F+c+B+A+d+F+d+B+c+H+d+G+c+G+d+H+c+H+d+G+c+E+d+F+d+B+c+d+D+F+c+D+D+C+A+d+d+d;return x[argument0]

```

# Answer
> 0 votes
# JavaScript (ES6),  ~~151~~  150 bytes

```
n=>(g=s=>(l=s.split(--k),k?g(l.join(l.pop())):l[n]))(`quack030285 >256UUU06273646371631
63436766133162328 3>:U47236 3831
5U2U
>8: U2U
622711
8  `,k=9)

```

Try it online!

# Answer
> 0 votes
# ///, 130 bytes

```
/0/quack//e/UrU
//d/m
//m/br1//b/rr//r/   //1/>:U//2/r  e>  : e >re>  : ebUUU//3/bbb1d1bmdr1b 1  1db1mdmb1db1mdr1b 1  1d1bmdbbm11/

```

Try it online!

---
Tags: code-golf, ascii-art, number, kolmogorov-complexity
---