title: Draw Reutersvärd's Triangle

text:
# Question
Title: Draw Reutersvärd's Triangle
This impossible object is Reutersvärd's triangle:

Draw your own version according to these rules:

* Exactly 9 cubes total
* Each side is made up of exactly 4 cubes
* The cubes appear to overlap such that the rendered object is in fact an impossible object
* 4 distinct colours are used - one for the background and 3 for each of the faces of the cubes
* In bitmap output, the full triangle should be at least 100 pixels tall and at least 100 pixels wide
* Aspect ratio: the width and height of the full triangle should not be off by more than a factor of 2
* The triangle may be rotated by any amount relative to the above image
* The triangle may or may not be reflected relative to the above image

# Answer
# Mathematica, 237 bytes

```
n={-1,1}#&;c_~g~s_:=Polygon[c+s#&/@{k={12,9},m=n@k,t={0,-12}}];p={#,#2~g~1,#3~g~-1}&;a=p[Cyan,#-k,#+m]&;b=p[Blue,#-t,#+k]&;c=p[Red,#-m,#+t]&;Graphics@{{a@#,b@#,c@#}&/@{j=4k,s=4{4,9},n@s,4m,r={-32,8},q=-4{4,5},4t,n@q,n@r},a@j,b@s,c@j,c@s}

```

Easier-to-read version:

```
1  n = {-1, 1} # &;
2  c_~g~s_ := Polygon[c + s # & /@ {k = {12, 9}, m = n@k, t = {0, -12}}];
3  p = {#, #2~g~1, #3~g~-1} &;
4  a = p[Cyan, # - k, # + m] &;
5  b = p[Blue, # - t, # + k] &;
6  c = p[Red, # - m, # + t] &;
7  Graphics@{
8    {a@#, b@#, c@#} & /@
9      {j = 4 k, s = 4{4, 9}, n@s, 4 m, r = {-32, 8},
10       q = -4{4, 5}, 4 t, n@q, n@r},
11   a@j, b@s, c@j, c@s}

```

Line 1 defines a function `n` that negates the first coordinate of an ordered pair. Line 2 defines a function `g` that produces a (roughly) equilateral triangle centered at the point `c`, and pointing down or up depending on whether `s` is `1` or `-1`. Line 3 defines `p` to be a parallelogram template consisting of a color and two triangles, and lines 4–6 define `a`, `b`, and `c` to be the three different specific types of parallelograms that appear in the cubes.

Line 8 defines a function `{a@#, b@#, c@#}&` that draws an entire cube centered at the point `#`; lines 9 and 10 apply that to the nine points needed to make the larger triangle. This produces nine cubes, starting at the upper right and going counterclockwise, where the later ones cover up parts of the earlier ones. Finally, line 11 redraws four parallelograms (in the upper right of the picture) so that they end up covering the later cubes as they're supposed to. The output is below:
> 18 votes

# Answer
# Brain-Flak, ~~487810~~ ~~327722~~ 75564 + 1 = 75565 bytes

Unfortunately this is a tad big to fit in an answer.

PasteBin

Try it Online

With the `-A` flag this outputs an ASCII ppm file that looks as follows:

# Explanation

You may have already guessed I did not write this by hand. So here's how I did it:

I first made the image you see above from the image provided by the challenge. It has the distinction of having no color channel that is at any value other than `255` or `0` this way we can wrap it up into a smaller file with the max color channel set to 1. I then wrote a python script to golf a Brain-Flak program that solves this using a module I wrote myself that can be found here. Its not very polished its just a hack I threw together for things like this. `push` is a function that returns efficient Brain-Flak code to push a number to the stack and `kolmo` is a very simple Kolmogorov complexity solving program that attempts to find an efficient way to push a particular string to the stack.

```
from value import push,kolmo

def group(a, n):
    return zip(*[a[i::n]for i in range(n)])

f=open("R.ppm")
a=["".join(x)for x in group(f.read().split()[3:][::-1],3)]
f.close()

def hardcode(string):
    result = push(ord("\n")).join("(<>({})<>"+{"0":"","1":"()"}[x]+")"for x in string)
    return result

last = ""
acc = 0
result = push(ord("0"))+"<>"
for x in a+[""]:
    if x != last:
        string = ("" if not last else kolmo("\n")+hardcode(last))
        result += min([push(acc)+"{({}[()]<%s>)}{}"%string,acc*string],key=len)
        acc=1
    else:
        acc += 1
    last = x
print result+kolmo("P3 100 100 ")

```

This was quite fun and I hope to improve my answer
> 16 votes

# Answer
# BBC BASIC, 147 bytes

tokenised filesize 129 bytes

```
t=PI/1.5x=500y=x:FORi=0TO28b=i MOD3GCOL0,b:b*=t:a=i DIV9*t:IFb=0x-=99*COSa:y-=99*SINa
MOVEx,y:VDU25;66*COSb;66*SINb;28953;66*COS(b-t);66*SIN(b-t);:NEXT

```

2 bytes saved by using an absolute coordinate specification (`MOVE`) and two relative specifications per parallelogram, instead of changing the origin in order to be able to use all absolute specifications. 1 byte of unnecessary whitespace eliminated.

# BBC BASIC, 150 bytes

tokenised filesize 127 bytes

Download interpreter at http://www.bbcbasic.co.uk/bbcwin/download.html

```
t=PI/1.5x=500y=x:F.i=0TO28b=i MOD3GCOL0,b:b*=t:a=i DIV9*t:IFb=0 x-=99*COSa:y-=99*SINa:ORIGINx,y
L.66*COSb,66*SINb,0,0PLOT117,66*COS(b-t),66*SIN(b-t)N.

```

**Explanation**

We start with the coordinates at top right and plot rhombuses in groups of 3. Before each group of 3 we move the origin (West, West, West, SE, SE SE, NE, NE NE.) That means that the group of 3 at top right is the last complete group to be plotted, bringing the origin back to its original location. We then continue and plot the black and red (but not the green) of the first group again, a total of 29 rhombuses.

**Ungolfed**

```
  t=PI/1.5                                 :REM 120 deg
  x=500                                    :REM coordinates of top right corner
  y=x
  FORi=0TO28
    b=i MOD3:GCOL0,b                       :REM set colour 0=black,1=red,2=green
    b*=t                                   :REM convert b to a multiple of 120deg
    a=i DIV9*t
    IFb=0 x-=99*COSa:y-=99*SINa:ORIGINx,y  :REM before each group of 3 rhombs move the graphics origin
    LINE66*COSb,66*SINb,0,0                :REM define one side of a rhombus
    PLOT117,66*COS(b-t),66*SIN(b-t)        :REM define one further corner and plot the rhombus
  NEXT

```

**Output**
> 12 votes

# Answer
# HTML + CSS 3D (855 ~~866~~ bytes)

HTML *117 bytes* \+ CSS *738 bytes*

To keep the `z-indexes` in order was a bit tricky. ;)

```
/* CSS */
p{position:absolute;left:110px;top:0;width:50px;height:50px;transform-style:preserve-3d;transform:rotateX(-45deg)rotateY(21deg)rotateZ(20deg)}
p+p{left:140px;top:50px}
p+p+p{left:170px;top:100px}
p+p+p+p{left:200px;top:150px}
p+p+p+p+p{left:140px;top:150px}
p+p+p+p+p+p{left:80px;top:150px}
p+p+p+p+p+p+p{left:20px;top:150px}
p:nth-child(8){z-index:1;left:50px;top:100px}
p:nth-child(9){z-index:-1;left:80px;top:50px}
p:nth-child(10){z-index:1;left:67px;top:59px;transform:rotateX(-45deg)rotateY(21deg)rotateZ(20deg)scale(0.6)}
a{position:absolute;width:50px;height:50px;background:red;transform:rotateY(0deg)translateZ(25px)}
a+a{background:tan;transform:rotateY(-90deg)translateZ(25px)}
a+a+a{background:navy;transform:rotateX(90deg)translateZ(25px
```

```
<!-- HTML -->
<p><a><a><a><p><a><a><a><p><a><a><a><p><a><a><a><p><a><a><a><p><a><a><a><p><a><a><a><p><a><a><a><p><a><a><a><p><a><a>
```

I've kept the new lines for better readability. Maybe somebody spots potential for more golfing. However, they are not included in the byte count.

## Result

## jsFiddle Demo

Try it yourself

Use Goole Chrome. Other browsers may have problems with the `z-indexes`.

## Edit

* Saved **2 bytes** by removing the duplicate `a`-selector, thanks to ETHproductions.
* Saved **9 bytes** by removing an unnecessary `margin:0` on the `a`-element.
> 12 votes

# Answer
# HTML + JavaScript (ES6), 351 ~~374 384~~

```
<canvas id=C></canvas><script>c=C.getContext("2d");`133124222162184253104213162164244191224182133191064104222093164253122224284151284`.match(/.../g).map((v,i)=>(c.fillStyle=['#fc0','#f04','#08a'][a=i%3],c.beginPath(),c[l='lineTo'](x=5*~~v/10,y=v%10*25),c[l](x-10,y+(--a+!a)*17),a&&c[l](x-30,y+a*17),c[l](x-20,y),!a&&c[l](x-10,y-17),c.fill()))</script>

```

*Less golfed*

```
<canvas id=C></canvas>
<script>
  c=C.getContext("2d");
  [133,124,222,162,184,253,104,213,162,164,244,191,224,182,133,191,64,104,222,93,164,253,122,224,284,151,284]
  .map((v,i)=>(
    a = i % 3,
    x = 5 * ~~ v / 10,
    y = v % 10 * 25,
    c.fillStyle = ['#fc0','#f04','#0a8'][a],
    c.beginPath(),
    --a,
    c[l='lineTo'](x, y),
    c[l]( x -10, y + (a+!a) * 17),
    a&&c[l](x - 30, y + a * 17),
    c[l](x - 20, y),
    !a&&c[l](x - 10, y - 17),
    c.fill()
  ))
</script>

```

**Test**

```
<canvas id=C></canvas><script>c=C.getContext("2d");`133124222162184253104213162164244191224182133191064104222093164253122224284151284`.match(/.../g).map((v,i)=>(c.fillStyle=['#fc0','#f04','#08a'][a=i%3],c.beginPath(),c[l='lineTo'](x=5*~~v/10,y=v%10*25),c[l](x-10,y+(--a+!a)*17),a&&c[l](x-30,y+a*17),c[l](x-20,y),!a&&c[l](x-10,y-17),c.fill()))</script>
```
> 9 votes

# Answer
## JavaScript(ES6)/SVG(HTML5), ~~350~~ 312 bytes

```
document.write(`<svg width=390 height=338>`)
a=`195,52;240,130;285,208;330,286;240,286;150,286;60,286;105,208;150,130;`
a=(a+a).split`;`
for(i=9;i--;)document.write(`<path fill=#FD0 d=M${a[i]}h60l-30,-52h-60z /><path fill=#088 d=M${a[i+3]}h60l-30,52h-60z /><path fill=#F64 d=M${a[i+6]}l-30,-52l-30,52l30,52z />`)
```
> 6 votes

# Answer
# SVG, ~~562~~ ~~540~~ ~~520~~ ~~504~~ ~~487~~ 473 bytes

This is my first time golfing SVG (or any markup, in fact); be gentle!

The assumed viewing environment is an SVG-capable web browser with anything like a typical window size. I tested it in Firefox 50 and in Chrome 55.

The `viewBox` is necessary to meet the 100-pixel requirement; blowing up all measurements by a suitable factor would also work but would take more bytes. Incidentally, it is possible to save another byte by removing the space in `0 -5` in the `viewBox` value, but Firefox won't accept this as valid (whereas Chrome will).

The aspect ratio is 1:1 instead of the true 0.866:1. I'm not sure exactly how the "factor of 2" rule is meant to be interpreted (I think it means that exaggeration as extreme as 0.433:1 or 1.732:1 is acceptable), but I'm pretty sure this meets the requirement anyway.

## SVG

```
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:l="http://www.w3.org/1999/xlink"
viewBox="0 -5 26 26"><g
id="a"><path d="m7,9H3V5h6z"/><g
id="f"><path fill="red" d="m9,5H3V1h4z"/><path
fill="blue" d="m3,1l2,4L3,9l-2-4z"/></g></g><use
l:href="#a" x="3" y="6"/><use
l:href="#e" x="12"/><g
id="e"><use l:href="#a" x="-6" y="12"/><use l:href="#a" x="-12" y="12"/></g><use
l:href="#a" x="-9" y="6"/><use
l:href="#a" x="-6"/><use
l:href="#a" x="-3" y="-6"/><use
l:href="#f"/></svg>

```

## Result
> 5 votes

# Answer
# Python 3 \+ Turtle, 389 bytes

```
from turtle import*
a='#2e6f6e','#FAD028','#E44834'
L=lt;F=fd;B=begin_fill;E=end_fill
Z=0,1,2
pu()
ht()
speed(0)
for m in Z:L(120);F(30);L(60);F(30);L(60);[[[[color(a[j-m]),B(),[F(20)==L((5-i%2)*60)for i in(1,)+Z],E(),L(120)]for j in Z],k%2and[L(180),F(30),L(180)]or[L(300),F(30),L(60)]]for k in Z]
L(120)
F(30)
L(60)
F(10)
for k in[2,1]:color(a[k]);B();[F(20)==L(240)for i in Z];E();L(60)

```

From Bubbler's golf of -131 bytes! Try it online!

# Python 3 + Turtle, 537 520 bytes

```
from turtle import*
a=['#2e6f6e','#FAD028','#E44834']
pu()
ht()
speed(0)
for m in range(3):
	lt(120);fd(30);lt(60);fd(30);lt(60)
	for k in range(3):
		for j in range(3):
			color(a[j]);begin_fill()
			for i in range(4):fd(20);rt(120 if i%2==0 else 60)
			end_fill();lt(120)
		if k==1:rt(180);fd(30);lt(180)
		else:rt(60);fd(30);lt(60)
	a=a[2:]+a[:2]
lt(120)
fd(30)
lt(60)
fd(10)
a=[a[2],a[1]]
for k in range(2):
	color(a[k]);begin_fill()
	for i in range(3):fd(20);rt(120)
	end_fill();lt(60)
turtle.Screen().exitonclick()

```

-17 bytes from Dion, after removing unnecessary whitespace.

Try it online!

gif made from cdlane's instructions!
> 5 votes

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


title: Anagram Factors

text:
# Question
Title: Anagram Factors
On a recent episode of QI, the first 5 multiples of 142857 were described as anagrams of the original number. Of course, anyone with more than a passing knowledge of that number will know that those numbers are actually cyclic, not just anagrams. But that got me thinking.

Please write a program or function that outputs all numbers of six or fewer digits which have a proper factor that is an anagram of itself. The list should start with the following numbers:

```
3105    (divisible by 1035)
7128    (divisible by 1782)
7425    (divisible by 2475)
8316    (divisible by 1386)
8712    (divisible by 2178)
9513    (divisible by 1359)
9801    (divisible by 1089)

```

If you prefer, you can find numbers which have an anagram that is a proper factor of the number, but take care to exclude leading zeros from your anagrams.

This is code golf, so the shortest code in bytes that breaks no standard loopholes wins.

# Answer
# Mathematica (REPL environment), ~~75~~ 74 bytes

*Thanks to ngenisis for tightening this up by a byte!*

```
Select[Range[10!],Most@#~MemberQ~Last@#&[Sort/@IntegerDigits@Divisors@#]&]

```

`Sort/@IntegerDigits@Divisors@#` produces a sorted list of digits for every divisor of its argument; the input number is itself a divisor, so its sorted list of digits is the last one. `Most@#~MemberQ~Last` detects whether that last sorted list of digits also appears in the list prior to the last element. And `Select[Range[10!],...]` retains only those integers up to 3,628,800 that pass this test (that bound chosen because it's one byte shorter than 106). It runs in about 5 minutes on my computer, yielding a list of 494 numbers, the largest of which is 3,427,191; there are 362 numbers up to 106, the larget of which is 989,901.
> 6 votes

# Answer
# Jelly, 12 bytes

```
ÆḌṢ€ċṢ
ȷ6ÇÐf

```

Try it online! (uses five or fewer digits because of TIO's time limit)

### Verfication

```
$ time jelly eun 'ÆḌṢ€ċṢ¶ȷ6ÇÐf'
[3105, 7128, 7425, 8316, 8712, 9513, 9801, 30105, 31050, 37125, 42741, 44172, 67128, 70416, 71208, 71253, 71280, 71328, 71928, 72108, 72441, 74142, 74250, 74628, 74925, 78912, 79128, 80712, 81816, 82755, 83160, 83181, 83916, 84510, 85725, 86712, 87120, 87132, 87192, 87912, 89154, 90321, 90801, 91152, 91203, 93513, 94041, 94143, 95130, 95193, 95613, 95832, 98010, 98091, 98901, 251748, 257148, 285174, 285714, 300105, 301050, 307125, 310284, 310500, 321705, 341172, 342711, 370521, 371142, 371250, 371628, 371925, 372411, 384102, 403515, 405135, 410256, 411372, 411723, 415368, 415380, 415638, 419076, 419580, 420741, 421056, 423711, 425016, 427113, 427410, 427491, 428571, 430515, 431379, 431568, 435105, 436158, 441072, 441720, 449172, 451035, 451305, 458112, 461538, 463158, 471852, 475281, 501624, 502416, 504216, 512208, 512820, 517428, 517482, 517725, 525771, 527175, 561024, 562104, 568971, 571428, 571482, 581124, 589761, 615384, 619584, 620379, 620568, 623079, 625128, 641088, 667128, 670416, 671208, 671280, 671328, 671928, 672108, 678912, 679128, 681072, 691872, 692037, 692307, 704016, 704136, 704160, 704196, 705213, 705321, 706416, 711342, 711423, 712008, 712080, 712503, 712530, 712800, 713208, 713280, 713328, 713748, 714285, 716283, 717948, 719208, 719253, 719280, 719328, 719928, 720108, 720441, 721068, 721080, 721308, 721602, 723411, 724113, 724410, 724491, 728244, 730812, 731892, 732108, 741042, 741285, 741420, 742284, 742500, 744822, 746280, 746928, 749142, 749250, 749628, 749925, 753081, 754188, 755271, 760212, 761082, 761238, 761904, 771525, 772551, 779148, 783111, 786912, 789120, 789132, 789192, 789312, 790416, 791208, 791280, 791328, 791928, 792108, 798912, 799128, 800712, 806712, 807120, 807132, 807192, 807912, 814752, 816816, 818160, 818916, 820512, 822744, 823716, 824472, 825174, 825714, 827550, 827658, 827955, 829467, 830412, 831117, 831600, 831762, 831810, 831831, 839160, 839181, 839916, 840510, 841023, 841104, 843102, 845100, 845910, 847422, 851148, 851220, 851742, 852471, 857142, 857250, 857628, 857925, 862512, 862758, 862947, 865728, 866712, 867120, 867132, 867192, 867912, 871200, 871320, 871332, 871425, 871920, 871932, 871992, 874125, 879120, 879132, 879192, 879912, 888216, 891054, 891540, 891594, 891723, 892755, 894510, 895725, 899154, 900801, 901152, 903021, 903210, 903231, 904041, 908010, 908091, 908901, 909321, 910203, 911043, 911358, 911520, 911736, 911952, 912030, 912093, 912303, 916083, 920241, 920376, 923076, 923580, 925113, 925614, 930321, 931176, 931203, 933513, 934143, 935130, 935193, 935613, 935832, 940410, 940491, 941430, 941493, 941652, 943137, 943173, 951300, 951588, 951930, 951993, 952380, 956130, 956193, 956613, 958032, 958320, 958332, 958392, 958632, 958716, 959832, 960741, 962037, 962307, 970137, 971028, 980100, 980910, 980991, 989010, 989091, 989901]

real    2m10.819s
user    2m10.683s
sys     0m0.192s

```

### How it works

```
ȷ6ÇÐf   Main link. No arguments.

ȷ6      Yield 1e6 = 1,000,000.
  ÇÐf   Filter; keep numbers in [1, ..., 1e6] for which the helper link returns
        a truthy value.

ÆḌṢ€ċṢ  Helper link. Argument: n

ÆḌ      Compute all proper divisors of n.
  Ṣ€    Sort each proper divisor's digits.
     Ṣ  Sort n's digits.
   ċ    Count the occurrences of the result to the right in the result to the left.

```
> 3 votes

# Answer
# Brachylog, 12 bytes

```
ℕf{k∋p.!}?ẉ⊥

```

Try it online!

This might time out before printing anything though (and if it doesn't it will only get to print 3105).

### Explanation

This prints those numbers indefinitely, as the author said it was acceptable that the program would print numbers bigger than 6 digits.

This is way too slow; you can use this program (and change `8300` by any `N`) to start printing from numbers stricly greater than `N`.

```
ℕ               Natural number: The Input is a natural number
 f              Factors: compute the factors of the Input
  {     }?      Call a predicate with the main Input as its output and the factors as Input
   k            Knife: remove the last factor(which is the Input itself)
    ∋           In: take one of those factors
     p.         Permute: the Output is a permutation of that factor
       !        Cut: ignore other possible permutations
         ?ẉ     Writeln: write the Input to STDOUT, followed by a line break
           ⊥    False: backtrack to try another value for the Input

```

*As @ais523 pointed out, we need a cut to avoid printing a number multiple times if several of its factors are permutations of it.*
> 3 votes

# Answer
## JavaScript (ES6), ~~103~~~~96~~ 94 bytes

An anonymous function that returns the array of matching integers.

```
_=>[...Array(1e6).keys(F=i=>[...i+''].sort()+0)].filter(n=>n*(R=i=>F(n/i--)==F(n)||R(i)%i)(9))

```

### Formatted and commented

```
_ =>                                // main function, takes no input
  [...Array(1e6).keys(              // define an array of 1,000,000 entries
    F = i => [...i + ''].sort() + 0 // define F: function used to normalize a string by
  )]                                // sorting its characters
  .filter(n =>                      // for each entry in the array:
    n * (                           // force falsy result for n = 0
      R = i =>                      // define R: recursive function used to test if
        F(n / i--) == F(n) ||       // n/i is an anagram of n, with i in [1 … 9]
        R(i) % i                    // F(n/1) == F(n) is always true, which allows to stop
    )                               // the recursion; but we need '%i' to ignore this result
    (9)                             // start recursion with i = 9
  )                                 //

```

### Divisor statistics

For 6-digit integers, each ratio from `2` to `9` between a matching integer `n` and its anagram is encountered at least once. But some of them appear just a few times:

```
 divisor | occurrences | first occurrence
---------+-------------+---------------------
    2    |    12       | 251748 / 2 = 125874
    3    |    118      | 3105   / 3 = 1035
    4    |    120      | 7128   / 4 = 1782
    5    |    4        | 714285 / 5 = 142857
    6    |    34       | 8316   / 6 = 1386
    7    |    49       | 9513   / 7 = 1359
    8    |    2        | 911736 / 8 = 113967
    9    |    23       | 9801   / 9 = 1089

```

### Test

The test below is limited to the range `[1 ... 39999]` so that it doesn't take too much time to complete.

```
let f =

_=>[...Array(4e4).keys(F=i=>[...i+''].sort()+0)].filter(n=>n*(R=i=>F(n/i--)==F(n)||R(i)%i)(9))

console.log(f())
```
> 3 votes

# Answer
## Pyke, 14 bytes

```
~1#`Sili-m`mS{

```

Try it here!

Should output all numbers like this but times out.

Test the algorithm here!
> 2 votes

# Answer
# Perl 6, 59 bytes

```
{grep {grep .comb.Bag===*.comb.Bag,grep $_%%*,2..^$_}

```

Terribly slow brute-force solution.

It returns a lazy sequence, so I could check the first few results, but it won't reach all results in reasonable time. (Should I mark it as non-competing?)
> 2 votes

# Answer
# Pure Bash, ~~128~~ ~~126~~ ~~122~~ ~~121~~ 120 bytes

```
for((;n<6**8;)){
c=0
for((j=++n;j;j/=10)){((c+=8**(j%10)));}
for k in ${a[c]};{((n%k))||{ echo $n;break;};}
a[c]+=\ $n
}

```

Try it online!

(This program is reasonably fast -- it took only 14 minutes to run through all the 6-digit numbers on my MacBook. Unfortunately TIO times out because it imposes a running-time limit of 1 minute, which is only enough time to get through the 5-digit numbers or so.)

# Bash + Unix utilities, 117 bytes

```
for n in {1..999999}
{
c=$(bc<<<0`sed 's/\(.\)/+8^\1/g'<<<$n`)
for k in ${a[c]};{((n%k))||echo $n;}
a[c]+=\ $n
}|uniq

```

This is shorter than the pure bash version, but quite a bit slower, presumably due in good part to all the forking going on.
> 2 votes

# Answer
# 05AB1E, 15 bytes

```
[¼¾œJv¾Ñ¨Dyåi¾,

```

Explanation:

```
[               # Start of infinite loop
 ¼              # Increase counter_variable by 1
  ¾œJv          # Loop through all the permutations of counter_variable
      ¾Ñ¨Dyå    # Check if a divisor of counter_variable is a permutation of counter_variable
            i¾, # If so, print counter_variable

```

Try it online! (this won't work, it will time out)
> 1 votes

# Answer
# Japt, 23 bytes

```
L³o f_ì á ¤fg mì f!vZ l

```

Try it online! Note that the linked code only calculates up to 1e4 because 1e6 times out on TIO.
> 1 votes

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

Times out on TIO due to infinite loop.
Saved 2 bytes as we could output more than 6-digit numbers according to OPs comment.

```
[NÑ¨€{N{å–

```

Try it online!

**Explanation**

```
[            # infinite loop with iteration index N
 NÑ          # get a list of all divisors of N
   ¨         # remove N from that list
    €{       # sort each entry in the list of divisors
      N{     # sort N
        å–   # output N if N is in the list

```
> 1 votes

# Answer
## Batch, 263 bytes

```
@echo off
set e=exit/b
for /l %%n in (1,1,999999)do call:n %%n
%e%
:n
call:c %1 1 0
for /l %%f in (2,1,9)do call:c %1 %%f %c%&&echo %1&&%e%
%e%
:c
set/ar=%1%%%2,d=%1/%2,c=-%3
if %r% gtr 0 %e%1
:l
set/ac+=1^<^<d%%10*3,d/=10
if %d% gtr 0 goto l
%e%%c%

```

Slow. As in, takes over a day to finish on my PC. Explanation: the `c` subroutine divides its first two arguments. If the remainder is zero, it then calculates the hash of the result by calculating the sum of the nth powers of 8 for each digit. This hash function, stolen from the bash answer, only collides on anagrams. (It would work for seven digit numbers but I don't have all fortnight.) The third argument is subtracted, and the subroutine exits with a truthy result if this is zero. The `n` subroutine calls the `c` subroutine once to calculate the hash, then eight more times to compare the hash; if it finds a collision, it prints `n` and exits the subroutine early.
> 1 votes

# Answer
# Haskell (Lambdabot), 87 bytes

```
[x|x<-[1..],any(\y->show x/=y&&head y/='0'&&rem x(read y::Int)==0)$permutations$show x]

```

Try it online!

This is probably unoptimal, as it's my first Haskell golf
> 1 votes

# Answer
# Python 2, 98 bytes

```
s=sorted;print filter(None,[[x for i in range(x)if s(`x`)==s(`i`)and x%i<1]for x in range(10**6)])

```
> 0 votes

# Answer
# Ruby, 96 bytes

```
->a{a.chars.permutation.map(&:join).reject{|x|/^0+/.match(x)||x==a}.detect{|n|a.to_i%n.to_i==0}}

```

The permutation function gives a lot of duplicates, so a large part of this is weedng those out.

Try it online!
> 0 votes

# Answer
# Scala, 101 bytes

```
for(x<-LazyList from 9)s"$x".permutations.find{d=>d.head>48&d.toInt!=x&x%d.toInt<1}map(_=>println(x))

```

Try it in Scastie (For whatever reason, TIO doesn't recognize LazyLists, not even after importing it explicitly)

---

# Scala (with recursion), 104 bytes

```
def f(x:Int){s"$x".permutations.find{d=>d.head>48&d.toInt!=x&x%d.toInt<1}map(_=>println(x))
f(x+1)}
f(9)

```

Do NOT try it online!. Try this modified version instead.
> 0 votes

---
Tags: code-golf, integer
---


# Question
Title: Redirect HTTP links to HTTPS with Javascript
# What is the shortest way to secure a site with Javascript?

I am new to Code Golfing, and this is what I've come up with so far. I bet that this could be improved though:

## Challenge:

> Make a script which redirects `http://` to `https://` with the least bytes of code

## Attempts:

Original code (150ish BYTES!):

```
if (window.location.protocol != "https:") {
  window.location.href =
    "https:" + window.location.href.substring(window.location.protocol.length);
}

```

My code so far (68 bytes):

```
var l=location;':'==l.protocol[4]&&(l.href=l.href.replace(':','s:'))

```

Updated, thanks to @mypronounismonicareinstate (52 bytes):

```
l=location;l["protocol"][5]||(l["protocol"]="https")

```

Thanks to @arnauld (45 bytes):

```
(l=location)[p='protocol'][5]||(l[p]='https')

```

This works, thanks to @anderskaseorg (38 bytes):

```
with(location)protocol='https'+href[4]

```

However, this last answer would not be commonly used on a real site

Could this be minified more?

# Answer
> 7 votes
# ~~39~~ 38 bytes

```
with(location)protocol='https'+href[4]

```

### How it works

* If `location.href` starts with `http:`, this assigns `location.protocol = 'https:'`.
* If `location.href` starts with `https:`, this assigns `location.protocol = 'httpss'`. According to the specification, this should have no effect because `httpss` is neither `http` nor `https`. Firefox obeys this specification. Chrome seems to try to find an external app to open the `httpss` scheme (bug).

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


# Question
Title: Constructing an evil maze against random exploration
RollerCoaster Tycoon 2's maze is the inspiration for this question. Credit to Marcel Vos for thoroughly breaking the classic RCT2 AI. The pathfinding AI in this question is the AI in the latest version of OpenRCT2 at the time of writing, which was updated in response to that video.

---

Suppose a guest enters a \\$w \times h\\$ grid maze with the following strategy in mind:

> After every step I pick a random valid direction except backwards, unless I have no other choice but to go back.

We are evil and wish to construct the maze that takes the most amount of time *on average* to solve using the above strategy.

---

This is a code-challenge. The winner is the answer that contains a \\$100 \times 100\\$ maze with the greatest mean solve time using the above strategy. In the case of a tie the earlier poster wins.

A \\$w \times h\\$ maze is a \\$w \times h\\$ grid of square tiles. It has *two* designated start tiles along the border, connected either horizontally or vertically, and similarly two designated exit squares, along the border, connected either horizontally or vertically. Between each tile there may or may not be a wall (with the exception of the two start and two end tiles, they must be directly connected to their partner). There is always a border of walls around the grid.

The guest enters with a 50/50% chance on either start tile, *facing away from the other tile*. Then the guest starts exploring the maze one step at a time. At the start of a step the guest looks to its left, forward and right (relative to its current direction) and checks for walls. It chooses a random new direction with uniform chance from the unobstructed directions. If and only if all other directions are obstructed it chooses to go backwards instead.

The guest wanders around as such until it reaches one of the two exit squares, which will cause the guest to immediately exit. The average number of steps it takes for this to happen is your score, the bigger the better. If the start and exit are not connected your maze is invalid and has no score.

---

To accurately score mazes I wrote a judge program in Python that uses Markov chains to compute your score mathematically. It requires Python 3, `numpy`, `scipy` and `imageio` to run (an optional dependency for a speedup is `scikit-umfpack`). In addition, the judge contains functions to output an image of your maze, as well as a compressed representation of your maze. Please familiarize yourself with the judge program before starting this challenge.

**Please include (a link to) a \\$100\times 100\\$ compressed maze as generated by the judge program in your answer. Your answer will be scored based on this. An answer without a concrete, specific solution maze is invalid.**

# Answer
# No dead ends near the entrance, ~~21,477,560~~ 21,485,005

Try it online!

Yay, 21 million. The giant horizontal segments up to row 19 are also removed, so about 20% of the entire grid is just an open space.

Also, as the "real maze" starts at the leftmost column, moving the entrance to the top right gives a slight bump to the score. (Thanks to @Neil)

---

# Previous version, 20,211,703

Try it online!

Yes, 20 million. It's actually good to remove some dead ends and add some open spaces near the entrance, but it stops being good as it gets sufficiently far away from it.

This is a derivation from width-3 dead end maze by removing some h-walls (it's called h-walls in the code, but it is a vertical segment in the image):

* The h-walls from row 1 to row 22 (inclusive) are entirely removed.
* The h-walls from row 23 to row 40 (inclusive) are reduced by half, keeping the odd indices.
> 11 votes

# Answer
# Tridents, score ~~21,947,177~~ 21,951,598

```
UEsDBBQAAAAIAAAAIQAL/+yrSgAAAIgAAAAJABQAYXJyXzAubnB5AQAQAIgAAAAAAAAASgAAAAAAAACb7BfqGxDJyFDGUK2eklqcXKRupaBuk2mirqOgnpZfVFKUmBefX5SSChJ3S8wpTgWKF2ckFqQC+RpGOpo6CrUKFACuFAYGBhAGAFBLAwQUAAAACAAAACEAlmPInE8AAACQAAAACQAUAGFycl8xLm5weQEAEACQAAAAAAAAAE8AAAAAAAAAm+wX6hsQychQxlCtnpJanFykbqWgbpNpoq6joJ6WX1RSlJgXn1+UkgoSd0vMKU4FihdnJBakAvkaRjoKRpo6CrUKZAOuZAYGhiQgToZiAFBLAwQUAAAACAAAACEAX1d180sAAACQAAAACQAUAGFycl8yLm5weQEAEACQAAAAAAAAAEsAAAAAAAAAm+wX6hsQychQxlCtnpJanFykbqWgbpNpoq6joJ6WX1RSlJgXn1+UkgoSd0vMKU4FihdnJBakAvkaRjoKRpo6CrUKZAMuBihghNIAUEsDBBQAAAAIAAAAIQCi1p2qngAAACwnAAAJABQAYXJyXzMubnB5AQAQACwnAAAAAAAAngAAAAAAAADt2jEKAkEMheFM6ynSRWGK3XI9gJ1iY2EloztiIa7MLDbqKbywuydYcLD7QwjkEfgukM9mt97unTzkaW3Mp2RLtdexNq927lKfwu3QpTaO+SpccxzyfAn3OOzzpvFaV9XC61t/q5mIcyJlc6rceFfUGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGP8zpPCVbNr4AlBLAwQUAAAACAAAACEAXL51PqgAAAAsJwAACQAUAGFycl80Lm5weQEAEAAsJwAAAAAAAKgAAAAAAAAA7dohDgIxEIXhqeUUdQNJxa5cDoCDYBAoUtgSBGFJSzDAKbgwW4GFDTWI/7V5Scd8re9zsZov10auctM2pF3UqdX7tlZndd/FS/SnTRfbkOczf0yhn6eDP4f+PK6rytmmmTj7sL9lJGIkp6S/xORlSnoQUrohICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICD+kij7f2UGvULeNynpT3kBUEsBAhQAFAAAAAgAAAAhAAv/7KtKAAAAiAAAAAkAAAAAAAAAAAAAAIABAAAAAGFycl8wLm5weVBLAQIUABQAAAAIAAAAIQCWY8icTwAAAJAAAAAJAAAAAAAAAAAAAACAAYUAAABhcnJfMS5ucHlQSwECFAAUAAAACAAAACEAX1d180sAAACQAAAACQAAAAAAAAAAAAAAgAEPAQAAYXJyXzIubnB5UEsBAhQAFAAAAAgAAAAhAKLWnaqeAAAALCcAAAkAAAAAAAAAAAAAAIABlQEAAGFycl8zLm5weVBLAQIUABQAAAAIAAAAIQBcvnU+qAAAACwnAAAJAAAAAAAAAAAAAACAAW4CAABhcnJfNC5ucHlQSwUGAAAAAAUABQATAQAAUQMAAAAA

```

Based on @Bubbler's answer, but some tinkering about with a wall finding algorithm led me to tweak the layout slightly:

Edit: Slightly improved my score by changing the exit orientation, which allowed me to use the trident shape there too. For some reason (I'm not ruling out human error) not only did @isaacg's "tricky routing" not affect the score for this layout but also my "trident exit" doesn't seem to affect the score for his layout...

I actually wrote a script where I could parametrise the number of long horizontal lines, how many of them had teeth, how many of them had gappy teeth, and how many of the ends had prongs, and this was the best I could come up with (also my wall finder couldn't find a way of improving it). Try it online!
> 11 votes

# Answer
# Two sides of mazes, score 21987725

```
UEsDBBQAAAAIAAAAIQChBYC8SQAAAJAAAAAJAAAAYXJyXzAubnB5m+wX6hsQychQxlCtnpJanFykbqWgbpNpoa6joJ6WX1RSlJgXn1+UkgoSd0vMKU4FihdnJBakAvkaRjqaOgq1ChQArhQGCIDRAFBLAwQUAAAACAAAACEAkzeCEkwAAACgAAAACQAAAGFycl8xLm5weZvsF+obEMnIUMZQrZ6SWpxcpG6loG6TaaGuo6Cell9UUpSYF59flJIKEndLzClOBYoXZyQWpAL5GkY6CkaaOgq1CmQDLgYcgBFKAwBQSwMEFAAAAAgAAAAhAJBqs1pOAAAAoAAAAAkAAABhcnJfMi5ucHmb7BfqGxDJyFDGUK2eklqcXKRupaBuk2mhrqOgnpZfVFKUmBefX5SSChJ3S8wpTgWKF2ckFqQC+RpGOgpGmjoKtQpkA65kBghAp5OgNABQSwMEFAAAAAgAAAAhAEghScnMAAAALCcAAAkAAABhcnJfMy5ucHnt2jEOgjAUgOF29RTdqgkDjHgAN42Lg5NBqXEwaopxUU/hhQVP8F4xhOF/IS+hy5eSf+Sz2izXW2se5unr0Byinzv/2hc+c/54jfdYXXbXWIfufFGdm9CeN6fqFtr3aVlmrsjzWebeLm0mJnnsb0l2H8MKHwwMDAwMDAwMDAwMDAwMDAwMDAwMjP8byTPAPVRGH0Vs9PhaY7pHukBXGoWupAJdaRS6kgp0pVHoSirQlUahK6lAVxqFrqQCXWmUsXRlBrhHt5IF8U9k9gtQSwMEFAAAAAgAAAAhACNNXj3ZAAAALCcAAAkAAABhcnJfNC5ucHnt2rEKwjAUheFk9SmyRaFDO9YHcFNcHJyk2oiDWEnFRX0KX9g6uGq5gXKRP4RAu3w9J3fsc7GaL9fWXM3N16HdRT91/r4tfOb8vomXWJ02TazD+/2sOrahe98eqnPonsdFnmeuLCeZezjZGhnpsr3PBMJa2+tMIPpuCAgICAgICAgICAgICAgICAgICAiIb1u4dKUQx9BF/MV1D0AwUXqKEmdQRTBReooSZ1BFMFF6ihJnUEUwUXqKEmdQRTBReooSZ1BF/MNEJTQ1RFH9/r9KuW7z+cIfpzUvUEsBAhQDFAAAAAgAAAAhAKEFgLxJAAAAkAAAAAkAAAAAAAAAAAAAAIABAAAAAGFycl8wLm5weVBLAQIUAxQAAAAIAAAAIQCTN4ISTAAAAKAAAAAJAAAAAAAAAAAAAACAAXAAAABhcnJfMS5ucHlQSwECFAMUAAAACAAAACEAkGqzWk4AAACgAAAACQAAAAAAAAAAAAAAgAHjAAAAYXJyXzIubnB5UEsBAhQDFAAAAAgAAAAhAEghScnMAAAALCcAAAkAAAAAAAAAAAAAAIABWAEAAGFycl8zLm5weVBLAQIUAxQAAAAIAAAAIQAjTV492QAAACwnAAAJAAAAAAAAAAAAAACAAUsCAABhcnJfNC5ucHlQSwUGAAAAAAUABQATAQAASwMAAAAA

```

Based on @Neil's trident design, but I added an extra side of mazes, and also did some tricky routing right at the end to improve the score a bit more.

It turned out to be optimal to have the blank region be a perfect square, which I didn't expect, due to the asymmetry of the maze region. The blank region is 58x58, and there are 14 rows of maze on each side.

I really wanted to get to 22 million, but I had to stop just short. I tried lots of designs that didn't improve anything, like making the blank region nonrectangular, or making the design symmetrical across the main axis. None of that helped.

Try it online!
> 9 votes

# Answer
# Even more dead ends, 16,555,009.5

```
UEsDBBQAAAAIAAAAIQChBYC8SQAAAJAAAAAJABQAYXJyXzAubnB5AQAQAJAAAAAAAAAASQAAAAAAAACb7BfqGxDJyFDGUK2eklqcXKRupaBuk2mhrqOgnpZfVFKUmBefX5SSChJ3S8wpTgWKF2ckFqQC+RpGOpo6CrUKFACuFAYIgNEAUEsDBBQAAAAIAAAAIQCcpkBwTAAAAKAAAAAJABQAYXJyXzEubnB5AQAQAKAAAAAAAAAATAAAAAAAAACb7BfqGxDJyFDGUK2eklqcXKRupaBuk2mhrqOgnpZfVFKUmBefX5SSChJ3S8wpTgWKF2ckFqQC+RpGOgpGmjoKtQpkAy4GNMCIxgcAUEsDBBQAAAAIAAAAIQAsPfLMTwAAAKAAAAAJABQAYXJyXzIubnB5AQAQAKAAAAAAAAAATwAAAAAAAACb7BfqGxDJyFDGUK2eklqcXKRupaBuk2mhrqOgnpZfVFKUmBefX5SSChJ3S8wpTgWKF2ckFqQC+RpGOgpGmjoKtQpkAy4GKEhmQAVJUBoAUEsDBBQAAAAIAAAAIQAYEnl9jgAAACwnAAAJABQAYXJyXzMubnB5AQAQACwnAAAAAAAAjgAAAAAAAADtzbENwjAUhGG7ZYrXPZBcxGUYIB0oDUUqZIgRRUSQHaUBpsjCmBWQqPhP19w137I/7NrOmtk8tI/5nHQr+jx5daKXMU0p3I5j6uPnb8KQY/nzNdxj2eu6duKrauPkJd9lZaz9eTEwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDD+23gDUEsDBBQAAAAIAAAAIQBg04Z/fgAAACwnAAAJABQAYXJyXzQubnB5AQAQACwnAAAAAAAAfgAAAAAAAADt2jEKwkAQheFJ6ymmG4UtkjIewE6xsbAKG7NiIUZ2g43JKbxwkisEAhb/42PgvTPM73Q5nq+ZfORrTUi3aHu1vi7Mqd3b2EX/qtrYhHk/+GcK054e/h2mvi3y3GlZ7pwOuiwbyWTOqhcAAAAAAAAAAAAAAAAA8M/W/iITGQFQSwECFAMUAAAACAAAACEAoQWAvEkAAACQAAAACQAAAAAAAAAAAAAAgAEAAAAAYXJyXzAubnB5UEsBAhQDFAAAAAgAAAAhAJymQHBMAAAAoAAAAAkAAAAAAAAAAAAAAIABhAAAAGFycl8xLm5weVBLAQIUAxQAAAAIAAAAIQAsPfLMTwAAAKAAAAAJAAAAAAAAAAAAAACAAQsBAABhcnJfMi5ucHlQSwECFAMUAAAACAAAACEAGBJ5fY4AAAAsJwAACQAAAAAAAAAAAAAAgAGVAQAAYXJyXzMubnB5UEsBAhQDFAAAAAgAAAAhAGDThn9+AAAALCcAAAkAAAAAAAAAAAAAAIABXgIAAGFycl80Lm5weVBLBQYAAAAABQAFABMBAAAXAwAAAAA=

```

The guests now have 3 choices per intersection for most intersections, however there are only about 2/3 as many intersections. Of 34 corridors, the first and last corridors have 98 two-way branches, and 32 corridors have 2 two-way branches and 98 three-way branches. (I didn't count carefully)
> 8 votes

# Answer
# Empty maze, score 51113

```
UEsDBBQAAAAIAAAAIQChBYC8SQAAAJAAAAAJAAAAYXJyXzAubnB5m+wX6hsQychQxlCtnpJanFykbqWgbpNpoa6joJ6WX1RSlJgXn1+UkgoSd0vMKU4FihdnJBakAvkaRjqaOgq1ChQArhQGCIDRAFBLAwQUAAAACAAAACEAkzeCEkwAAACgAAAACQAAAGFycl8xLm5weZvsF+obEMnIUMZQrZ6SWpxcpG6loG6TaaGuo6Cell9UUpSYF59flJIKEndLzClOBYoXZyQWpAL5GkY6CkaaOgq1CmQDLgYcgBFKAwBQSwMEFAAAAAgAAAAhAJBqs1pOAAAAoAAAAAkAAABhcnJfMi5ucHmb7BfqGxDJyFDGUK2eklqcXKRupaBuk2mhrqOgnpZfVFKUmBefX5SSChJ3S8wpTgWKF2ckFqQC+RpGOgpGmjoKtQpkA65kBghAp5OgNABQSwMEFAAAAAgAAAAhAPN9K5lvAAAALCcAAAkAAABhcnJfMy5ucHntyDEOgkAUANGl5RS/+5JsASUewE5CY0FFVlliYYTsEhr1FFwYuIIJ3bxuZqlu17pJzGw+2vn4CHoW/d4LtaL9EKbg3u0QOr//i3tFv/34dKPf+lSWVoo8z6z85D+pAQAAAAAAAAAAAAAAAADgYCtQSwMEFAAAAAgAAAAhACFK7HxvAAAALCcAAAkAAABhcnJfNC5ucHntyDEOgkAUANGl5RS/+5JsASUewE5CY0FFVlliYYTsEhr1FFwYuIIJ3bxuZqlu17pJzGw+2vn4CHoW/d4LtaL9EKbg3u0QOr//i3tFv/34dKPf+lTkuZWyzKz85D+pAQAAAAAAAAAAAAAAAADgYCtQSwECFAMUAAAACAAAACEAoQWAvEkAAACQAAAACQAAAAAAAAAAAAAAgAEAAAAAYXJyXzAubnB5UEsBAhQDFAAAAAgAAAAhAJM3ghJMAAAAoAAAAAkAAAAAAAAAAAAAAIABcAAAAGFycl8xLm5weVBLAQIUAxQAAAAIAAAAIQCQarNaTgAAAKAAAAAJAAAAAAAAAAAAAACAAeMAAABhcnJfMi5ucHlQSwECFAMUAAAACAAAACEA830rmW8AAAAsJwAACQAAAAAAAAAAAAAAgAFYAQAAYXJyXzMubnB5UEsBAhQDFAAAAAgAAAAhACFK7HxvAAAALCcAAAkAAAAAAAAAAAAAAIAB7gEAAGFycl80Lm5weVBLBQYAAAAABQAFABMBAACEAgAAAAA=

```

Try it online! Just to get the ball rolling.
> 5 votes

# Answer
# Zigzag path, score 12,582,074

```
UEsDBBQAAAAIAAAAIQChBYC8SQAAAJAAAAAJAAAAYXJyXzAubnB5m+wX6hsQychQxlCtnpJanFykbqWgbpNpoa6joJ6WX1RSlJgXn1+UkgoSd0vMKU4FihdnJBakAvkaRjqaOgq1ChQArhQGCIDRAFBLAwQUAAAACAAAACEAkzeCEkwAAACgAAAACQAAAGFycl8xLm5weZvsF+obEMnIUMZQrZ6SWpxcpG6loG6TaaGuo6Cell9UUpSYF59flJIKEndLzClOBYoXZyQWpAL5GkY6CkaaOgq1CmQDLgYcgBFKAwBQSwMEFAAAAAgAAAAhAJVYfYFPAAAAoAAAAAkAAABhcnJfMi5ucHmb7BfqGxDJyFDGUK2eklqcXKRupaBuk2mhrqOgnpZfVFKUmBefX5SSChJ3S8wpTgWKF2ckFqQC+RpGOgpGmjoKtQpkAy4GKEhiQAXJUBoAUEsDBBQAAAAIAAAAIQDzfSuZbwAAACwnAAAJAAAAYXJyXzMubnB57cgxDoJAFADRpeUUv/uSbAElHsBOQmNBRVZZYmGE7BIa9RRcGLiCCd28bmapbte6ScxsPtr5+Ah6Fv3eC7Wi/RCm4N7tEDq//4t7Rb/9+HSj3/pUllaKPM+s/OQ/qQEAAAAAAAAAAAAAAAAA4GArUEsDBBQAAAAIAAAAIQAos+JrlgAAACwnAAAJAAAAYXJyXzQubnB57doxDsIwDIVhZ+UU3gxShnYsB2ADsTAwobQNYkAUJYgFegouTHuFStl+Wx7eW74L+Hc47Y9nJ2/5WB9zl2yr9m1r82rXIb1SeFyG1Me534V7jlOfb+EZp7yuq8pr02y8jrpsVuJESp8rvhAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBDLieJvZPIHUEsBAhQDFAAAAAgAAAAhAKEFgLxJAAAAkAAAAAkAAAAAAAAAAAAAAIABAAAAAGFycl8wLm5weVBLAQIUAxQAAAAIAAAAIQCTN4ISTAAAAKAAAAAJAAAAAAAAAAAAAACAAXAAAABhcnJfMS5ucHlQSwECFAMUAAAACAAAACEAlVh9gU8AAACgAAAACQAAAAAAAAAAAAAAgAHjAAAAYXJyXzIubnB5UEsBAhQDFAAAAAgAAAAhAPN9K5lvAAAALCcAAAkAAAAAAAAAAAAAAIABWQEAAGFycl8zLm5weVBLAQIUAxQAAAAIAAAAIQAos+JrlgAAACwnAAAJAAAAAAAAAAAAAACAAe8BAABhcnJfNC5ucHlQSwUGAAAAAAUABQATAQAArAIAAAAA

```

Try it online! Creates a giant zigzag, something like this but larger:

```
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| S                                                             |
+   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +
| S                                                             |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+   +
|                                                               |
+   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +
|                                                               |
+   +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
|                                                               |
+   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +
|                                                               |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+   +
|                                                               |
+   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +
|                                                               |
+   +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
|                                                               |
+   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +
|                                                               |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+   +
|                                                               |
+   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +
|                                                               |
+   +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
|                                                               |
+   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +
|                                                               |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+   +
| E                                                             |
+   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +
| E                                                             |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

```
> 3 votes

# Answer
# The original dead end guest trap, 16,505,047.166666668

```
UEsDBBQAAAAIAAAAIQChBYC8SQAAAJAAAAAJABQAYXJyXzAubnB5AQAQAJAAAAAAAAAASQAAAAAAAACb7BfqGxDJyFDGUK2eklqcXKRupaBuk2mhrqOgnpZfVFKUmBefX5SSChJ3S8wpTgWKF2ckFqQC+RpGOpo6CrUKFACuFAYIgNEAUEsDBBQAAAAIAAAAIQCTN4ISTAAAAKAAAAAJABQAYXJyXzEubnB5AQAQAKAAAAAAAAAATAAAAAAAAACb7BfqGxDJyFDGUK2eklqcXKRupaBuk2mhrqOgnpZfVFKUmBefX5SSChJ3S8wpTgWKF2ckFqQC+RpGOgpGmjoKtQpkAy4GHIARSgMAUEsDBBQAAAAIAAAAIQAsPfLMTwAAAKAAAAAJABQAYXJyXzIubnB5AQAQAKAAAAAAAAAATwAAAAAAAACb7BfqGxDJyFDGUK2eklqcXKRupaBuk2mhrqOgnpZfVFKUmBefX5SSChJ3S8wpTgWKF2ckFqQC+RpGOgpGmjoKtQpkAy4GKEhmQAVJUBoAUEsDBBQAAAAIAAAAIQCiugFzcQAAACwnAAAJABQAYXJyXzMubnB5AQAQACwnAAAAAAAAcQAAAAAAAADtyDEOgkAURdGhdRW/+5hMASUugA5jY2FlRhlDQcDMEBphFWwY3AIJ3X2nene53qvbIzGj+Wnt4zvoRXR65WpFP30Yguuefaj9v5eujX7rsXFfv/20KKzkWXa2Msu+nUwCAAAAAAAAAAAAAAAAAMCxVlBLAwQUAAAACAAAACEAKLPia5YAAAAsJwAACQAUAGFycl80Lm5weQEAEAAsJwAAAAAAAJYAAAAAAAAA7doxDsIwDIVhZ+UU3gxShnYsB2ADsTAwobQNYkAUJYgFegouTHuFStl+Wx7eW74L+Hc47Y9nJ2/5WB9zl2yr9m1r82rXIb1SeFyG1Me534V7jlOfb+EZp7yuq8pr02y8jrpsVuJESp8rvhAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBDLieJvZPIHUEsBAhQDFAAAAAgAAAAhAKEFgLxJAAAAkAAAAAkAAAAAAAAAAAAAAIABAAAAAGFycl8wLm5weVBLAQIUAxQAAAAIAAAAIQCTN4ISTAAAAKAAAAAJAAAAAAAAAAAAAACAAYQAAABhcnJfMS5ucHlQSwECFAMUAAAACAAAACEALD3yzE8AAACgAAAACQAAAAAAAAAAAAAAgAELAQAAYXJyXzIubnB5UEsBAhQDFAAAAAgAAAAhAKK6AXNxAAAALCcAAAkAAAAAAAAAAAAAAIABlQEAAGFycl8zLm5weVBLAQIUAxQAAAAIAAAAIQAos+JrlgAAACwnAAAJAAAAAAAAAAAAAACAAUECAABhcnJfNC5ucHlQSwUGAAAAAAUABQATAQAAEgMAAAAA

```

The original design in Marcel Vos's video. 50 corridors, each with 99 intersections, gives 4950 two-way branches (maybe off by one or two) for guests to choose between.
> 2 votes

# Answer
# Slightly fewer dead ends, score 16,663,349

```
UEsDBBQAAAAIAAAAIQChBYC8SQAAAJAAAAAJAAAAYXJyXzAubnB5m+wX6hsQychQxlCtnpJanFykbqWgbpNpoa6joJ6WX1RSlJgXn1+UkgoSd0vMKU4FihdnJBakAvkaRjqaOgq1ChQArhQGCIDRAFBLAwQUAAAACAAAACEAkzeCEkwAAACgAAAACQAAAGFycl8xLm5weZvsF+obEMnIUMZQrZ6SWpxcpG6loG6TaaGuo6Cell9UUpSYF59flJIKEndLzClOBYoXZyQWpAL5GkY6CkaaOgq1CmQDLgYcgBFKAwBQSwMEFAAAAAgAAAAhAJVYfYFPAAAAoAAAAAkAAABhcnJfMi5ucHmb7BfqGxDJyFDGUK2eklqcXKRupaBuk2mhrqOgnpZfVFKUmBefX5SSChJ3S8wpTgWKF2ckFqQC+RpGOgpGmjoKtQpkAy4GKEhiQAXJUBoAUEsDBBQAAAAIAAAAIQAhaJ1vdQAAACwnAAAJAAAAYXJyXzMubnB57cgxDoJAFEXRoXUVv/uaTAElLsBOY0NBRQYZY2HEzBgaYBVsGNgCBbG491TvTbfiei8T05leGx8fQc+iQ52pFX224Rfcp2pD49f/4t7RL398ua9f9jHPrWRperIyyrYOZocSAAAAAAAAAAAAAAAAAMDf2qMZUEsDBBQAAAAIAAAAIQAos+JrlgAAACwnAAAJAAAAYXJyXzQubnB57doxDsIwDIVhZ+UU3gxShnYsB2ADsTAwobQNYkAUJYgFegouTHuFStl+Wx7eW74L+Hc47Y9nJ2/5WB9zl2yr9m1r82rXIb1SeFyG1Me534V7jlOfb+EZp7yuq8pr02y8jrpsVuJESp8rvhAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBDLieJvZPIHUEsBAhQDFAAAAAgAAAAhAKEFgLxJAAAAkAAAAAkAAAAAAAAAAAAAAIABAAAAAGFycl8wLm5weVBLAQIUAxQAAAAIAAAAIQCTN4ISTAAAAKAAAAAJAAAAAAAAAAAAAACAAXAAAABhcnJfMS5ucHlQSwECFAMUAAAACAAAACEAlVh9gU8AAACgAAAACQAAAAAAAAAAAAAAgAHjAAAAYXJyXzIubnB5UEsBAhQDFAAAAAgAAAAhACFonW91AAAALCcAAAkAAAAAAAAAAAAAAIABWQEAAGFycl8zLm5weVBLAQIUAxQAAAAIAAAAIQAos+JrlgAAACwnAAAJAAAAAAAAAAAAAACAAfUBAABhcnJfNC5ucHlQSwUGAAAAAAUABQATAQAAsgIAAAAA

```

Try it online! Based on the original dead end guest trap as posted by @qwr, but removing some of the dead ends like this manages to increase the score:

```
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| S     |   |   |   |   |   |   |   |   |   |   |   |   |       |
+   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +
| S                                                             |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+   +
|       |   |   |   |   |   |   |   |   |   |   |   |   |       |
+   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +
|                                                               |
+   +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
|       |   |   |   |   |   |   |   |   |   |   |   |   |       |
+   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +
|                                                               |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+   +
|       |   |   |   |   |   |   |   |   |   |   |   |   |       |
+   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +
|                                                               |
+   +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
|       |   |   |   |   |   |   |   |   |   |   |   |   |       |
+   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +
|                                                               |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+   +
|       |   |   |   |   |   |   |   |   |   |   |   |   |       |
+   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +
|                                                               |
+   +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
|       |   |   |   |   |   |   |   |   |   |   |   |   |       |
+   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +
|                                                               |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+   +
| E     |   |   |   |   |   |   |   |   |   |   |   |   |       |
+   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +   +
| E                                                             |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

```
> 2 votes

---
Tags: code-challenge, path-finding, maze
---


title: Attack, Decay, Sustain, Release

text:
# Question
Title: Attack, Decay, Sustain, Release
Sound synthesizers use envelope generators to control how certain parameters of the sound (such as overall loudness) change with time. In many synthesizers an envelope is defined by four parameters, as represented in the following figure from Wikipedia:

* **Attack time (A)**: time taken for the envelope to reach its maximum level, starting from zero, when the key is first pressed.
* **Decay time (D)**: time taken for the envelope to reach the specified sustain level.
* **Sustain level (S)**: level which is maintained, after the initial attack and decay, for as long as the key is being pressed.
* **Release time (R)**: time taken for the envelope to reach zero when the key is released.

# The challenge

Input the four parameters A, D, S, R and **plot the envelope**.

Parameters will be **integer values from 0 to 127**.

The **maximum level** (reached at the end of the attack phase) will be assumed to be **127**.

The **horizontal segment at the sustain level** will be assumed to have **duration 64** (in the actual sound this duration is not fixed, but is determined by the amount of time that the key is held).

# Format and further details

The output should be an image in raster or vector format. If it's raster, the polygonal line should occupy at least 50 pixels vertically an horizontally.

The image can be either displayed or produced as a file in a standard image format. The file can be written to disk, or its exact contents can be output, either to STDERR or as function return argument.

The graph need only contain the polygonal line that defines the envelope. The scale of each axis can be freely chosen. Other elements such as axis lines, numeric labels or line colors are optional.

Input means and format are flexible as usual. For example, you can take the four numbers in any order, or an array containing them. A program or a function can be provided. Standard loopholes are forbidden.

Shortest code in bytes wins.

# Test cases

Input is in the format `[A D S R]`. Note that the scale is different in each figure (in accordance with the rule that scale can be freely chosen)

```
[15 30 70 40]

```

```
[64 64 64 64]

```

```
[0 10 50 80]

```

```
[0 0 90 80]

```

```
[5 50 0 0]

```

```
[5 50 0 80]

```

```
[24 32 127 48]

```

# Answer
> 7 votes
# MATL, ~~31~~ 22 bytes

```
Oii64ivYsO127itO5$h&XG

```

Accepts four separate inputs ordered as `A`, `D`, `R`, `S`

Try it out at **MATL Online**

**Explanation**

```
0   % Push a literal 0 to the stack
ii  % Grab the first two inputs
64  % Push the number literal 64 to the stack
i   % Grab the third input
v   % Vertically concatenate all values
Ys  % Compute the cumulative sum
0   % Push the number literal 0 to the stack
127 % Push the number literal 127 to the stack
i   % Grab the fourth input
t   % Duplicate the fourth input
O   % Push the number literal 0 to the stack
5$h % Concatenate the last 5 elements on the stack
&XG % Plot the result using the first array as x and second array as y

```

# Answer
> 44 votes
# TikZ, ~~195~~ ~~193~~ ~~181~~ ~~177~~ ~~172~~ ~~167~~ ~~163~~ ~~160~~ 159 bytes

*Thanks to David Carlisle for his helpful answer here*

```
\documentclass[tikz]{standalone}\begin{document}\tikz\def~#1{\typein[#1];}~\a~\s~\d~\r\def\u{)--(\a+\d}\draw(,)--(\a,127\u,\s\u+64,\s\u+\r+64,);\end{document}

```

Yes, you heard right ***TikZ***.

## Explanation

This uses a couple of techniques to achieve its goal. The first thing is input. Most people might not know that LATEX can take input. Well it can. This is achieved with the command `\typein`. This will halt the compiler and request input from the user as assign it to a variable.

The other main technique is the use of `\def`. `\def` in Tikz is absurdly powerful. It essentially defines a piece of code and pastes it everywhere you call the variable. In this code we define two things `\typein[#1]{}` so that we can assign our variables golfily and `)--(\a+\d` because this code shows up a bunch of times in the ungolfed version.

Here are two versions of the code (without the wrapper):

### Golfed:

```
\documentclass[tikz]{standalone}\begin{document}\tikz\def~#1{\typein[#1];}~\a~\s~\d~\r\def\u{)--(\a+\d}\draw(,)--(\a,127\u,\s\u+64,\s\u+\r+64,);\end{document}

```

### Ungolfed:

```
\typein[\a]{}\typein[\s]{}\typein[\d]{}\typein[\r]{}\draw(0,0)--(\a,127)--(\a+\d,)--(\a+\d+64,)--(\a+\d+\r+64,0);

```

## Image:

Since I cannot upload a pdf image directly, and converting it to any other format seems to cause the line to disappear altogether, here is what an image might look like when opened in Preview (input for this image is `[64 64 64 64]`):

As you can see it is very thin. However because it is a PDF image and not a raster image does not have to comply with thickness requirements.

# Answer
> 20 votes
# Python 2, ~~83~~ ~~80~~ 79 bytes

```
from turtle import*
def f(A,D,S,R):X=A+D+64;map(goto,[A,A+D,X,X+R],[127,S,S,0])

```

**Try it online** (83-byte version, because it runs online)

Note that certain outputs may not be completely visible using Trinket, because of the way the canvas works. You'll need to download and install Python if you want it to work better.

### Ungolfed:

```
from turtle import*
A,D,S,R=input()
goto(A,127)
goto(A+D,S)
goto(A+D+64,S)
goto(A+D+64+R,0)

```

This version doesn't work in Trinket, because Trinket doesn't support value unpacking of input.

# Answer
> 17 votes
## Mathematica, ~~61~~ 58 bytes

```
ListLinePlot[{Accumulate@{0,##3,64,#2},{0,127,#,#,0}}]&

```

is the operator for `Transpose` and is rendered as a superscript `T` by Mathematica.

Takes the arguments in the order `S, R, A, D` and returns a vector graphics object.

Results for all seven test cases:

Click for larger version.

# Answer
> 12 votes
## R, ~~66~~ 63 bytes

```
function(A,D,S,R)plot(cumsum(c(0,A,D,64,R)),c(0,127,S,S,0),"l")

```

Displays the image, with axis labs being `cumsum(c(0,A,D,64,R))` and `c(0,127,S,S,0)`, as well axis lines and numeric labels.

Thanks to @Zahiro Mor for shaving off *3 bytes* !

**Previous answer :**

```
function(A,D,S,R)plot(c(0,A,A+D,b<-A+D+64,b+R),c(0,127,S,S,0),"l")

```

# Answer
> 11 votes
# Matlab, 50 bytes

```
@(A,D,S,R)plot(cumsum([0,A,D,64,R]),[0,127,S,S,0])

```

This yields an anonymous function "ans" that has to be called as ans(A,D,S,R).

# Answer
> 9 votes
## JavaScript (ES6) + HTML, 126 + 23 = 149

```
c=O.getContext`2d`;c.moveTo(a=0,z=O.height=128);g=(y,x=prompt())=>c.lineTo(a+=+x,y)||g;g(0)(s=z+~prompt())(s,64)(z);c.stroke()
```

```
<canvas id=O width=512>
```

Takes input one at a time in the order `A, S, D, R`.

# Answer
> 9 votes
## JavaScript (ES6), ~~114~~ 111 bytes

```
f=(a,d,s,r)=>`<svg width=446 height=128><path stroke=red fill=none d=M0,127L${a},0l${d},${127-s}h64l${r},${s}>`
```

```
<div oninput=o.innerHTML=f(a.value,d.value,s.value,r.value)><input type=number value=0 min=0 max=127 id=a><input type=number value=63 min=0 max=127 id=d><input type=number value=127 min=0 max=127 id=s><input type=number value=0 min=0 max=127 id=r><div id=o><svg width=446 height=128><path stroke=red fill=none d=M0,127L0,0l63,0h64l0,127 /></svg>
```

Returns an SVG image suitable for `innerHTML`. Add 18 bytes for valid XML.

# Answer
> 8 votes
## Haskell, ~~112~~ 110 bytes

```
import Graphics.Gloss
(a#d)s r=display(InWindow""(600,300)(0,0))red$line$zip(scanl(+)0[a,d,64,r])[0,127,s,s,0]

```

Usage example: `(0#10) 50 80`.

This uses the `Gloss` library. The `display` function expects a window to plot in (here: a window without title (`""`), size 600x300, position `(0,0)` on desktop), a background color (`red`) and picture witch is a line along the path made by zipping the cumulative sum of `[0,a,d,64,r]` = `[0,a,a+d,a+d+64,a+d+64+r]` as the x coordinates and `[0,127,s,s,0]` as the y coordinates.

Edit: Thanks @xnor for 2 bytes!

# Answer
> 5 votes
# Processing, ~~134~~ 108 + 14(call to `size`) = ~~148~~ 122 bytes

First we need a call to `size` somewhere in the program so that the output will fit in the window (default at 100x100).

```
size(400,400);

```

And here's the actual function:

```
void g(int a,int b,int c,int d){line(0,127,a,0);line(a,0,b+=a,c=127-c);line(b,c,b+=64,c);line(b,c,b+d,127);}

```

Call it like `f(15,20,70,40);`

### Screenshot

```
15, 20, 70, 40

```

---

My newer answer is more straightforward than the older answer, but I like the older one more (even if it is bigger).

### Old answer (148 bytes)

```
size(400,400);

```

and the two functions

```
void f(int[]v){translate(0,127);l(v[0],-127);l(v[1],127-v[2]);l(64,0);l(v[3],v[2]);}void l(int x,int y){line(0,0,x,y);translate(x,y);}

```

Call it like `f(int_array_containing_values);` and the result will look something like: `f(new int[]{15,20,70,40});`

# Answer
> 4 votes
# PHP, ~~149~~ 130 bytes

```
[,$a,$d,$s,$r]=$argv;imagepolygon($i=imagecreatetruecolor(446,127),[0,127,$a,0,$d+=$a,$s,$d+=64,$s,$d+$r,127],5,999);imagepng($i);

```

takes input from command line arguments, writes image (PNG with graph blue on black) to stdout. Requires PHP 7.1 or later.

usage e.g.

```
# any OS with ImageMagick:
php -r '<code>' <parameters> | display

# linux with feh:
php -r '<code>' <parameters> | feh

```

+4 bytes for older PHP: Replace `[,$a,$d,$s,$r]` with `list(,$a,$d,$s,$r)`.

---

There is a small hack in there: instead of using `imageopenpolygon` to hide the base line, the finishing polygon line is drawn outside the canvas. (y=127 would only display on an image with height \>= 128.)

I could have saved more with color 99 or 9 instead of 999; but those are pretty hard to see on black. :)

# Answer
> 4 votes
# SmileBASIC, 90 bytes

```
INPUT A,D,S,R
B=A+D+64W=#Y-S
GLINE.,#Y,A,0GLINE A,0,A+D,W
GLINE A+D,W,B,W
GLINE B,W,B+R,#Y

```

# Answer
> 3 votes
## Bash + grace, 70 bytes

```
t=$[$1+$2]
echo "0 0
$1 127
$t $3
$[t+64] $3
$[t+64+$4] 0">f
xmgrace f

```

The script writes to file `f` the coordinates of each point, and xmgrace (the GUI version) reads the file and displays the plot using lines by default.

**Run**:

```
./plot_ADSR.sh 15 30 70 40

```

**Output:** (print screen)

I think this can be done directly by a grace script, if it can accept input, but I'm not familiar with its syntax. I'll look into it.

**Explanation:**

```
t=$[$1+$2]          # store the value of (A+D) for later usage
echo "0 0           # start writing the coordinates to file "f", first the origin
$1 127              # then (A, 127)
$t $3               # then (A + D, S)
$[t+64] $3          # then (A + D + 64, S)
$[t+64+$4] 0">f     # then (A + D + 64 + R, 0)
xmgrace f           # call xmgrace to plot the generated XY file

```

# Answer
> 2 votes
## Go, ~~947~~ ~~915~~ 506 bytes

*This is far from optimized, trying to learn the language while participating in these questions. Feel free to point out what I can do.*

**Condensed:**

```
package main;import (."os";."image";k"image/png";c"image/color";."strconv";."math");func main(){g:=NewRGBA(Rect(0,0,127*4,127));a,_:=ParseFloat(Args[1],4);d,_:=ParseFloat(Args[2],4);s,_:=ParseFloat(Args[3],4);r,_:=ParseFloat(Args[4],4);z:=[5][]float64{{0,0},{a,127},{a+d,s},{a+d+64,s},{a+d+64+r,0}};for i:=1;i<len(z);i++{v,w,x,y:=z[i-1][0],z[i-1][1],z[i][0],z[i][1];m:=(y-w)/(x-v);t:=y-m*x;for v<=x{g.Set(int(Ceil(v)),127-int(Ceil(w)),c.RGBA{0,0,0,255});v+=.01;w=m*v+t}};f,_:=Create("o.png");k.Encode(f,g)}

```

**Uncondenced:**

```
package main

import (
    ."os"
    ."image"
    k"image/png"
    c"image/color"
    ."strconv"
    ."math"
    "fmt"
)

func main(){
    g := NewRGBA(Rect(0, 0, 127*4, 127))

    a, _ := ParseFloat(Args[1], 4)
    d, _ := ParseFloat(Args[2], 4)
    s, _ := ParseFloat(Args[3], 4)
    r, _ := ParseFloat(Args[4], 4)

    z := [5][]float64{{0,0},{a,127},{a+d,s},{a+d+64,s},{a+d+64+r,0}}
    for i:=1;i<len(z);i++{
        v,w,x,y:=z[i-1][0],z[i-1][1],z[i][0],z[i][1]
        m:=(y-w)/(x-v)
        t:=y-m*x
        for v<=x{
            g.Set(int(Ceil(v)),127-int(Ceil(w)), c.RGBA{0,0,0,255})
            v+=.01
            w=m*v+t
        }
    }
    f,_:=Create("o.png")
    k.Encode(f,g)
}

```

# Answer
> 1 votes
## dc, 120 bytes

Initially I thought I can't answer in dc, but I see that printing the syntax of a vector image is allowed.

```
?sR127r-sS[<svg><path d="M0 127 L]nrdn[ 0 L]n+dn32PlSn[ L]n64+dn32PlSn[ L]nlR+n[ 127" fill="none" stroke="red"/></svg>]p

```

The code calculates the translated coordinates of each point and generates the SVG syntax for the plot. Since an image editor has the origin at the top-left corner, I had to subtract the `y` values from `height`, 127 in this case, so that the image is shown as if the origin is at the bottom-left corner.

**Run example:** or **Try it Online!**

```
dc -f plot_ADSR.dc <<< "15 30 70 40"

```

**Output:**

```
<svg><path d="M0 127 L15 0 L45 57 L109 57 L149 127" fill="none" stroke="red"/></svg>
```

To display the image plot, save that exact output to a file and open it with Gimp, for example, or enter the text in an html page as I did above.

**Explanation:** `dc` is a reverse-polish **d**esk **c**alculator stack language

The script is a long concatenation of the SVG syntax string. The keyword `M` stands for *move to coordinate* and `L` stands for *draw line from current position to given coordinate*.

```
?                           # read input (in reverse order by default). Stack: RSDA
sR                          # pop top value, store it in register 'R'. Stack: SDA
127r-sS                     # push 127, swap top 2 values, pop them and push
                            #subtracting result, save it to 'S', pop it. Stack: DA
[<svg><path d="M0 127 L]n   # [..]n print string (push then pop). Stack: unchanged
rdn                         # swap, duplicate top, print (A) and pop it. Stack: AD
[ 0 L]n                     # printing
+dn                         # pop top 2 values, push addition result, duplicate it,
                            #print and pop it. Stack: (A+D)
32P                         # print a space
lSn                         # push value from register 'S', print and pop it.
                            #Stack: unchanged
[ L]n                       # printing
64+dn                       # push 64, pop top 2 values, push addition result,
                            #duplicate it, print and pop it. Stack: (A+D+64)
32PlSn[ L]n                 # print space, print register 'S', more printing
lR+n                        #push value from register 'R', pop top 2 values, push
                            #addition result, print it and pop it. Stack: empty
[ 127" fill="none" stroke="red"/></svg>]p   # printing

```

# Answer
> 1 votes
# Processing, 111 bytes

```
size(400,128);line(0,127,a,0),line(a,0,a+d,127-s),line(a+d,127-s,a+d+64,127-s),line(a+d+64,127-s,a+d+64+r,127);

```

Used a simpler method of input compared to user41805.

## Output (formatted)

`0,0,90,80`

`0,10,50,80`

`5,50,0,0`

`5,50,0,80`

`15,30,70,40`

`24,32,127,48`

`64,64,64,64`

## Ungolfed code with formatting

```
void settings() {
  //size adjusts according to params
  size(a+d+64+r, 129);
}
void setup() {
  translate(1,0);
  background(255);
  strokeWeight(3);

  //axes
  line(0,127,600,127);
  line(0,0,0,127);

  //graph
  stroke(53,113,9);
  line(0,127,a,0);
  stroke(228,77,40);
  line(a,0,a+d,127-s);
  stroke(26,39,232);
  line(a+d,127-s,a+d+64,127-s);
  stroke(110,27,109);
  line(a+d+64,127-s,a+d+64+r,127);

  //save to file
  save("a"+a+"d"+d+"s"+s+"r"+r+".png");
}
int a=24,d=32,s=127,r=48;

```

This program will save your images to disk in the same folder.

---
Tags: code-golf, number, graphical-output, music
---


title: Compress your code in an image

text:
# Question
Title: Compress your code in an image
This is a variation.

## Introduction

We all write short code, because some obscure reasons, but whatever we do, the'll take up at least 144 pixels/byte (with a 12px font). But what would happen, if we would encode our code in images? This is your task today.

## Challenge

You task is to read in your own source code (non-proper quines are allowed, e.g. literally reading the source file), and create an image out of it, by setting the red, green and blue components of a pixel based on the ASCII value of the character.

Example:

We have the string "Hello world!"

```
Hello world!

```

Let's convert this to ASCII values:

```
72 101 108 108 111 32 119 111 114 108 100 33

```

Map the RGB values to it (If the source code's length is not divisible by 3, use 0s as the remaining characters):

```
 __________________________________________________
| R | G | B || R | G | B || R | G | B || R | G | B |
----------------------------------------------------
|72 |101|108||108|111|32 ||119|111|114||108|100|33 |
----------------------------------------------------

```

We then create the image with the smallest area out of it. We have 4 sets of RGB values, so the smallest image will be a 2\*2 image, going from the top left pixel to the right:

And we get this awfully colored image (resized, so it's at least visible, also proves the fact how small it can get)

## Rules/Additional information

* There's no input
* The output should be as a separate file, or in a separate window.
* For multibyte characters, split the character in 2 bytes.
* The source code must be at least 1 byte long
* The image should be the one from the possible sizes, wich has the closest width/height ratio to 1
* The pixel count on the image should exactly be ceil(byte count / 3), no extra pixels should be added

## Scoring

This is a , so the smallest answer in bytes wins.

# Answer
> 1 votes
## Actually, 12 bytes

```
Q"P6 4 1 255

```

Try it online!

This program also works in Seriously.

This program outputs a PPM image, which is acceptable by default.

Output image (scaled up 50x):

Explanation:

```
Q"P6 4 1 255
Q             push source code
 "P6 4 1 255  push header for a 4x1 raw (type P6) 8-bit PPM image (the closing " is implicitly added at EOF)

```

# Answer
> 8 votes
# MATLAB, ~~81~~ ~~72~~ 69 bytes

```
@()image(shiftdim(reshape(evalin('base','char(ans)'),3,1,23)/255,1.))

```

This creates an anonymous function which can be pasted into the command window and run using `ans()`. When run this creates a 23-pixel image (a prime) therefore the most square representation is a simple array of pixels.

**Explanation**

When pasted into the command window, the anonymous function will automatically assign itself to the variable `ans`. Then from within the anonymous function, we use:

```
evalin('base', 'char(ans)')

```

which evaluates `char(ans)` within the namespace of the command window rather than within the local namespace of the anonymous function. It is therefore able to convert the anonymous function itself into a string representation.

Then we have the following operations which are more straightforward:

```
%// Reshape the result into a 3 x 1 x 23 matrix where the first dimension is RGB
%// due to column-major ordering of MATLAB
R = reshape(string, 3, 1, 23);

%// Divide the result by 255. This implicitly converts the char to a double
%// and in order for RGB interpreted properly by MATLAB, doubles must be
%// normalized between 0 and 1.
R = R / 255;

%// Shift the dimensions to the left 1 to move the RGB channel values into
%// the third dimension. Note the extra decimal point. This is because it
%// is far shorter to lengthen the code by one byte than to pad the string
%// to give us a length divisible by 3
R = shiftdim(R, 1.);

%// Display the RGB image
image(R);

```

# Answer
> 4 votes
## Javascript(ES6) ~~324~~ ~~312~~ 309 Bytes

I'm sure this could be golfed a bit:

```
f=()=>{s="f="+f;l=s.length/3;c=document.createElement('canvas');for(i=0;++i<l/i;l%i?0:w=i,h=l/w);c.s=c.setAttribute;c.s("width",w);c.s("height",h);(i=(t=c.getContext('2d')).createImageData(w,h)).data.map((a,b)=>i.data[b]=b%4<3?s.charCodeAt(b-~~(b/4)):255);t.putImageData(i,0,0);open(c.toDataURL('image/png'))}

```
* creates a canvas
* builds image in it
* Opens data url for image in new tab

New lines for readability:

```
f=()=>{
    s="f="+f;l=s.length/3;
    c=document.createElement('canvas');
    for(i=0;++i<l/i;l%i?0:w=i,h=l/w);
    c.s=c.setAttribute;
    c.s("width",w);
    c.s("height",h);
    (i=(t=c.getContext('2d')).createImageData(w,h)).data.map((a,b)=>i.data[b]=b%4<3?s.charCodeAt(b-~~(b/4)):255);
    t.putImageData(i,0,0);
    open(c.toDataURL('image/png'))
}

```

### Output

# Answer
> 3 votes
# Javascript ES6 - 216 bytes

```
f=(  )=>((d=(x=(v=document.createElement`canvas`).getContext`2d`).createImageData(v.width=9,v.height=8)).data.set([..."f="+f].reduce((p,c,i)=>(c=c.charCodeAt(0),[...p,...i%3<2?[c]:[c,255]]))),x.putImageData(d,0,0),v)

```

Ungolfed:

```
f=(  )=>(                                           // define function f (extra spaces to account for missing pixel + alpha channel calculation)
 (d=(x=(v=document.createElement`canvas`).          // assign html5 canvas to v
          getContext`2d`).                          // assign graphics context to x
          createImageData(v.width=9,v.height=8)).   // create & assign ImageData to d
                                                    //   set width and height of both d and v
 data.set([..."f="+f].                              // get f's source, convert to array of chars
   reduce((p,c,i)=>(c=c.charCodeAt(0),              // convert char array to int array
                    [...p,...i%3<2?[c]:[c,255]]))), // insert alpha values 255
 x.putImageData(d,0,0),                             // draw source RGBA array to canvas
 v)                                                 // return canvas

```

Note: `f` returns a canvas.

Example run (assumes there's a `<body>` to append to):

```
document.body.appendChild(f())

```

Should dump the following image to the page (enlarged):

# Answer
> 2 votes
## PowerShell v4, 64 bytes

```
"P6 11 2 255"+[char[]](gc $MyInvocation.MyCommand.Name)|sc a.ppm

```

It gets the content of its own filename, casts the string as a char array, adds some PPM header and sets the content to a.ppm as output. 64 bytes makes it 11x2 pixels:

# Answer
> 1 votes
# Node.js, 63 bytes

```
(F=x=>require('fs').writeFile('P6','P6 7 3 255 (F='+F+')()'))()

```

Outputs image into a file named `P6` which is in the PPM (P6) format.

Here's a PNG rendition (7x3 pixels):

# Answer
> 1 votes
## PHP, 226 bytes

**Golfed**

```
<?$b=strlen($w=join(file('p.php')));$z=imagecreatetruecolor(5,15);for($c--;++$c<$b+1|$i%3;$i%3?:$a=!imagesetpixel($z,$x%5,(int)$x++/5,$a))$a+=($c<$b?ord($w[$c]):0)*256**(2-$i++%3);header("Content-Type:image/png");imagepng($z);

```

**Ungolfed version**

```
<?
// Read the file into an array and join it together. Store the length of the resulting string.
$b=strlen($w=join(file('p.php')));

// Create the image. Our file is 226 bytes, 226/3 = 75 = 5 * 15
$z=imagecreatetruecolor(5,15);

// Loop through the script string, converting each character into a pixel.
// Once three characters have been converted, draw the pixel with the converted RGB value and reset the color to 0.
for($c--;++$c<$b+1|$i%3;$i%3?:$a=!imagesetpixel($z,$x%5,(int)$x++/5,$a))$a+=($c<$b?ord($w[$c]):0)*256**(2-$i++%3);

// Tell the program we're sending an image
header("Content-Type:image/png");

// And send it!
imagepng($z);

```

Enter this script into a file named 'p.php' and run it. You need your own method of running PHP script, because this reads from a local file.

Output image:

# Answer
> 1 votes
## Java 511 chars

The length of the solution leads to a greater picture which is cool, because these pictures are really nice.

```
import java.awt.image.*;import java.io.*;import java.nio.file.*;import javax.imageio.*; public class Q{public static void main(String[]a)throws Throwable{int w=19,h=9;byte[]e=Files.readAllBytes(Paths.get("Q.java"));String t=new String(e);while(t.length()%3!=0)t+='\0';BufferedImage I=new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);int r,c=r=0;for(int i=0;i<t.length();i++){I.setRGB(c,r,255<<24|t.charAt(i)<< 16|t.charAt(++i)<< 8|t.charAt(++i));if(++c==w){c=0;r++;}}ImageIO.write(I,"png",new File("Q.png"));}}

```

Note that there is an invisible trailing newline! It reads the source file, which has to be "Q.java" and creates a picture "Q.png" which looks like this:

or scaled 100x

# Answer
> 0 votes
# APL (Dyalog), 33 bytes

Requires `⎕IO←0` which is default on many systems. Also, AutoFormat should be off to preserve the program exactly as given.

```
(⊂⎕NPUT⊃)'P',⍕⎕AV⍳'␍ɫ␉⍣',⊃⌽⎕NR'f'

```

Hex B9 BA FD 4E 50 55 54 BB F8 0D 50 0D C2 CD FD 41 56 B2 0D 03 0B 01 FF 0D C2 BB C8 FD 4E 52 0D 16 0D
Unicode 28 2282 2395 4E 50 55 54 2283 29 27 50 27 2C 2355 2395 41 56 2373 27 0D 026B 08 2363 27 2C 2283 233D 2395 4E 52 27 66 27

Creates `P`: P3 11 1 255 185 186 253 78 80 85 84 187 248 13 80 13 194 205 253 65 86 178 13 3 11 1 255 13 194 187 200 253 78 82 13 22 13
Which you save and drop here to see:

`⎕NR'f'`**N**ested **R**epresentation of the program *f*

`⊃⌽` pick the last (lit. first of the reversed) element (line)

`'␍ɫ␉⍣',` prepend the four characters (filetype, width, height, max)

`⎕AV⍳` find corresponding indices in the **A**tomic **V**ector (the character set

format as text

`'P',` prepend a letter

`(``)` apply the following tacit function:

take the entire argument \[and into a\]

`⎕NPUT`**N**ative \[file,\] **Put** \[it, with a filename consisting of\]

the first character ("P")

# Answer
> 0 votes
# Processing, 193 bytes

```
byte a[]=loadBytes("s.pde");noStroke();int x=0,y=0;for(int k=0;k<a.length%3;k++){append(a,byte(0));}for(int i=0;i<a.length-2;i+=3,x++){if(x>0){x=0;y+=1;}fill(a[i],a[i+1],a[i+2]);rect(x,y,1,1);}

```

## Original

## Resized

Even with Processing's builtins, this was very difficult.

# Answer
> -1 votes
# Python, 81 bytes

```
q=open(__file__).read()
print'P3\n9 3 256 '+' '.join(map(lambda x:str(ord(x)),q))

```

Output is in PPM format.

This is what the image looks like:

Scaled up:

---
Tags: code-golf, graphical-output, quine
---


title: Pi to the power y, for small y's

text:
# Question
Title: Pi to the power y, for small y's
# Input

This task takes no input.

# Output

Your code should compute and print (or return)
\\$\pi^y\\$ for all \\$y = \frac11, \frac12, \frac13, \frac14, \frac15, \frac16, \frac17, \frac18, \frac19, \frac1{10}, \frac1{11}, \frac1{12}\\$. The first 20 digits of the output (truncated and without any rounding) should be correct in each case.

Here are the answers:

```
3.1415926535897932384
1.7724538509055160272
1.4645918875615232630
1.3313353638003897127
1.2572741156691850593
1.2102032422537642759
1.1776640300231973966
1.1538350678499894305
1.1356352767378998683
1.1212823532318632987
1.1096740829646979321
1.1000923789635869829

```

# Answer
# APL (Dyalog Extended), ~~9~~ 8 bytesSBCS

```
(⍳12)√○1

```

Try it online! (`⎕PP←34` is Print Precision: 34 digits; `⎕FR←1287` is Float Representation: 128-bit decimal)

`○1`\\$π×1\\$

`(``)√` take the following roots of that:

`⍳12`**ɩ**ndices 1 through 12
> 19 votes

# Answer
# JavaScript (ES7), 121 bytes

Computes as many digits as the precision of IEEE 754 allows and hardcodes the other ones.

```
_=>[32384,60272,2630,7127,[n=0]+593,2759,3966,4305,8683,2987,9321,69829].map(v=>(Math.PI**(1/++n)+'').slice(0,~(n==2))+v)

```

Try it online!

### Commented

```
_ =>                          // input is ignored
[ 32384, 60272, 2630, 7127,   // hard-coded digits for n=1 to n=4
  [n = 0] + 593,              // initialize n to 0, and set this entry to '0593' (n=5)
  2759, 3966, 4305, 8683,     // hard-coded digits for n=6 to n=9
  2987, 9321, 69829           // hard-coded digits for n=10 to n=12
].map(v =>                    // for each entry in the above array:
  (Math.PI ** (1 / ++n) + '') //   increment n; compute π**(1/n) and coerce it to a string
  .slice(0, ~(n == 2))        //   remove the last 2 digits if n=2,
                              //   or only the last digit otherwise
  + v                         //   append the hard-coded digits
)                             // end of map()

```
> 19 votes

# Answer
# Bash \+ bc ~~\+ coreutils~~, ~~51~~, ~~40~~, ~~39~~, 36 bytes

following @ChristianSievers comment `|cut -c -21` could be removed.

-3 bytes thanks to @DigitalTrauma.

```
echo "e(l(4*a(1))/"{1..12}");"|bc -l

```

Try it online!

Some explanations

* `bc -l` define math functions and set scale to 20, see `man bc` for more details
* `a()` atan function, so `4*a(1)` is `pi`
* `e()` exp function
* `l()` log function, so `e(l(x)/y)` is `x^(1/y)`
> 15 votes

# Answer
# Julia 1.0, 18 bytes

```
@.π^(1/big(1:12))

```

Try it online!

`(1./big(1:12))` divides a `BigInt` 1 by each of 1 thru 12, then `π.^` raises pi to each of those values. So long as there is one `BigInt` or `BigFloat` involved in each computation, it will calculate the result at that precision. The `@.` macro transforms the code to add dots to every function call (thus the dots that appear in my explanation that don't appear in the code snippet), this causes it to "broadcast" which for this purpose means do it all elementwise.

20-\>19 thanks to Robin Ryder

19-\>18 thanks to TimD
> 15 votes

# Answer
# Wolfram Language (Mathematica), ~~22~~ ~~20~~ 19 bytes

-2 bytes thanks to game0ver -1 byte thanks to LegionMammal978

```
Pi^(1`11/Range@12)&

```

Try it online!
> 9 votes

# Answer
# 05AB1E (legacy), ~~47~~ ~~43~~ 40 bytes

```
•u¬Œo¡õ≠ÎĆζw1Á4¼©éßw–xùó1O•5ôεžqN>zm16£ì

```

-7 bytes thanks to *@Grimy*.

Try it online.

Uses the legacy version, because for some reason the new version outputs \\$1.0\\$ for \\$\pi^{\frac{1}{1}}\\$.. :S

**Explanation:**

```
•u¬Œo¡õ≠ÎĆζw1Á4¼©éßw–xùó1O•
             # Push compressed integer 323846027232630971275059342759739669430598683329877932169829
 5ô          # Split it into parts of size 5:
             #  [32384,60272,32630,97127,50593,42759,73966,94305,98683,32987,79321,69829]
ε            # Then map each integer to:
   N>        #  Take the 0-based map-index, and increase it by 1
     z       #  Calculate 1/(index+1)
 žq   m      #  Then calculate PI the power of this
       16£   #  Only leave the first 16 characters (including decimal dot)
          ì  #  And prepend it before the current integer we're mapping
             # (after which the mapped result is output implicitly)

```

See this 05AB1E tip of mine (sections *How to compress large integers?*) to understand why `•u¬Œo¡õ≠ÎĆζw1Á4¼©éßw–xùó1O•` is `323846027232630971275059342759739669430598683329877932169829`.
> 8 votes

# Answer
# Python 3, ~~61~~ ~~69~~ 63 bytes

Variant of Jitse's answer, who wants to stick to standard libraries. As mentioned by @Seb & @Jitse, `Rational` or `E/E` are needed because `1/i` isn't precise enough as float.

```
from sympy import*;i=E/E
while i<13:print(N(pi**(1/i),99));i+=1

```

Try it online!

As a bonus, `sympy` allows to output 99 decimals with the same byte count as for 20 decimals:

```
3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211707
1.77245385090551602729816748334114518279754945612238712821380778985291128459103218137495065673854467
1.46459188756152326302014252726379039173859685562793717435725593713839364979828626614568206782035382
1.33133536380038971279753491795028085330936622381810425845370748286670076101723561496824589105670695
1.25727411566918505938452211411044829390616631003965817353418162262716270074393519788994784267497245
1.21020324225376427596603076175994353105276255513631810467305643780646240044814351479113420061960303
1.17766403002319739668470085583704641096763145003350008756991802723553566109741289228117335907046316
1.15383506784998943054096521314988190017738887987082462087415032873413337243208073328092932090341440
1.13563527673789986837981146453309184806238366027985302804182074656192075351096762716281170420998022
1.12128235323186329872203095522015520934269381296656043824699758762377264153679046528721553289724806
1.10967408296469793211291254568401340513968966612239757917494488030006513039871082996506101420959919
1.10009237896358698298222864697784031503277459309498017808547779493972810083028975298933600450861044

```
> 7 votes

# Answer
# Python 3, 91 bytes

```
import fractions as f;p=f.Decimal('%s2384'%f.math.pi);i=p/p
while i<13:print(p**i**-1);i+=1

```

Try it online!

*-23 bytes thanks to flornquake*
> 6 votes

# Answer
# bc -l, 28

```
for(;i<12;)e(l(4*a(1))/++i)

```

Try it online!
> 5 votes

# Answer
# Ruby `-rbigdecimal/math`, ~~65~~ 50 bytes

Conveniently, even though `BigMath.PI(9)` only *guarantees* precision up to 9 digits, it actually is precise up to 26, which is enough to calculate the exponents, which use the builtin `Rational` fractions instead of floats to ensure the precision is still good enough. (Also, making a `Rational` saves a byte over dividing it normally, since Ruby uses integer division if both arguments are integers, necessitating the use of `1.0` somewhere in the code.)

-15 bytes from histocrat!

```
1.upto(12){|i|puts BigMath.PI(9).**(1r/i).to_s ?F}

```

Try it online!
> 5 votes

# Answer
# Pari/GP, 20 bytes

```
vector(12,n,Pi^n^-1)

```

Try it online!

(TIO needs some supporting code, but this works as is in the REPL.
> 3 votes

# Answer
# cQuents, 268 bytes

```
#1&"3.1415926535897932384
1.7724538509055160272
1.4645918875615232630
1.3313353638003897127
1.2572741156691850593
1.2102032422537642759
1.1776640300231973966
1.1538350678499894305
1.1356352767378998683
1.1212823532318632987
1.1096740829646979321
1.1000923789635869829"

```

Try it online!

There is no way to get more precision out of floats in cQuents, so the values must be hardcoded as strings.

# cQuents, 11 bytes

```
#12&`p^(1/$

```

Try it online!

Does not reach the required precision levels.
> 3 votes

# Answer
# Octave, 23 bytes

```
vpa(pi,22).^(1./(1:12))

```

Try it online!

Declares a variable precision arithmetic (VPA) pi. Octave then cleverly infers that the double constant `pi` actually means pi, not whatever the double constant contains.
> 3 votes

# Answer
# C (gcc `-lm`), ~~171~~ ~~131~~ 122 bytes

Shaved off ~~40~~ 49 bytes thanks to ceilingcat.

```
i;p(){for(;i<12;)printf("%.14f%d ",pow(acos(~fesetround(1024)),1./++i),L"纀罶얡꜇胛"[i]);}

```

Try it online!

Output:

```
3.1415926535897932384 1.7724538509055160272 1.4645918875615232630 1.3313353638003897127 1.2572741156691850593 1.2102032422537642759 1.1776640300231973966 1.1538350678499894305 1.1356352767378998683 1.1212823532318632987 1.1096740829646979321 1.1000923789635869829

```
> 3 votes

# Answer
# \+ Rmpfr, 80 bytes

Requires package Rmpfr.

```
mpfr("1.00000000238982476721842284052415179434",30 *log2(10))^(479001600/(1:12))

```

Gives the following, with truncations mine and some minor formatting

```
12 'mpfr' numbers of precision  99   bits
3.1415926535897932384...
1.7724538509055160272...
1.4645918875615232630...
1.3313353638003897127...
1.2572741156691850593...
1.2102032422537642759...
1.1776640300231973966...
1.1538350678499894305...
1.1356352767378998683...
1.1212823532318632987...
1.1096740829646979321...
1.1000923789635869829...

```

See below for why simpler versions don't work. Direct calculation using exponents 1/N for N=1,12 returned inaccurate value fairly early. I figured that was probably due to R or Rmpfr rounding 1/3 early, so whole number exponents would be preferred. So I calculated pi^(12!) (12!=479001600) using Mathematica, then raised it to the power of 12!/N, which would always be a whole number. I had to further tune it by passing the number to Rmpfr as a character vector (so R wouldn't round it), and by using an arbitrarily high precision in both Mathematica and Rmpfr so it would truncate accurately. Because of those arbitrary additions, I can probably shave off a few bytes, but I'm good with it as is.

# ~~, 29 bytes~~

This only works if R value for pi is accurate, which it isn't. Even reassigning the variable pi to a more accurate representation does not improve accuracy, as it rounds or something around 17 decimals.

```
format(pi^(1/1:12),nsmall=20)

```

Try it online

Or, for 30 bytes

```
options(digits=20);pi^(1/1:12)

```

There's a package that gives a more accurate value for pi and other floating point numbers, Rmpfr, which you'll find referenced in questions about pi in R. One might expect the following to give the desired output.

```
library(Rmpfr)
Const("pi",20 *log2(10))^(1/1:12)

```

It doesn't. It gives

```
12 'mpfr' numbers of precision  66   bits
[1] 3.1415926535897932385  1.7724538509055160273  1.464591887561523232
[4] 1.3313353638003897128 1.2572741156691850754 1.2102032422537642632
[7]  1.177664030023197386 1.1538350678499894305 1.1356352767378998604
[10] 1.1212823532318633058 1.1096740829646979353 1.1000923789635869772

```

This is wrong on all counts by rounding or being a few off in the last digits (sidenote: the rnd.mode flag for mpfr does not fix this). Now one might think if we went up to many digits (say 100), then it would surely be correct to the first 20 digits. Nope

```
12 'mpfr' numbers of precision  332   bits
 [1] 3.1415926535897932384...
 [2] 1.7724538509055160272...
 [3] 1.4645918875615232319...
 [4] 1.3313353638003897127...
 [5] 1.2572741156691850753...
 [6] 1.2102032422537642631...
 [7] 1.1776640300231973859...
 [8] 1.1538350678499894305...
 [9] 1.1356352767378998603...
[10] 1.1212823532318633058...
[11] 1.1096740829646979353...
[12] 1.1000923789635869771...

```

(Truncations mine). These don't all match OP or the other responses.
> 3 votes

# Answer
# C (gcc) with libquadmath, 107

* 2 bytes saved thanks to @ceilingcat.

This uses `__float128` to get the required precision.

```
#import<quadmath.h>
s[9];main(i){for(;i<13;puts(s))quadmath_snprintf(s,36,"%.99Qf",expq(logq(M_PIq)/i++));}

```

Try it online!

---

I was curious to try this using the GNU MPFR library too:

# C (gcc) with libmpfr, 123

* 13 bytes saved thanks to @ceilingcat.

```
#include<mpfr.h>
i;main(){MPFR_DECL_INIT(p,99);for(;i<12;){mpfr_const_pi(p,99);mpfr_root(p,p,++i,MPFR_RNDN);mpfr_printf("%.19Rf\n",p);}}

```

Try it online!
> 3 votes

# Answer
# Canvas, 30 bytes

```
６«｛“≥αｙＨT.─Ｃ¹„1.0000ŗ┤“^m„┘÷＾］

```

Don't try it here! It'll take a while to calculate all those digits (it took ~15 minutes to run for me). Rather, here's a version of the same code, only outputting the last 3 items.

Computes `C ^ (27720/N)` where `C` is the hard-coded constant `pi^(1/27720)` = `1.000041297024626834690309` and N is looped over from 1 to 12. The big number library decided to expand the amount of significant digits for successively bigger N, making the code take unreasonable amounts of time to run.
> 2 votes

# Answer
# Python 3, 146 bytes

```
import math
for i in range(1,13):print(str(math.pi**(1/i))[:~(i==2)]+str([32384,60272,2630,7127,'0593',2759,3966,4305,8683,2987,9321,69829][i-1]))

```

Try it online!

This uses a similar method to Arnauld's JavaScript solution, by using the inbuilt pi value with the extra precision added to the end.
> 2 votes

# Answer
# Jelly, 46 bytes

```
12İ€ØP*×ȷ19Ḟ+“Ṿẏ⁽)¬ọƓỴ³ɲỊUị&ıİḣl’ḃ4ȷ¤_2ȷD;"€”.

```

Try it online!

Similar to some other answers, but encodes the difference between the Jelly answer and the correct answer (with big integer arithmetic). Full explanation to follow.
> 2 votes

# Answer
# Java 10, ~~316~~ ~~299~~ ~~268~~ 259 bytes

```
v->Math.PI+"2384 1.7724538509055160272 1.4645918875615232630 1.3313353638003897127 1.2572741156691850593 1.2102032422537642759 1.1776640300231973966 1.1538350678499894305 1.1356352767378998683 1.1212823532318632987 1.1096740829646979321 1.1000923789635869829"

```

-40 bytes by just hard-coding the output instead of calculating it.. \>.\>
-9 bytes thanks to *@ceilingcat*.

Try it online.

**Old ~~299~~ 291 bytes answer with actual calculations..**

```
v->{var P=new java.math.BigDecimal(Math.PI+"2384");var x=P;for(int i=0;++i<13;System.out.println(x)){var p=P;for(x=P.divide(P.valueOf(i),21,5);x.subtract(p).abs().compareTo(P.ONE.movePointLeft(22))>0;)x=P.valueOf(i-1).multiply(p=x).add(P.divide(x.pow(i-1),21,5)).divide(P.valueOf(i),21,5);}}

```

Not entirely precise, but good enough to have the first 20 digits correct.

Try it online.

**Explanation:**

Most bytes come from the fact that `BigDecimal` doesn't have a builtin for `BigDecimal.pow(BigDecimal)` nor the \\$n\\$th root, so we'll have to calculate this manually..

```
v->{                         // Method with empty unused parameter and no return-type
  var P=new java.math.BigDecimal(Math.PI+"2384");
                             //  Create a BigDecimal for PI
  var x=P;                   //  Create a BigDecimal to print after every iteration
  for(int i=0;++i<13;        //  Loop `i` in the range [1,12]:
      System.out.println(x)){//    After every iteration: print `x` to STDOUT
    var p=P;                 //   Create a BigDecimal to save the previous value
    for(x=P.divide(P.valueOf(i),
                             //   Set `x` to PI divided by `i`
                   21,5);    //   (with precision 21 and rounding mode HALF_DOWN)
                             //   Continue an inner loop as long as:
        x.subtract(p).abs()  //   The absolute difference between `x` and `p`
         .compareTo(P.ONE.movePointLeft(22))>0;)
                             //   is larger than 1e-22
      x=                     //    Set `x` to:
        P.valueOf(i-1)       //     `i-1`
         .multiply(p=x)      //     Multiplied by `x` (and store the previous `x` in `p`)
         .add(               //     And add:
          P.divide(          //      PI divided by
           x.pow(i-1),21,5)) //      `x` to the power `i-1`
         .divide(P.valueOf(i),21,5);}}
                             //     Divided by `i`

```
> 2 votes

# Answer
# Perl 5, 72 bytes

```
$n=1;print substr(Math::BigFloat->bpi()**(1/$n++),0,21).$/ while($n<13);

```

Even using \\$\pi\\$ from BigFloat, it doesn't seem to exactly match the given outputs. I'm sure it's truncated properly, though.

Try it online!
> 2 votes

# Answer
# Fortran (GFortran), 48 bytes

```
print*,(acos(-1._16)**(1/real(i,16)),i=1,12)
end

```

Try it online!

Just an implicit loop with quad-precision vars. Not transferable, but works with GCC.
> 1 votes

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