# Question
Title: Counting triangles with integer perimeter
Mary has given John two sticks of lengths `a` and `b` respectively, where `a` and `b` are positive integers.

John is very curious.

He would like to know how many triangles with integer perimeter can be formed, by having one additional side.

Please help him find it out.

(This is my first time composing this kind of stupid stories in coding problems, so forgive me if it is too stupid.)

# Specs

* Given two integers `a` and `b`, find the number of triangles with integer perimeter that can be formed, by having one additional side.

# Details

* Congruent triangles are congruent.
* Flat triangles are flat out uncounted.
* Zero-sided triangles are counted zero times.

# Scoring

This is . Shortest solution in bytes wins.

# Testcases

```
a b output
1 2 1
3 3 5
9 7 13

```

# Answer
> 6 votes
## Jelly, 3 bytes

```
«Ḥ’

```

Try it online!

### Explanation

```
«   min(a,b)
 Ḥ          *2
  ’           -1

```

(Not quite rigorous) proof of correctness:

* Let **x = min(a,b)** and **y = max(a,b)**, and let **z** be a potential third side.
* We can't have **z ≤ y-x**, because for **z \< y-x** the triangle can't be closed and for **z = y-x** it would be degenerate. See triangle inequality.
* We can't have **z ≥ y+x**, for the same reasons.
* Every integer **z** in between is valid and gives a different triangle. That means we've got **(y+x) - (y-x) - 1 = 2x - 1** different triangles.

# Answer
> 4 votes
## CJam, 7 bytes

```
l~e<2*(

```

Test it here.

### Explanation

```
l~  e# Read and evaluate input.
e<  e# min(a,b).
2*  e# Double.
(   e# Decrement.

```

For a proof of correctness, see my Jelly answer which uses the same algorithm.

# Answer
> 3 votes
# 05AB1E, 3 bytes

Using @MartinBüttner's algorithm. Code:

```
·<ß

```

Explanation:

```
·    # Double the input.
 <   # Decrement by 1.
  ß  # Take the smallest value.

```

Uses **CP-1252** encoding. Try it online!.

# Answer
> 2 votes
## Labyrinth, 20 bytes

Thanks to Sp3000 for some help while golfing this.

```
<""-}:?:?
"`
{
++(!@

```

Try it online!

### Explanation

It turns out that the `2*min(a,b)-1` approach isn't the shortest in Labyrinth. Instead it's easier to compute `(a+b)-|a-b|-1`.

Labyrinth primer:

* Labyrinth has two stacks of arbitrary-precision integers, *main* and *aux*(iliary), which are initially filled with an (implicit) infinite amount of zeros. I will usually represent these like `Main [... a b | c d ...] Aux`, where `Main` grows to the right, `Aux` grows to the left and `...` represents the implicit zeros at the bottom.
* The source code resembles a maze, where the instruction pointer (IP) follows corridors when it can (even around corners). The code starts at the first valid character in reading order, i.e. in the top left corner in this case. When the IP comes to any form of junction (i.e. several adjacent cells in addition to the one it came from), it will pick a direction based on the top of the main stack. The basic rules are: turn left when negative, keep going ahead when zero, turn right when positive. And when one of these is not possible because there's a wall, then the IP will take the opposite direction. The IP also turns around when hitting dead ends.
* The source code can be modified at runtime using `<>^v` which cyclically shift a row or column of the grid.

The code starts on the `<` which immediately modifies the source code. This is a common golfing trick in Labyrinth whenever a program starts with a long-ish bit of linear code. Afterwards, the source looks like this, with the IP still on the `<`:

```
""-}:?:?<
"`
{
++(!@

```

Since the IP is now in a dead end, it has to start moving left. The linear code does the following:

```
Op      Explanation                    Stacks
?       Read integer a from STDIN.     Main [... a | ...] Aux
:       Duplicate.                     Main [... a a | ...] Aux
?       Read integer b from STDIN.     Main [... a a b | ...] Aux
:       Duplicate.                     Main [... a a b b | ...] Aux
}       Move b over to aux.            Main [... a a b | b ...] Aux
-       Subtract b from a on main.     Main [... a (a-b) | b ...] Aux

```

The code now enters the only nonlinear part of the code which compues `-abs(x)`, (where I'm now using `<` and `v` to indicate entry and exit points):

```
""<
"`
v

```

The `"` is a no-op (i.e. it does nothing), whereas the ``` multiplies the top of the main stack by `-1`. Let's go through the three possible cases of control flow:

* If `a == b`, i.e. `a-b` is zero, the IP keeps moving west on the first `"`. Then it hits a corner on the the second `"` and has to turn south. Again, it keeps moving south on the third `"` and leaves this 2x2 block. All in all, nothing happens to zeros at all.
* If `a > b`, i.e. `a-b` is positive, the IP turns south on the first `"`. The ``` then switches the top of the main stack to `b-a` and the IP has to take a turn west. On the next `"` the top of the stack is now negative, and the IP turns south. Therefore, if the top of the stack is positive, its sign will be negated by this block.
* If `a < b`, i.e. `a-b` is negative, then the IP also turns towards the ``` , which now makes it positive. That means the IP turns *north* on the next no-op. It hits the corner and turns east, and turns south once more so that it reaches the ``` a second time. At this point, the control flow is no different from a positive input, so after applying ``` twice, we're back at `a-b` which is negative and leaves the loop. Despite doing a lot more stuff, negative inputs are also unaffected by this part of the code.

Now that we've computed `-abs(a-b)`, the remainder of the code is all linear again:

```
Op      Explanation                    Stacks
                                       [... a -|a-b| | b ...]
{       Move b back to main.           [... a -|a-b| b | ...]
+       Add.                           [... a (-|a-b|+b) | ...]
+       Add.                           [... (a+b-|a-b|) | ...]
(       Decrement.                     [... (a+b-|a-b|-1) | ...]
!       Print as integer.              [... | ...]
@       Terminate program.

```

# Answer
> 2 votes
# Cubix, 18 ~~19~~ bytes

Not overly short, but a tad more interesting to do due to a lack of a minimum function.
Saved a byte with a big thanks to Martin Büttner

```
-@IOIU>wu+..U;?;2*

```

This wraps onto a cube with edge length 2 and ends up looking like this

```
    - @
    I O
I U > w u + . .
U ; ? ; 2 * . .
    . .
    . .

```

Explanation that hopefully can be followed. Try it here

Getting parameters from STDIN

```
    -                # This section gets input, u-turns onto top face,
    I                # heading up, gets another input and performs a subtraction.
I U                  # Carries on around the bottom of the cube upto the next part.

```

Determine least and leaving it at TOS

```
    > w              # Hits the ? going up.  if TOS is negative turn left, pop stack
U ; ? ;              # and U-turn onto bottom face heading back up to ?.
    .                # If 0 redirect through > and w to ; popping stack, heading right.
    .                # If positive redirect right to ; which pops TOS

```

Output the answer and end

```
      @              # Push 2 onto the stack, multiply, U-turn onto input which
      O              # gives us -1 for the stack, add it then u-turn to the left
I       u +          # onto the top face, output the TOS as number and end
U       2 *

```

# Answer
> 1 votes
# Javascript full program ~~88~~ 42 bytes

```
a=prompt();b=prompt();alert((a<b?a:b)*2-1)

```

I hate prompts, even java is better in that aspect.

# Javascript function ~~73~~ ~~31~~ 21 bytes

```
(a,b)=>(a<b?a:b)*2-1

```

Testable version:

```
c=(a,b)=>(a<b?a:b)*2-1

var d = prompt("enter first number");
var e = prompt("enter second number");
alert(c(d, e));
```

Thanks to @Neil for saving 8 bytes. Thanks goes to @MartinBüttner for the algorithm and for saving 1 byte.

# Answer
> 1 votes
## Retina, 14 bytes

```
M!`(1+) \1
 1

```

Input and output in unary.

Try it online! (Modified to run multiple decimal test cases at once.)

### Explanation

Still the same approach as my CJam and Jelly answers (the latter contains a proof of correctness), but this time using string processing of unary representations.

```
M!`(1+) \1

```

This finds `min(a,b)` by matching the first string of `1`s that can be found in both of them. This being a match stage and using the `!` the result is actually `min(a,b) min(a,b)` since the entire match is written back.

```
 1

```

This simply matches the separating a space and a single `1` and removes them. This leaves a string of `2*min(a,b) - 1` characters, which is the desired result.

# Answer
> 1 votes
# k (8 bytes)

Using the `Jelly`/`CJam` algorithm

```
-1+2*min

```

e.g.

```
k)-1+2*(&). 10 10
19

```

# Answer
> 1 votes
# Java ~~55~~ 42 bytes

```
int c(int a,int b){return (a<b?a:b)*2-1);}

```

# Answer
> 1 votes
# APL, 6 bytes

```
1-⍨2×⌊

```

This is a dyadic function train that accepts integers on the right and left and returns an integer. It uses the 2 min(*a*, *b*) - 1 approach.

Try it here (includes all test cases)

# Answer
> 1 votes
## Actually, 3 bytes

```
mτD

```

Try it online or verify all test cases at once

This uses the same `2*min(a,b)-1` approach that basically every other solutions uses. Each operation (minimum, double, decrement) is its own single-byte command.

# Answer
> 1 votes
# J, 7 bytes

```
1-~2*<.

```

This is a tacit verb.

```
1-~2*<.
1-~      reflexive minus (i.e. R - 1)
   2*    double
     <.  lesser of

```

# Answer
> 1 votes
# Jolf, 4 bytes

```
m±♀j

```

Replace ♀ with a literal `\x12` byte, or try it here!

## Explanation

```
m±♀j
  ♀j  min of j and implicit input
m±    2*(^)-1

```

# Answer
> 0 votes
# PHP 36 bytes

```
function($a,$b){echo min($a,$b)*2-1}

```

Thanks goes to @MartinBüttner for the algorithm

# Answer
> 0 votes
**C# 6.0 - 34 bytes**

```
int a(int b,int c)=>(b<c?b:c)*2-1;

```

---
Tags: code-golf, math, geometry
---


title: Rainbowlify An Image

text:
# Question
Title: Rainbowlify An Image
This challenge is about gradually shifting hues in an image to make pretty pictures like this:

(original)

# Challenge

Write a program or function that takes in two non-negative integers and an image in any common image file format of your choosing (you can take a path to the image or the raw image data).

We'll call the first integer the **cycles** and the second integer the **offset**.

We'll also define floating-point **step** as 360 times **cycles** divided by the area of the image, or `step = 360 * cycles / (image width * image height)`.

For each pixel **P** in the image, moving one row at a time, left-to-right, top-to-bottom (i.e. in reading order if the pixels were letters), do the following:

1. Increase the hue of **P** by **offset** degrees (looping around from 360 to 0 if necessary).
2. Then increase **offset** by **step**.

Save, display, or output raw the resulting image in any common image file format.

This procedure incrementally increases the hue of all the pixels in the image, making **cycles** full loops around the hue rainbow, starting by initially offsetting the hue by **offset**.

When **cycles** is 1 and **offset** is 0, as in the Starry Night image above, the top and bottom rows of pixels have practically no hue shift but in between there's a full color cycle.

# Details

* **Cycles** can be any non-negative integer but you may assume that **offset** is from 0 to 359 inclusive.
* When **cycles** is 0, every pixel in the image will have its hue shifted by exactly **offset** since **step** must be 0 too. (In this case if **offset** is 0 then the image doesn't change at all.)
* You may assume **cycles** and **offset** are input as floats if desired (i.e. `1.0` instead of `1`). (I realize they needn't be integers at all, it just makes the challenge simpler.)
* "Hue" refers to the RGB color space version, common in HSL/HSV color models.

# Examples

Original:

Cycles = 1, offset = 0:

Cycles = 1, offset = 180:

Original:

Cycles = 2, offset = 60:

Original:

(Thanks ArtOfCode.)

Cycles = 1, offset = 120:

Original:

(Thanks Doorknob.)

Cycles = 1, offset = 0:

Cycles = 4, offset = 0:

Cycles = 200, offset = 0:

Cycles = 30000, offset = 0:

(These images may not be pixel perfect due to imgur compressing them.)

# Scoring

The shortest code in bytes wins. Tiebreaker is higher voted answer.

Answers that post their own cool looking test images will get more brownie points from me.

# Answer
# Pyth, 86 bytes, full program

```
=N.tE7=Z*6*.n0cEl.n'zMmhtS[0255ss*VG.>+Lc-1.tH1 3[.tH1Kc.tH0@3 2_K)d)3.wmmgk~-NZd'z

```

Pyth doesn't have built-in color space conversions - this is the real deal.

Takes input in the following format on stdin:

```
input_filename.png
offset
cycles

```

The output image is written to `o.png`.

---

This works by rotating the color cube around its diagonal, and then clamping any values outside of the range.

If `a` is the angle to rotate by, and `r, g, b` is the input color, we calculate the new color `r', g', b'` by:

```
o = cos(a), i = sin(a) / sqrt(3)
n = (1 - o) / 3
m = [n + o, n - i, n + i]
clamp(c) = max(0, min(255, c))
r' = clamp(r*m[0] + g*m[1] + b*m[2])
g' = clamp(r*m[2] + g*m[0] + b*m[1])
b' = clamp(r*m[1] + g*m[2] + b*m[0])

```
> 8 votes

# Answer
# Java (Full program), 491 488 bytes (Thanks @Geobits)

```
import java.awt.*;import java.io.*;import static javax.imageio.ImageIO.*;class Q{public static void main(String[]v)throws Exception{File f=new File(v[2]);java.awt.image.BufferedImage b=read(f);for(int i=0,j,h=b.getHeight(),w=b.getWidth();i<h;i++)for(j=0;j<w;){Color c=new Color(b.getRGB(j,i));float[]a=new float[3];c.RGBtoHSB(c.getRed(),c.getGreen(),c.getBlue(),a);b.setRGB(j++,i,c.HSBtoRGB((a[0]+Float.valueOf(v[1])/360+(i*w+j)*Float.valueOf(v[0])/w/h)%1,a[1],a[2]));}write(b,"png",f);}}

```

### Ungolfed

```
import java.awt.*;
import java.io.*;

import static javax.imageio.ImageIO.*;

class A79200 {
    public static void main(String[] v) throws Exception {
        File file = new File(v[2]);
        java.awt.image.BufferedImage image = read(file);
        for (int i = 0, j, height = image.getHeight(), width = image.getWidth(); i < height; i++)
            for (j = 0; j < width; ) {
                Color color = new Color(image.getRGB(j, i));
                float[] arr = new float[3];
                color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), arr);
                image.setRGB(j++, i, color.HSBtoRGB((arr[0] + Float.valueOf(v[1]) / 360 + (i * width + j) * Float.valueOf(v[0]) / width / height) % 1, arr[1], arr[2]));
            }
        write(image, "png", file);
    }
}

```

### Explanation

* Usage: Pretty straightforward. Compile with `java -c Q.java`. Run with `java Q <cycles> <offset> <imagepath>`. Will override the existing image, so be careful.
* I was gonna make a method only solution at first but I didn't quite know how to handle imports on those, so I figured I'd go full , this is *probably* not going to win anyways :^)

### Results:

`Image 1: 1 cycle, 0 offset`

`Image 1: 1 cycle, 180 offset`

`Image 2: 2 cycles, 60 offset`

`Image 3: 1 cycle, 120 offset`

`Image 4: 1 cycle, 0 offset`

`Image 4: 4 cycles, 0 offset`

`Image 4: 200 cycles, 0 offset`

`Bonus: The Starry Night, 1 cycle, 0 offset`
> 6 votes

# Answer
# Python, 379 bytes

```
from PIL.Image import*
from colorsys import*
def f(H,c,I):
 i=open(I);x,y=i.size;S=1.*c/(x*y);r,g,b=i.split();R=[];G=[];B=[]
 for x,y,z in zip(r.getdata(),g.getdata(),b.getdata()):
  e=255.;h,s,v=rgb_to_hsv(x/e,y/e,z/e);t=hsv_to_rgb(h+H,s,v);H=H+S%1.;x,y,z=[int(x*e)for x in t];R.append(x);G.append(y);B.append(z)
 p=Image.putdata;p(r,R);p(g,G);p(b,B);return merge('RGB',(r,g,b))

```

This takes a path to a `.jpg` as input. It will not work with png, although you can change `r,g,b=i.split();` to `r,g,b=i.split()[:3];` to load a png image.

Here are some images:

Original:

Offset: 0, Cycles: 4

Original:

Offset 0, 1 cycle:

Original:

Offset 0, 2.5 cycles:
> 6 votes

---
Tags: code-golf, graphical-output, image-processing, color
---


title: Minimize Those Ones

text:
# Question
Title: Minimize Those Ones
Your task is to build a natural number using the fewest number of ones and only the operators `+` or `-`. For example, the number seven can be written `1+1+1+1+1+1+1=7`, but it can also be written as `11-1-1-1-1=7`. The first one uses `7` ones, while the latter only uses `6`. Your task is to return the minimum number of ones that can be used given the input of some natural number, `n`.

This is code golf, so the shortest valid code in bytes wins.

### Test cases

Input =\> Output

```
0 => 2 (since 1-1=0)
7 => 6
121 => 6
72 => 15
1000 => 7
2016 => 21

```

# Answer
> 3 votes
## JavaScript (ES6), ~~127~~ ~~126~~ 87 bytes

```
f=(n,z=2,m=n*9+'',r=m.replace(/./g,1))=>n?m.length+(m<'55'?f(n- --r/10,0)-1:f(r-n,0)):z
```

```
Input: <input type="number" oninput="result.textContent=f(this.value)"> Result: <span id="result"></span>
```

Should work to about 10~~14~~15 at which point you start running into JavaScript's integer limits. Explanation:

```
f=(                             Recursive function
 n,                             Parameter
 z=2,                           Zero workaround
 m=n*9+'',                      Magic
 r=m.replace(/./g,1)            Find repunit not less than than n
)=>n?                           Nothing to do if n is zero
 m.length+                      Assume subtracting from repunit
 (m<'55'?                       Should we subtract from repunit?
  f(n- --r/10,0)                No, so subtract previous repuint
   -1:                          Which is one 1 shorter
  f(r-n,0)):                    Subtract from repunit
 z                              Return special case if n is zero

```

This uses the `n*9` magic twice; firstly, it gives me the length of the next repunit, secondly, if the first two digits of `n*9` are `55` or higher, then we need to subtract `n` from that next repunit, otherwise we need to subtract the previous repunit (which is calculated by subtracting 1 and dividing by 10). This should work up to 1015.

# Answer
> 2 votes
# Pyth, ~~19~~ 16 bytes

```
ffqQvs+R1Y^c3"+-

```

Test suite

Brute force algorithm. The necessary strings are generated by taking all lists whose elements are `['+', '-', '']` of length equal to the number of 1s being tested, appending a 1 to each, and concatenating to a single string. These strings are then evaluated and compared with the input. This is repeated until a successful string is found.

Some strings with a leading `+` or `-` are tested, but this isn't a problem. It would be if the input was negative though.

It can run up to length 9 before it becomes too slow.

**Explanation:**

```
ffqQvs+R1Y^c3"+-
ffqQvs+R1Y^c3"+-"T    Implicit variable introduction
                      Q = eval(input())
f                     Starting with T = 1 and counting upwards, repeat until true.
                      The value of T where the result is first true is output.
           c3"+-"     Chop "+-" into thirds, giving ['+', '-', '']
          ^      T    Form every list with those elements of length T.
 f                    Filter over those lists, lambda var Y.
      +R1Y            Append a 1 to each element of the list.
     s                Concatenate.
    v                 Eval.
  qQ                  Compare for equality with the input.
                      The inner filter will let through the successful cases.
                      The outer filter will stop when there is a successful case.

```

# Answer
> 2 votes
# JavaScript (ES6), 92 bytes

```
f=(n,i=3)=>eval([...s=i.toString(3)].map(d=>"-+"[d]||"").join`1`+".0")-n?f(n,i+1):s.length-1
```

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

## Explanation

Recursive function. This generates all possible permutations of `1`s separated by either `+`, `-` or nothing. It does this by incrementing a base-3 number, turning it into an array of digits, converting each digit `0` to `-`, `1` to `+` and `2` to an empty string, then joining them together with `1`s. The resulting string is `eval`d as a JavaScript statement which returns the result of the equation.

Because the operators are joined with `1`s in between (like `+1+1+1+`), there are `length - 1` `1`s. The first operator is ignored (because `+1` = `1`, `<nothing>1` = `1` and it's a number so there will never be a leading `0` for `-`) and the final operator is also ignored (by appending `.0` to the equation).

### Higher Output Version, 96 bytes

The other version can't return outputs higher than ~10 because of the recursion call stack limit. This version uses a for loop instead of recursion, so it can return outputs up to ~33. The amount of time required increases exponentially though so I don't recommend testing it.

```
n=>eval('for(a=3;eval([...s=a.toString(3)].map(d=>"-+"[d]||"").join`1`+".0")-n;)a++;s.length-1')

```

---
Tags: code-golf, number-theory
---


title: How many shapes are in this picture?

text:
# Question
Title: How many shapes are in this picture?
Children are very good at classifying objects and counting them. Computers seem to have more trouble. This is a simplified version of this problem. Can you write a small program that can classify and count objects in an image?

The problem: Given an image containing one or more circles and rectangles, return 2 integers with the count of circles and count of rectangles.

## Rules

* The input image will be black figures on a white background in any bitmap format you choose.
* The image width and height will be between 100 and 1000 pixels.
* Figures will be fully contained within the image.
* Figures will have 1 pixel line width.
* Images will not use anti-aliasing. They will be black on white only.
* Figures may touch, intersect, or be inside another figure.
* Intersecting figures will have a maximum of 4 common pixels.
* Circles will have a diameter of 20 pixels or more.
* Rectangle sides will be 10 or more pixels long.
* You may not use any built-ins or libraries that recognize shapes, or any other function that makes this challenge trivial.
* Return or print 2 integers with the counts of circles and rectangles.

## Example 1

Answer: 3 4

## Example 2:

Answer: 4 13

This is a code golf challenge, so the shortest program or function in each language will win.

# Answer
> 4 votes
# PHP – 355 bytes

The byte count doesn't include `'<image-url>'`.

```
<?php
m('<image-url>');function m($f){$i=imagecreatefrompng($f);$r=f($i,17);$c=f($i,9);echo($c-$r).' '.$r."\n";}function f($i,$k){$w=imagesx($i);$h=imagesy($i);$r=0;for($y=0;$y<$h;$y++)for($x=0;$x<$w;$x++)if(!imagecolorat($i,$x,$y))$r+=g($i,$x,$y,$w,$k);return$r;}function g($i,&$x,$y,$w,$k){$l=$x;while(!imagecolorat($i,$x,$y)&&$x<$w)$x++;return($x-$l>$k)?1/2:0;}

```

In the two test cases, the URLs I used are `https://i.stack.imgur.com/qnIFk.png` and `https://i.stack.imgur.com/HV9k3.png`.

Counts horizontal lines and divides by two to get the number of shapes. Relies on the observation that circles have shorter horizontal segments and rectangles have longer horizontal segments.

Admitted hack, not guaranteed to work for anything other than the test cases!

I tried rotating the images by ± 45° and detecting for horizontal lines. This would be equivalent to checking for diagonal lines and would pick up the circles better, but I couldn't find an interpolation algorithm which left clean enough edges to work with. For example, they might smudge a line into two rows of pixels and mess up the count.

---
Tags: code-golf, image-processing, counting
---


# Question
Title: Determine If a Challenge is Worth Answering
I am a *very* casual code golfer, and don't often see posts until they show up in the "Hot Network Questions" sidebar over on StackOverflow. Usually, I'm late to the game, and since the only language I know is Python, there is little point in me answering as there are already several Python answers. Your challenge is to figure out if a question is worth me answering.

**Input:**

* Your code (function or program) will take one input parameter `i`

**Output:**

* Truthy or Falsey value for question id `i`. Output Truthy if question has more than 5 answers, greater than 3 question score, and one or less answer in Python (no distinction between version).

**Rules/Clarifications:**

* Input format can be anything reasonable (stdin, file, command line), but should be specified in your answer. Data types and leading/trailing whitespace doesn't matter.
* Assume question id is valid for `codegolf.stackexchange.com`.
* Ignore language specific question requirements. (i.e. if a question meets votes and answers, and has no Python answers because it is Java only, it still results in Truthy).
* An answer qualifies as a Python answer if "python" (case insenstive) occurs anywhere before the first newline of the post.
* This is code golf, so shortest code in bytes wins.

**Sample Cases\***

```
id = 79082 => True
id = 78591 => False (less than 5 answers, also hella hard)
id = 78410 => True
id = 76428 => False (greater than 1 Python answer)
id = 78298 => False (not high enough question score)

```

*\*Verified at time of posting, may have changed*

# Answer
> 9 votes
# 05AB1E, ~~167~~ ~~160~~ ~~159~~ ~~158~~ ~~156~~ ~~154~~ 143 bytes

~~Damn, almost as long as a normal language...~~

Crap... ~~longer~~ ~~currently beating the the Ruby answer by *1* byte.~~

~~Now longer than the Ruby answer, ***argh!***.~~

I probably should go to bed right now.

Thanks to @wnnmaw for saving 1 byte and thanks to @R. Kap for saving another 2 bytes!

### Code:

```
’£Ø ˆå§¾.‡¢ as g;#.¾¿„–(g.ˆåƒÛ('·Ç://ÐÏg.´¢/q/'+•œ_#()).‚Ø())’.e©’„à="Ž»"’DU¢®…îŒ€ƒŠ‡¡`99£þs\®X¡¦vy’„à="‚¬-„¹"’¡¦'>¡¦¦¬l’±¸’¢s\}rUV)O2‹X5›Y3›)P

```

Or with more readability:

```
’£Ø ˆå§¾.‡¢ as g;#.¾¿„–(g.ˆåƒÛ('·Ç://ÐÏg.´¢/q/'+•œ_#()).‚Ø())’
 .e©
’„à="Ž»"’
 DU¢®
“îŒ€ƒŠ‡“
 ¡`99£þs\®X¡¦
v
 y’„à="‚¬-„¹"’¡¦'>¡¦¦¬l’±¸’¢s\}rUV)O2‹X5›Y3›)P

```

### Explanation:

First of all, a lot of text is being compressed here, which translates to good old Python. The uncompressed version is:

```
"import urllib.request as g
 f=g.urlopen('http://ppcg.lol/q/'+pop_#())
 #.append(f.read())"
.e©“class="answer"“¢®"useful and clear"¡`99£þs\®“class="answer"“¡¦vy“class="post-text"“¡¦'>¡¦¦¬l"python"¢s\}rUV)O2‹X5›Y3›)P

```

This part:

```
import urllib.request as g
stack.append(g.urlopen('http://ppcg.lol/q/'+pop_stack()).read())`

```

actually pops a stack value, copies it into the url and fetches all HTML data. The HTML data is pushed on top of the stack using `#.append(f.read())`.

We count the **number of answers**, by count the number of occurences of `class="answer"`.

To count the number of votes, we just split the data at "useful and clear" and keep only the digit values of `[0:99]` using `®"useful and clear"¡`99£þ`. This is the number of upvotes.

Eventually, we need to check every answer if the text `"Python"` exists before the closing header text. To get all answers, we just split the data on `class="post-text"` and split each of them again on `<`. We remove the first two elements to get the part in which the language is displayed and check if the lowercase version is in this string.

So, now our stack looks like this for id = `79273`:

```
`[6, '14', 0, 0, 0, 1, 0, 0]`
  │    │   └───────┬──────┘
  │    │           │
  │    │   is python answer?
  │    │
  │    └── number of upvotes
  │
  └─── number of answers

```

This can also be seen with the `-d`ebug flag on in the interpreter.

So, it's just a matter of processing the data:

```
rUV)O2‹X5›Y3›)P

r                # Reverse the stack
 U               # Pop the number of answers value and store into X
  V              # Pop the number of upvotes value and store into Y
   )O            # Wrap everything together and sum it all up
     2‹          # Check if smaller than 2
       X5›       # Push X and check if greater than 5
          Y3›    # Push Y and check if greater than 3
             )P  # Wrap everything into an array and take the product.
                   This results into 1 if and only if all values are 1 (and not 0).

```

Uses **CP-1252** encoding. You can download the interpreter here.

# Answer
> 5 votes
# Python 3.5, 280 272 260 ~~242~~ 240 bytes:

(*Thanks to Adnan for the trick about using the `*` operator in comparisons resulting in 2 saved bytes!*)

```
def g(o):import urllib.request as u,re;R=re.findall;w=bytes.decode(u.urlopen('http://ppcg.lol/q/'+o).read());print((len(R('(?:<h[0-9]>|<p>).*python',w.lower()))<2)*(int(R('(?<="vote-count-post ">)[0-9]+',w)[0])>3)*w.count('answercell">')>5)

```

Simple enough. Uses Python's built in `urllib` library to go to the question's site, and then uses regular expressions to find the vote count, answer count, and the count of Python specific answers in the decoded text returned from the website. Finally, these values are compared against the conditions required to return a `truthy` value, and if they satisfy all the conditions, then `True` is returned. Otherwise `False` is.

The only thing I may be worried about here is that the regular expressions give a lot of lee way in the terms of the number of python specific answers to save bytes, so it may be a bit inaccurate at times, though it's probably good enough for the purposes of this challenge. However, if you want a much more accurate one, I have added one below, although its longer than the one above. The one shown below is currently 298 bytes since it uses a much longer regular expression–one which you couldn't know how long it took me to discover–for counting Python answers than my original function for the sake of accuracy. This one should work for about at least 80% to 90% of all test cases thrown at it.

```
def g(o):import urllib.request as u,re;R=re.findall;w=bytes.decode(u.urlopen('http://ppcg.lol/q/'+o).read());print(len(R('(?<=answercell">).*?(?:<h[0-9]>|<strong>)[^\n]*python[^\n]*(?=</h[0-9]>|</strong>)',w.lower()))<2and int(R('(?<="vote-count-post ">)[0-9]+',w)[0])>3and w.count('answercell">')>5)

```

But, what about those questions with multiple pages of answers? Neither of the above will work very well in that situation, if, say, 1 python answer is on the first page and another is on the second. Well, I took the liberty to fix this issue by creating another version of my function (shown below) that checks *every page* of answers, if multiple ones exist, for Python answers, and it has done quite well on many of the test cases I have thrown at it. Well, without further ado, here is the new and updated function:

```
def g(o):
 import urllib.request as u,re;R=re.findall;w=bytes.decode(u.urlopen('http://ppcg.lol/q/'+o).read());t=0if len(re.findall('="go to page ([0-9]+)">',w))<1else max([int(i)for i in re.findall('="go to page ([0-9]+)">',w)])
 if t<1:print(len(R('(?<=answercell">).*?(?:<h[0-9]>|<strong>)[^\n]*python[^\n]*(?=</h[0-9]>|</strong>)',w.lower(),re.DOTALL))<2and int(R('(?<="vote-count-post ">)[0-9]+',w)[0])>3and w.count('answercell">')>5)
 else:
  P=[];U=[];K=[]
  for i in range(2,t+2):P.append(len(R('(?<=answercell">).*?(?:<h[0-9]>|<strong>)[^\n]*python[^\n]*(?=</h[0-9]>|</strong>)',w.lower(),re.DOTALL)));U.append(int(R('(?<="vote-count-post ">)[0-9]+',w)[0]));K.append(w.count('answercell">'));w=bytes.decode(u.urlopen('http://ppcg.lol/questions/'+o+'/?page='+str(i)).read())
  print(sum(P)<2and U[0]>3and sum(K)>5);print('# Python answers: ',sum(P));print('# Votes: ',U[0]);print('# Answers: ',sum(K))

```

Quite long, isn't it? I wasn't really going much for code golf with this, although, if you want, I can golf it down a bit more. Otherwise, I love it, and could not be happier. Oh, I almost forgot, as an added bonus, this also outputs the total number of Python answers on the question, total votes on the question, and total number of answers on the question if the question `id` corresponds to a question with more than 1 page of answers. Otherwise, if the question only consists of a single page of answers, it just outputs the `truthy/falsy` value. I really did get a bit carried away with this challenge.

These each take the question's `id` in the form of a *string*.

I would put `Try It Online!` links here for each function, but unfortunately, neither `repl.it` nor `Ideone` allow fetching of resources via Python's `urllib` library.

# Answer
> 4 votes
# Ruby + HTTParty, ~~170~~ ~~146~~ ~~145~~ ~~142~~ ~~139~~ 138 + 11 ( `-rhttparty` flag) = ~~181~~ ~~157~~ ~~156~~ ~~153~~ ~~150~~ 149 bytes

I don't think there's any edge cases that would cause my regex patterns to break, I hope...

Updated to the shortlink provided by @WashingtonGuedes and discovering that HTTParty doesn't complain if I start with `//` instead of `http://`.

Updated for slightly more secure regexes. I saved bytes anyways by discovering that HTTParty response objects inherit from String, which means I don't even need to use `.body` when matching the regex!

@manatwork pointed out an accidental character addition that I had left in, and for the sake of golf, `i` has to be accepted as a String now.

Updated regexes. ~~Same length.~~ -1 byte by cutting out a paren.

```
->i{/"up.*?(\d+)/=~s=HTTParty.get("//ppcg.lol/q/"+i)
$1.to_i>3&&(a=s.scan /st.*xt".*\n(.*)/).size>5&&a[1..-1].count{|e|e[0]=~/python/i}<2}

```

Extra notes:

* The first line of an answer (which should contain the language according to the spec) is two lines after the HTML Tag with class `"post-text"`, which we matched with `st.*xt"`. A more secure version would have added a space after it, but we're sacrificing that for the sake of golf.
* HTTParty is used over the native `net/http` modules because of proper redirect handling for the given URL.
* `"up*?\d` was the shortest sequence I found that corresponded with the number of votes. We only need the first one, so thankfully answers don't affect this.

# Answer
> 4 votes
# Julia, 275 bytes

```
using Requests
f(q,p=(s,t)->JSON.parse(readall(get("https://api.stackexchange.com/2.2/questions/$q$s",query=Dict(:site=>"codegolf",:filter=>"$t"))))["items"],x=p("","")[1])=x["answer_count"]>5&&x["score"]>3&&count(i->ismatch(r"python",i["body"]),p("/answers","!9YdnSMKKT"))<2

```

This is a function that accepts an integer and returns a boolean. It connects to the Stack Exchange API and each run of the function makes 2 API requests, so don't run it too many times or you'll exhaust your 300 requests/day quota.

Ungolfed:

```
using Requests

function f(q)
    # Define a function that takes two strings and returns a Dict
    # that connects to the SE API
    p = (s,t) -> JSON.parse(readall(get("https://api.stackexchange.com/2.2/questions/$q$s",
        query = Dict(:site => "codegolf", :filter=> "$t"))))["items"]

    # Get the question object
    x = p("", "")[1]

    # Get all answers using the `withbody` API filter
    y = p("/answers", "!9YdnSMKKT")

    x["answer_count"] > 3 && x["score"] > 5 &&
        count(i -> ismatch(r"python", i["body"], y) < 2
end

```

# Answer
> 4 votes
# Racket, 339 Bytes

```
(λ(q)((λ(h)((λ(g)((λ(j)(and(>(h j'score)3)(>(h j'answer_count)5)(<(for/sum([a(g"~a/answers"q)]#:when(regexp-match #rx"(?i:python)"(h a'body)))1)2)))(car(g"~a"q))))(λ(s d)(define-values(x y b)(http-sendrecv"api.stackexchange.com"(format"/2.2/questions/~a?site=codegolf&filter=withbody"(format s d))))(h(read-json b)'items))))hash-ref))

```

There is much to golf, still.

# Answer
> 3 votes
# Groovy, 179 161 157

```
{i->t=new URL("http://ppcg.lol/q/$i").text;a=0;p=0;(t=~/"(?i)p.{25}>\n.*python/).each{p++};(t=~/(?m)v.{13}t ">(\d+)/).each{if(it[1].toLong()>3)a++};a>5&&p<2}

```

Thanks to Timtech 17 chars saved.

Keyword *def* is also not necessary.

---
Tags: code-golf, internet, classification
---


title: Automatic house-builder

text:
# Question
Title: Automatic house-builder
Automatic house building nanobots have been fabricated, and it's your job to code them.

Here is the house created by input `7 4 2`

```
  /-----/|
 /     / |
|-----|  |
|     |  |
|     | /
|_____|/

```

The input is a string containing the house's dimensions.

`7` is the width.

```
|_____|

---7---

```

`4` is the height.

```
|
|
|
|

```

`2` is the depth

```
 /
/

```

Given this input, can you create the house?

Your code must be as small as possible so that it can fit in the robots.

## Notes

The smallest dimensions you will be given as input are `3 2 2`. Your program can do anything with dimensions that are smaller than `3 2 2`.

## Testcases

```
3 2 10

          /-/|
         / / |
        / / /
       / / /
      / / /
     / / /
    / / /
   / / /
  / / /
 / / /
|-| /
|_|/

```

# Answer
> 3 votes
## Python 2, 128 bytes

```
w,h,d=input();i=d
while-i<h:c='|/'[i>0];print' '*i+c+'- _'[(d>i!=0)+(h+i<2)]*(w-2)+c+' '*min(d-i,h-1,w+1,h-1+i)+'/|'[d-i<h];i-=1

```

Prints row by row. The row indices `i` count down from `d` to `-h+1`.

# Answer
> 1 votes
## JavaScript (ES6), 169 bytes

```
(w,h,d)=>[...Array(d+h--)].map((_,i)=>` `[r=`repeat`](i<d&&d-i)+(c=`|/`[+(i<d)])+` _-`[i&&i-d?h+d-i?0:1:2][r](w-2)+c+` `[r]((i<d?i:d)-(i>h&&i-h))+`|/`[+(i>h)]).join`\n`

```

Where `\n` represents a literal newline character. Explanation:

```
(w,h,d,)=>                          Parameters
[...Array(d+h--)].map((_,i)=>       Loop over total height = d + h
 ` `[r=`repeat`](i<d&&d-i)+         Space before roof (if applicable)
 (c=`|/`[+(i<d)])+                  Left wall/roof edge
 ` _-`[i&&i-d?h+d-i?0:1:2][r](w-2)+ Space, floor or eaves between walls
 c+                                 Right wall/roof edge (same as left)
 ` `[r]((i<d?i:d)-(i>h&&i-h))+      Right wall
 `|/`[+(i>h)]                       Back wall/floor edge
).join`                             Join everything together
`

```

Edit: Saved 2 bytes thanks to @jrich.

# Answer
> 1 votes
# Ruby, 145 bytes

Returns a list of strings. Each element in the list corresponds to a line. If a multiline string must be returned, add 3 bytes to add `*$/` right before the last bracket.

```
->w,h,d{s=' ';(0..m=d+h-1).map{|i|(i<d ?s*(d-i)+?/:?|)+(i<1||i==d ??-:i==m ??_ :s)*(w-2)+(i<d ? ?/:?|)+(i<h ?s*[i,d].min+?|:s*[m-i,h-1].min+?/)}}

```

# Answer
> 1 votes
# Python 224 301 297 Bytes

(Now Works for all boxes including 1x1x1)

```
l,w,h=input()
s,r,d,v,R,x=" "," - ","/","|",range,(l*3-1)
print s*(w+1)+r*l
for n in R(w):
    if n<h:e,c=v,n
    else:e,c=d,h
    print s*(w-n)+d+s*x+d+s*c+e
if h-w>=1:e,c=v,w
elif w>h:e,c=d,h
else:e,c=d,w
print s+r*l+s*c+e
for n in R(h):
    if h>w+n:e,c=v,w
    else:e,c=d,h-n-1
    print v+s*x+v+s*c+e
print r*l

```

Explanation:

Takes in three constants: l (length), h(height), w(width).

If we look at a couple sample boxes we can find patterns in the spacing.

For a 3 x 4 x 3 box, we will use numbers to represent spacing between sections.

```
1234 -  -  -
123/12345678/|
12/12345678/1|
1/12345678/12|
1 -  -  - 123|
|12345678|123/
|       8|12/
|       8|1/
|       8|/
 -  -  -

```

The top row has 4 spaces or which is w + 1. The Next three lines have w - (1 * x). X being the line.

These are patterns that continue throughout all lines in all boxes. Therefore, we can easily program this line by line, multiplying the number of spaces to fit the pattern.

Here is a sample for a 5 x 5 x2 box.

```
 123 -  -  -  -  -
 12/12345678912345/|
 1/              /1|
 1 -  -  -  -  - 12|
 |              |12|
 |              |12|
 |              |12|
 |              |1/
 |12345678912345|/
  -  -  -  -  -

```

# Answer
> 0 votes
# Python 3.5, 328 326 313 305 295 248 bytes

(*Thanks to Kevin Lau for the tip about reducing the size of the ternary statements!*)

```
def s(w,h,d):R,M=range,max;S,V,L=' |/';O=w-2;D=d-M(0,d-h);Q=h-M(0,h-d);print('\n'.join([S*(d-i)+L+' -'[i<1]*O+L+S*[h-1,i][i<=D-1]+'/|'[i<=D-1]for i in R(D+M(0,d-h))]+[V+[' -'[i==h],'_'][i<2]*O+V+S*[i-1,d][i>Q]+'/|'[i>Q]for i in R(Q+M(0,h-d),0,-1)]))

```

Takes input as 3 integers in the order of `width, height, depth`. Will golf more over time wherever I can.

Try it online! (Ideone)

## Explanation:

For the purposes of this explanation, assume the function was executed with the arguments `(3,2,3)` where 3 is the width (`w`), 2 is the height (`h`), and 3 is the depth (`d`). That being said, let me begin by showing the main part of the entire function:

```
'\n'.join([S*(d-i)+L+' -'[i<1]*O+L+S*[h-1,i][i<=D-1]+'/|'[i<=D-1]for i in R(D+M(0,d-h))]+[V+[' -'[i==h],'_'][i<2]*O+V+S*[i-1,d][i>Q]+'/|'[i>Q]for i in R(Q+M(0,h-d),0,-1)])

```

Here, the two lists that make up the entire "house" are created and then joined together by literal new lines (`\n`). Let's call them list `a` and list `b` respectively, and analyze each one of them:

* Here is where list `a` is created:

```
[S*(d-i)+L+' -'[i<1]*O+L+S*[h-1,i][i<=D-1]+'/|'[i<=D-1]for i in R(D+M(0,d-h))]

```

This list contains the first `d` lines of the house. Here, `i` is each number in the range `0=>(d-(d-h))+d-h` where `d-h=0` if negative or zero. To start, `d-i` spaces are added to the list, followed by a `/` and then whatever is returned by a compressed conditional statement. In this conditional statement, `w-2` number of spaces are returned if `i>1`. Otherwise the same number of `-` are returned. Then, these are followed up by another `/`, and then spaces, where the number of spaces now depends on whether or not `i<=d-(d-h)-1`. If it is, then `i` spaces are added. Otherwise, `h-1` spaces are added. Finally, this is all topped off by either a `/` or a `|`, where `|` is added if `i<=d-(d-h)-1`, otherwise a `/` is added. In this case of a `3x2x3` prism, this would be returned by list `a`:

```
      /-/|
     / / |
    / / /

```
* Here is where list `b` is created:

```
[V+[' -'[i==h],'_'][i<2]*O+V+S*[i-1,d][i>Q]+'/|'[i>Q]for i in R(Q+M(0,h-d),0,-1)]`

```

This lists contains the rest of the lines of the prism. In this list, `i` is each integer in the range `(h-(h-d))+h-d=>0` where `h-d=0` if negative or zero. To start this list off, firstly a `|` is added since these lines always start with a `|`. Then, either a space, `-`, or `_` is added depending on whether or not `i=h` or `i<2`. If `i<2`, then a `_` is added. Otherwise, a `-` is added if `i=h`, or a space is added if `i>h` or `i<h` or `i>2`. After this decision has been made, then `w-2` number of the chosen character is added. After this, another `|` is added, and then either `i-1` or `d` number of spaces are added. If `i>h-(h-d)`, then a `d` number of spaces are added. Otherwise, `i-1` number of spaces are added. Finally, this is all topped off with either a `|` or a `/`, in which a `|` is added if `i>h-(h-d)`, or a `/` is added if `i<=h-(h-d)`. In the case of a `3x2x3` prism, list `b` returns:

```
    |-| /
    |_|/

```

After the 2 lists have been created, they are finally joined with literal new lines (`\n`) using `'\n'.join()`. This is your completed prism, and in this case, would come to look like this:

```
       /-/|
      / / |
     / / /
    |-| /
    |_|/

```

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


# Question
Title: The GOLF CPU Golfing Challenge: Sides of a Cuboid
This challenge is the second of a series of problems that should be written in the GOLF CPU. You can find the first here

For this problem, you are given the volume of a cuboid (A rectangular cube). Each of the side lengths are integers. You must return the number of distinct cuboids that have that volume. This sequence matches A034836 (thanks Tylio)

```
Input:Output [List] [of] [cuboids]
1:1 [1,1,1]
5:1 [1,1,5]
8:3 [1,1,8] [1,2,4] [2,2,2]
24:6 [1,1,24] [1,2,12] [1,3,8] [1,4,6] [2,2,6] [2,3,4]
100:8 [1,1,100] [1,2,50] [1,4,25] [1,5,20] [1,10,10] [2,2,25] [2,5,10] [4,5,5]
1080:52
468719: 1
468720: 678
468721: 2

```

Your program should be written in GOLF CPU. For input/output you can either use STDIO or the registers. Hardcoding primes or answers isn't allowed.

This is a problem, so the answer that solves the examples above with the fewest amount of cycles wins!

# Answer
# 14,483 cycles

I use the fact that the output depends only on the signature (exponents in the prime factorization) of the input. I used the formula from https://oeis.org/A034836. The sieve of Eratosthenes is used to find primes to factorize the input by trial division.

```
# Input in register n
# Outputs in register r and exit code

# the signature of n (exponents in its prime factorization) are stored in
# memory starting at address 0x1000000000000000.  They are byte-sized
# since the largest exponent we can have is 64 (2**64)

# mov z, 0x1000000000000000 (implicit)
mov y, z

# pull out factors of 2
# number of factors is stored in k
# mov k, 0 (implicit)
factor_two:
  and c, n, 1
  snz c, 3
    shr n, n, 1
    inc k
    jmp factor_two

# store factors of two if nonzero
sz k, 2
  sb z, k
  inc z

# Sieve of Eratosthenes
# we only check odd primes, since we already removed factors of 2
# we store COMPOSITE(i) at address i
# we also check n for divisibility by every prime we find
# note we only have to check for prime factors up to sqrt(n)!

mov i, 1
sieve_loop:
  add i, i, 2 # go to the next odd number
  lb c, i # check if COMPOSITE(i)
  jnz sieve_loop, c # if so, continue

  mulu j, k, i, i # j = i**2
  geu c, j, n              # if i**2 > n:
  jnz end_sieve_loop, c #   break

  # otherwise, i is prime; check if n is divisible by i
  mov k, 0
  factor_i:
    divu q, r, n, i # r = n % i
    snz r, 3
      mov n, q      # n /= i
      inc k
      jmp factor_i

  # store factors of i if nonzero
  sz k, 2
    sb z, k
    inc z

  # now cross off all composites that are odd multiples of i,
  # but only up to sqrt(n)
  shl d, i, 2 # d = 2 * i
  # we already have j = i**2, we can start marking composites here:
  # since every lesser multiple of i must have a smaller  prime factor and
  # therefore must have already been marked

  sieve_inner_loop:
    sb j, 1
    add j, j, d # j += 2*i
    mulu c, k, j, j  # c = j**2
    leu c, c, n             # if j**2 < n:
    jnz sieve_inner_loop, c #   continue

  jmp sieve_loop

end_sieve_loop:

# if n != 1, n is a prime and needs to be added to the signature
cmp c, n, 1
snz c, 2 # skip if n==1
  sb z, 1

#mov z, 0x1000000000000000

# according to https://oeis.org/A034836, we have:
# a(n) = (np + 3*nsq + 2*ntp)/6
# where np = Times@@Binomial[2+s,2],
# ntp = Times@@Floor[Floor[s,3]/s],
# nsq = Times@@(Floor[s/2] + 1),
# and s is the signature

# Binomial[2+s,2] == (1+s)(2+s)/2
# Floor[Floor[s,3]/s] == 1 if s divides 3, 0 otherwise

# I tested this formula up to n=10,000,000

mov t, 0 # <= BUG? (doesn't work without this line)
mov d, 1 # np
mov e, 1 # ntp
mov f, 1 # nsq

product_loop:
  lb s, y
  jz finish, s
  inc y

  divu q, r, s, 3 # r = s % 3
  sz r, 1
    mov e, 0

  inc s
  mulu d, x, d, s # d *= s + 1

  inc s
  mulu d, x, d, s # d *= s + 2
  shr d, d, 1     # d /= 2

  shr s, s, 1     # s /= 2 (s == (s+2)/2 == floor(s/2) + 1)
  mulu f, x, f, s # f *= floor(s/2) + 1

  jmp product_loop

finish:

add r, e, f # r = e + f
shl r, r, 1 # r *= 2
add r, r, f # r += f
add r, r, d # r += d
            # r == d + 3*f + 2*e

divu r, s, r, 6 # r /= 6

halt r

```

Test cases:

```
robert@unity:~/golf-cpu$ ./assemble.py cube.golf
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=1
Execution terminated after 42 cycles with exit code 1.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=5
Execution terminated after 77 cycles with exit code 1.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=8
Execution terminated after 91 cycles with exit code 3.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=24
Execution terminated after 126 cycles with exit code 6.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=100
Execution terminated after 218 cycles with exit code 8.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=1080
Execution terminated after 236 cycles with exit code 52.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=468719
Execution terminated after 9710 cycles with exit code 1.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=468720
Execution terminated after 422 cycles with exit code 678.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=468721
Execution terminated after 3561 cycles with exit code 2.
robert@unity:~/golf-cpu$

```
> 7 votes

# Answer
# Total cycles for examples: 29,566,640

It cubes the input number in the algorithm, so the input can't be larger than around `2^21`.

Cycle count for example input:

```
Input    Cycles
1        153
5        75
8        773
24       1,528
100      3,185
1080     27,608
468719   9,676,846
468720   9,764,814
468721   10,091,658

```

I'm using an algorithm I found on OEIS, which does the following:

```
cuboids(n):
    if is_prime(n):
        return 1
    res = 0
    for d in divisors(n):
        if d^3 <= n:
            for d0 in divisors(n/d):
                if d0^2 <= n/d:
                    res += 1
                if d0 < d:
                    res -= 1

    return res

```

This might actually be slower than just trying every divisor combination and checking if `d1 <= d2 <= d3`, however the bottle-neck is finding the prime anyway.

Divisors are found by using the prime factorization of the number. I'm using the same method to build an array of all primes below the input number as I used in the previous problem.

Run with:

```
python3 assemble.py 52489-cuboids.golf
python3 golf.py -d 52489-cuboids.bin x=<INPUT>

```

Output will be in the `t` register.

Example run:

```
$ python3 golf.py -d 52489-cuboids.bin x=1080 | grep 'Execution\|t: '
Execution terminated after 27608 cycles with exit code 0. Register file at exit:
t: 52                   0x34

```

Code:

```
    call build_primes

    mov q, x
    call is_prime
    jnz prime, a

    shl m, x, 3
    add m, m, 8
    call divisors

    mov y, x
    mov k, l

    mov t, 0

    mov p, m

outer_loop:
    cmp a, p, k
    jnz done, a

    lw d, p

    add p, p, 8

    mulu a, r, d, d
    mulu a, r, a, d
    lequ a, a, y
    jz outer_loop, a

    divu x, r, y, d
    mov m, k
    call divisors

    mov q, m

inner_loop:
    cmp a, q, l
    jnz outer_loop, a

    lw o, q

    add q, q, 8

    mulu a, r, o, o
    lequ a, a, x
    jz skip1, a

    inc t

skip1:
    leu a, o, d
    jz inner_loop, a

    dec t

    jmp inner_loop

done:
    halt 0

prime:
    mov t, 1
    halt 0

# Input: x, m
# Output: l
# x: input number
# m: memory location to store divisors
# l: memory location where last divisor is stored + 8
divisors:
    sw m, 1
    add l, m, 8

    mov p, 2

divisors_outer:
    mov q, 1
    push z, 0

divisors_inner:
    divu y, r, x, p
    jnz divisors_not_divisible, r

    mulu q, r, q, p
    push z, q

    mov x, y

    jmp divisors_inner

divisors_not_divisible:
    mov w, l

divisors_not_divisible_outer:
    mov v, m

    pop t, z
    jz divisors_not_divisible_last, t

divisors_not_divisible_inner:
    cmp a, v, w
    jnz divisors_not_divisible_outer, a

    lw s, v
    mulu a, r, s, t
    sw l, a
    add l, l, 8

    add v, v, 8

    jmp divisors_not_divisible_inner

divisors_not_divisible_last:
    shl i, p, 3
    lw p, i

    cmp a, x, 1
    jz divisors_outer, a

    ret l

# Input: x
# Memory layout: [-1, -1, 3, 5, -1, 7, -1, 11, ...]
# x: max integer
# p: current prime
# y: pointer to last found prime
# i: current integer
build_primes:
    sw 0, -1
    sw 8, -1
    sw 16, 1
    mov y, 16

    mov p, 2

build_primes_outer:
    mulu i, r, p, p
    jnz build_primes_final, r

    geu a, i, x
    jnz build_primes_final, a

build_primes_inner:
    shl m, i, 3
    sw m, -1

    add i, i, p

    geu a, i, x
    jz build_primes_inner, a

build_primes_next:
    inc p
    shl m, p, 3
    lw a, m
    jnz build_primes_next, a

    sw y, p
    mov y, m
    sw y, 1

    jmp build_primes_outer

build_primes_final:
    inc p
    geu a, p, x
    jnz build_primes_ret, a

    shl m, p, 3
    lw a, m
    jnz build_primes_final, a

    sw y, p
    mov y, m
    sw y, 1

    jmp build_primes_final

build_primes_ret:
    ret

# Input: q
# Output: a
is_prime:
    shl m, q, 3
    lw a, m
    neq a, a, -1
    ret a

```
> 2 votes

---
Tags: golf-cpu, fewest-operations
---


# Question
Title: Probability of something happening at least n out of m times
Write a program or function, that given a success probability *p*, a number *n* and a number of trials *m* returns the chance of **at least** *n* successes out of *m* trials.

Your answer must be precise to at least 5 digits after the decimal.

Test cases:

```
 0.1, 10, 100 -> 0.54871
 0.2, 10, 100 -> 0.99767
 0.5, 13,  20 -> 0.13159
 0.5,  4,   4 -> 0.06250
0.45, 50, 100 -> 0.18273
 0.4, 50, 100 -> 0.02710
   1,  1,   2 -> 1.00000
   1,  2,   1 -> 0.00000
   0,  0,   1 -> 1.00000
   0,  0,   0 -> 1.00000
   0,  1,   1 -> 0.00000
   1,  1,   0 -> 0.00000

```

# Answer
# Jelly, ~~15~~ 14 bytes

```
2ṗ’S<¥ÐḟCạ⁵P€S

```

Reads **m**, **n** and **p** (in that order) as command-line arguments. Try it online!

Note that this approach requires **O(2m)** time and memory, so it isn't *quite* efficient enough for the test cases where **m = 100**. On my machine, the test case **(m, n, p) = (20, 13, 0.5)** takes roughly 100 seconds. It requires too much memory for the online interpreter.

### How it works

```
2ṗ              Cartesian product; yield all vectors of {1, 2}^n.
  ’             Decrement, yielding all vectors of {0, 1}^n.
      Ðḟ        Filter; keep elements for which the link to the left yields False.
     ¥          Combine the two links to the left into a dyadic chain.
   S              Sum, counting the number of ones.
    <             Compare the count with n.
        C       Complement; map z to 1 - z.
         ạ⁵     Compute the absolute difference with p.
           P€   Compute the product of each list.
             S  Compute the sum of all products.

```
> 3 votes

# Answer
## Mathematica, 29 bytes

```
BetaRegularized[#3,#,1+#2-#]&

```

Takes input in the order `n,m,p`. Mathematica is so good, it even golfs your code for you:

`BetaRegularized` is the regularised incomplete beta function.
> 9 votes

# Answer
# R, ~~32~~ 31 bytes

```
function(p,n,m)pbeta(p,m,1+n-m)

```

*edit - 1 byte switching to beta distribution (along the lines of @Sp3000 Mathematica Answer)*
> 6 votes

# Answer
## Python, 57 bytes

```
f=lambda p,n,m:m and(1-p)*f(p,n,m-1)+p*f(p,n-1,m-1)or n<1

```

The recursive formula for binomial coefficients, except the base case `m==0` indicates whether the remaining number of required successes `n` is nonnegative, with `True/False` for `1/0`. Because of its exponential recursion tree, this stalls on large inputs.
> 3 votes

# Answer
# Haskell, 73 bytes

```
g x=product[1..x];f p n m=sum[g m/g k/g(m-k)*p**k*(1-p)**(m-k)|k<-[n..m]]

```
> 3 votes

# Answer
# MATLAB, ~~78~~ 71 bytes

Saved 7 bytes thanks to Luis Mendo!

```
@(m,k,p)sum(arrayfun(@(t)prod((1:m)./[1:t 1:m-t])*p^t*(1-p)^(m-t),k:m))

ans(100,10,0.1)
0.5487

```

The arrayfun function is no fun, but I haven't found a way to get rid of it...
> 3 votes

# Answer
# Pyth, 26 bytes

```
AQJEsm**.cHd^Jd^-1J-HdrGhH

```

Try it online!

Uses standard cumulative binomial distribution.
> 1 votes

# Answer
# Pyth, 20 bytes

```
JEKEcsmgsm<O0QKJCGCG

```

Try it online!

Note: CG is a very large number which the interpreter cannot handle. Therefore, the number of trials have been lowered to ^T3 which is one thousand. Therefore, the link produces an inaccurate result.

Uses pure probabilistic approach.
> 1 votes

# Answer
## JavaScript (ES7), 82 bytes

```
(p,n,m)=>[...Array(++m)].reduce((r,_,i)=>r+(b=!i||b*m/i)*p**i*(1-p)**--m*(i>=n),0)

```

Saved 1 byte by using `reduce`! Explanation:

```
(p,n,m)=>               Parameters
 [...Array(++m)].       m+1 terms
  reduce((r,_,i)=>r+    Sum
   (b=!i||b*m/i)*       Binomial coefficient
   p**i*(1-p)**--m*     Probability
   (i>=n),              Ignore first n terms
   0)

```
> 1 votes

# Answer
# MATL, 23 bytes

```
y2$:Xni5M^1IG-lG7M-^**s

```

Inputs are in the order `m`, `n`, `p`.

**Try it online!**

This does a direct computation summing the terms from `n` to `m` of the binomial probability (mass) function.
> 1 votes

# Answer
# Octave, 26 bytes

```
@(p,n,m)1-binocdf(n-1,m,p)

```

This is an anonymous function. To use it, assign it to a variable.

**Try it here**.
> 1 votes

# Answer
# Jelly, ~~18~~ 17 bytes

```
⁵C*ạ×⁵*¥×c@
R’çSC

```

Reads **n**, **m** and **p** (in that order) as command-line arguments. Try it online!
> 1 votes

# Answer
# TI-Basic, 17 bytes

Precise to 10 decimals, could be adjusted anywhere from 0-14 decimals with more code.

```
Prompt P,N,M:1-binomcdf(M,P,N-1

```
> 0 votes

# Answer
## Haskell, 54 bytes

```
(p%n)m|m<1=sum[1|n<1]|d<-m-1=(1-p)*(p%n)d+p*(p%(n-1))d

```

Defines a function `(%)`. Call it like `(%) 0.4 2 3`.
> 0 votes

# Answer
# Mathematica, 48 bytes

```
Sum[s^k(1-s)^(#3-k)#3~Binomial~k,{k,##2}]/.s->#&

```

Uses the binomial distribution probability formula to calculate the chance of *k* successes for *k* from *n* to *m*. Handles the edge cases by using a symbolic sum where *s* is a symbolic variable for the probability that is later replaced with the actual value *p*. (Since *s*0 = 1 but 00 is indeterminate.)
> 0 votes

---
Tags: code-golf, math, probability-theory
---


title: Build a triangle without any triangles

text:
# Question
Title: Build a triangle without any triangles
As a little kid, I liked to play with these toys a lot:

They probably intended for these to be used for art, but I always used them for math! Fractals, patterns, etc. One time, I was given this challenge:

> Build a triangle without using any of the green triangle tiles.

This challenge stumped me for the longest time, until I stumbled upon a really beautiful and simple way to do it with just 3 trapezoids:

```
  /\
 /_/\
/__\_\

```

Now, take this triangle, and rotate it:

```
______
\ \__/
 \/ /
  \/

```

Using these two triangles, we can construct larger triangles out of them. Here is a triangle of height 2:

```
     /\
    /_/\
   /__\_\
  /\ \__/\
 /_/\/ /_/\
/__\_\/__\_\

```

And here are triangles of height 3-7:

```
#3
        /\
       /_/\
      /__\_\
     /\ \__/\
    /_/\/ /_/\
   /__\_\/__\_\
  /\ \__/\ \__/\
 /_/\/ /_/\/ /_/\
/__\_\/__\_\/__\_\

#4
           /\
          /_/\
         /__\_\
        /\ \__/\
       /_/\/ /_/\
      /__\_\/__\_\
     /\ \__/\ \__/\
    /_/\/ /_/\/ /_/\
   /__\_\/__\_\/__\_\
  /\ \__/\ \__/\ \__/\
 /_/\/ /_/\/ /_/\/ /_/\
/__\_\/__\_\/__\_\/__\_\

#5
              /\
             /_/\
            /__\_\
           /\ \__/\
          /_/\/ /_/\
         /__\_\/__\_\
        /\ \__/\ \__/\
       /_/\/ /_/\/ /_/\
      /__\_\/__\_\/__\_\
     /\ \__/\ \__/\ \__/\
    /_/\/ /_/\/ /_/\/ /_/\
   /__\_\/__\_\/__\_\/__\_\
  /\ \__/\ \__/\ \__/\ \__/\
 /_/\/ /_/\/ /_/\/ /_/\/ /_/\
/__\_\/__\_\/__\_\/__\_\/__\_\

#6
                 /\
                /_/\
               /__\_\
              /\ \__/\
             /_/\/ /_/\
            /__\_\/__\_\
           /\ \__/\ \__/\
          /_/\/ /_/\/ /_/\
         /__\_\/__\_\/__\_\
        /\ \__/\ \__/\ \__/\
       /_/\/ /_/\/ /_/\/ /_/\
      /__\_\/__\_\/__\_\/__\_\
     /\ \__/\ \__/\ \__/\ \__/\
    /_/\/ /_/\/ /_/\/ /_/\/ /_/\
   /__\_\/__\_\/__\_\/__\_\/__\_\
  /\ \__/\ \__/\ \__/\ \__/\ \__/\
 /_/\/ /_/\/ /_/\/ /_/\/ /_/\/ /_/\
/__\_\/__\_\/__\_\/__\_\/__\_\/__\_\

#7
                    /\
                   /_/\
                  /__\_\
                 /\ \__/\
                /_/\/ /_/\
               /__\_\/__\_\
              /\ \__/\ \__/\
             /_/\/ /_/\/ /_/\
            /__\_\/__\_\/__\_\
           /\ \__/\ \__/\ \__/\
          /_/\/ /_/\/ /_/\/ /_/\
         /__\_\/__\_\/__\_\/__\_\
        /\ \__/\ \__/\ \__/\ \__/\
       /_/\/ /_/\/ /_/\/ /_/\/ /_/\
      /__\_\/__\_\/__\_\/__\_\/__\_\
     /\ \__/\ \__/\ \__/\ \__/\ \__/\
    /_/\/ /_/\/ /_/\/ /_/\/ /_/\/ /_/\
   /__\_\/__\_\/__\_\/__\_\/__\_\/__\_\
  /\ \__/\ \__/\ \__/\ \__/\ \__/\ \__/\
 /_/\/ /_/\/ /_/\/ /_/\/ /_/\/ /_/\/ /_/\
/__\_\/__\_\/__\_\/__\_\/__\_\/__\_\/__\_\

```

# The Challenge

Write a program or function that takes a number *n* and prints a triangle-less triangle of height *n*. Trailing spaces on each line is acceptable, and up to one trailing or leading newline is also acceptable. IO can be in any reasonable format. The input is guarenteed to be a positive integer, so you don't have to worry about negative numbers, decimals, non-numbers etc.

Shortest answer in bytes wins!

# Answer
> 15 votes
# CJam, 47

```
ri_"/__\_\/_/\/ /\ \__"6/f**eeW%{_S.*s\~,\-<N}/

```

**Explanation:**

```
ri_       read the input, convert to integer and duplicate
"…"       push that string, containing the repeating pattern
           (3 lines in reverse order, concatenated)
6/        split into (3) lines of 6 characters
f*        multiply (repeat) each line n times
*         repeat the array of 3 lines n times
           at this point we have an array of 3*n strings with 6*n characters each
ee        enumerate the array (obtaining an array of [index string] pairs)
W%        reverse the array
           (so the lines are in correct order and indices in reverse order)
{…}/      for each [index string] pair
  _       duplicate the pair
  S.*     vectorized-multiply with " "
           this effectively replaces the index with a string of <index> spaces
  s       convert the pair to string, effectively concatenating the spaces
           with the string
  \       swap with the other copy of the [index string] pair
  ~,      dump the index and string on the stack and get the string length
  \-      subtract the index from it - this is the desired line length
  <       cut the concatenated string to that length
  N       add a newline

```

Try it online

# Answer
> 17 votes
# Ruby, 79

```
->n{1.upto(n*=3){|i|puts (' '*(n-i)).ljust(n+i,'/__\_\/\ \__/_/\/ '[i%3*6,6])}}

```

A. (-4 bytes, `-1` `+1`) changed from 0-indexed (`.times`) to 1-indexed (`1.upto`)

B. (-5 bytes) changed from array of three 6-char strings to selection of 6-char substring of 18-char string.

C. (-1 byte) `m=n*3` -\> `n*=3`

D. (-5 bytes) reduced all five double backslashes to single backslashes (partly made possible by reordering of string required for point A)

# Ruby, 94

```
->n{(m=n*3).times{|i|puts (' '*(m-i-1)).ljust(m+i+1,[ '/\\ \\__','/_/\\/ ','/__\\_\\'][i%3])}}

```

**explanation**

The basic unit is a 3x6 diamond as follows (last character on each row duplicated for clarity:)

```
    /\ \__/
   /_/\/ /
  /__\_\/

```

All we need to do is display a suitable window of this pattern. Ruby's `ljust` allows you to pad with any string, not just spaces. Normally `ljust` would be used to pad a string of printable characters by adding spaces at the end, but here we use it in reverse: to pad a string of spaces by adding printable characters at the end.

**ungolfed in test program**

```
f=->n{
  (m=n*3).times{|i|                  #for each line of the triangle
    puts (' '*(m-i-1)).              #print m-i-1 spaces,
      ljust(m+i+1,[ '/\\ \\__',      #left justified and padded to total length m+i+1
                   '/_/\\/ ',        #by one of these three strings
                  '/__\\_\\'][i%3])
  }
}

f[gets.to_i]

```

# Answer
> 9 votes
# Retina, ~~150~~ ~~122~~ 118 bytes

The output to this challenge looks awesome, by the way!

Input is in unary. The output contains a trailing linefeed. The code uses ISO 8859-1 encoding. Note the trailing space on the penultimate line.

```
(?=_\\¶.*1)
_\/__\
(?=/_/\\¶.*1)
/_/\/
(^|__)(?=/\\¶.*1)
$1/\ \__
ms}`(.*1*)1
/\¶/_/\¶/__\_\¶$1
m`^(?=(.*¶)*.)
$#1$*

```

**Try it online**

### Explanation

If you want a more in-depth explanation, comment or message me in chat.

```
(?=_\\¶.*1)                     # Matches the start of the 3rd line of every triangle
/__\_\                          #   and prepends another layer if needed
(?=/_/\\¶.*1)                   # 2nd line of each triangle
/_/\/
(^|__)(?=/\\¶.*1)               # 1st line of each triangle
$1/\ \__
ms}`(.*1*)1                 # This and above in a multi-single-line loop.
/\¶/_/\¶/__\_\¶$1               #   This stage adds a flattened triangle on top
m`^(?=(.*¶)*.)                  # Prepend a space for every line following -1
$#1$*

```

Thanks to Martin for golfing 32 bytes off.

# Answer
> 8 votes
#Tarmo's ascii printing language, 46 bytes.

```
1  /\| /_/\|/__\_\2 \__|/ 0n{n-a-1{~}1a{2#1}$}

```

Just by looking to such odd programming languages like CJam, it's makes me bit dizzy how complex, unnatural and cryptic language can be, that I wanted to "boldly go where no man has gone before", and invent my own language. As a result I've created my own language for ascii patterns printing.

Basic idea is that you can define first patten and then printing - using same kind of character '1' or '2' or whatever number - you can define your own print pattern.

Once pattern is defined (Starts from number till number end) - next numbers will execute pattern printing.

For example

```
1  /\| /_/\|/__\_\01

```

Outputs like this:

```
  /\
 /_/\
/__\_\

```

Will define pattern 1 and then print it right away. Pattern is defined everything separated with '|' character. 0 at the end - acts like pattern termination.

Special characters like '$' are reserved as line-feed, and '~' is reserved for spacing - half - of specific pattern.

```
1  /\| /_/\|/__\_\01$~11$~1~11

```

Will outputs text like this:

```
  /\
 /_/\
/__\_\
     /\
    /_/\
   /__\_\
        /\
       /_/\
      /__\_\

```

Next goes for-loops. That one needs to be easily visible - so I've retained {} brackets for for-loops, but variable names are auto-named - so first bracket will use 'a' variable, second 'b' and so on. Iteration will go always from 0 to specific number - and that number is defined before {} brackets.

'n' is reserved variable for whole function input.

So code:

```
1  /\| /_/\|/__\_\0n{1$}

```

Will outputs ( With n == 4 ):

```
  /\
 /_/\
/__\_\
  /\
 /_/\
/__\_\
  /\
 /_/\
/__\_\
  /\
 /_/\
/__\_\

```

And '#' is special modifier for trim lead whitespace.

And finally whole solution:

DrawPatterns.cs:

```
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.CSharp;

class DrawPatterns
{
//Command line parameters - for example like this: "1  /\| /_/\|/__\_\2 \__|/ 0n{n-a-1{~}1a{2#1}$}" 3
    static Dictionary<char, String[]> patterns = new Dictionary<char,string[]>();

    static string Tabs(int n)
    {
        if( n < 0 ) n = 0;

        String r = "";

        for( int i = 0; i < n ; i++ )
            r += "    ";

        return r;
    }

    static int[] left = new int[10];
    static int top = Console.CursorTop;
    static int lastTop = Console.CursorTop;

    static public void DoPrint(char c, char modifier = ' ')
    {
        if (c == '$')
        {
            for (int i = 0; i < left.Length; i++)
                left[i] = 0;
            top = lastTop + 1;
            return;
        }

        if (!patterns.ContainsKey(c))
            return;

        if (modifier == '½' || modifier == '~')
        {
            int maxSize = patterns[c].Select(x => x.Length).Max();
            for( int i = 0; i < left.Length; i++ )
                left[i] += maxSize / 2;
            return;
        }

        int iLine = 0;
        foreach (var l in patterns[c])
        {
            Console.SetCursorPosition(left[iLine], top + iLine);
            if( top + iLine > lastTop )
                lastTop = top + iLine;

            String s = l;
            if (modifier == '#')
                s = s.TrimStart(' ');

            Console.WriteLine(s);
            left[iLine] += s.Length;
            iLine++;
        }
    }

    static void Main(string[] _args)
    {
        List<String> args = _args.ToList();
        String todo = "";
        String code = "";
        char nextVar = 'a';
        String lf = "\r\n";
        int align = 1;
        char lastModifier = ' ';
        int nextArg = 1;
        Dictionary<String, String> argValues = new Dictionary<string,string>();
        bool bDebug = false;

        if (args.Count != 0 && args[0].ToLower() == "-d")
        {
            bDebug = true;
            args.RemoveAt(0);
        }

        if (args.Count == 0)
        {
            Console.WriteLine("Usage: DrawPatterns.cs [options] \"script\" <arguments to script>");
            Console.WriteLine("[options] allowed:");
            Console.WriteLine("-d - debug");
            return;
        }

        String prog = args[0];

        for( int i = 0; i < prog.Length; i++ )
        {
            char c = prog[i];

            // Define pattern.
            if (c >= '0' && c <= '9' && !patterns.ContainsKey(c))
            {
                String p = Regex.Match(prog.Substring(i + 1), "[^0-9]*").Groups[0].Value;
                patterns[c] = p.Split('|');
                i += p.Length;
                if( prog[i + 1] == '0' ) i++;
                continue;
            }

            String procRemain = prog.Substring(i);
            // modifier specified, but pattern number is not provided - use first pattern.
            if( lastModifier != ' ' && ( c < '0' || c > '9' ) )
            {
                code += Tabs(align);
                code += "print('1' , '" + lastModifier + "');" + lf;
                lastModifier = ' ';
            }

            switch ( c )
            {
                case '{':
                    code += Tabs(align);
                    code += "for ( int " + nextVar + " = 0; " + nextVar + " < " + todo + " ; " + nextVar + "++ )" + lf;

                    //  Check for all variable names if they can be used in program.
                    foreach ( var m in Regex.Matches(todo, "[a-zA-Z_][a-zA-Z0-9_]*", RegexOptions.Singleline) )
                    {
                        String varName = m.ToString();

                        if( varName.Length == 1 && varName[0] <= nextVar )
                            // Already declared as a loop.
                            continue;

                        if( argValues.ContainsKey(varName ) )
                            continue;

                        if( nextArg >= args.Count )
                        {
                            Console.WriteLine("Insufficient parameters provided to script - argument '" + varName + "' value is needed");
                            return;
                        }

                        argValues[varName] = args[nextArg];
                        nextArg++;
                    }

                    code += Tabs(align);
                    code += "{" + lf;
                    nextVar++;
                    todo = "";
                    align++;
                    break;

                case '}':
                    align--;
                    code += Tabs(align);
                    code += "}" + lf;
                    break;

                default:
                    if (((c >= '0' && c <= '9') || c == '<' || c == '$') && todo == "")
                    {
                        code += Tabs(align);
                        code += "print('" + c + "' , '" + lastModifier + "');" + lf;
                        lastModifier = ' ';
                        continue;
                    }

                    if (c == '½' || c == '~' || c == '#')
                    {
                        lastModifier = c;
                        continue;
                    }

                    if( c == '\r' || c == '\n' )
                        continue;

                    todo += c;
                    break;
            }

        } //for

        String code2 = "";
        code2 += "using System;" + lf;
        code2 += "public class ExecClass { static void Exec( Action<char, char> print";

        object[] invokeArgs = new object[ argValues.Count+1];
        invokeArgs[0] = new Action<char, char>(DoPrint);
        int iValueIndex = 1;

        foreach ( var kv in argValues )
        {
            code2 += ",";
            code2 += "int " + kv.Key;
            invokeArgs[iValueIndex] = Int32.Parse(kv.Value);
            iValueIndex++;
        }

        code2 += ") {" + lf;
        code2 += code;
        code2 += "} };";

        if( bDebug )
        {
            int line = 1;
            String lineNumberedCode =Regex.Replace(code2, "^(.*)$",
                delegate(Match m) { return (line++).ToString("d2") + ": " + m.Value; },
                RegexOptions.Multiline
            );
            Console.WriteLine(lineNumberedCode);
            Console.WriteLine();
            Console.WriteLine();
        }

        left[0] = Console.CursorLeft;
        for( int i = 1; i < left.Length; i++ )
            left[i] = left[0];
        top = Console.CursorTop;

        try
        {
            var compileResult = new CSharpCodeProvider().CompileAssemblyFromSource( new CompilerParameters() { GenerateExecutable = false, GenerateInMemory = true }, code2);
            if (compileResult.Errors.HasErrors)
            {
                foreach (CompilerError ce in compileResult.Errors)
                {
                    if (ce.IsWarning) continue;
                    Console.WriteLine("{0}({1},{2}: error {3}: {4}", ce.FileName, ce.Line, ce.Column, ce.ErrorNumber, ce.ErrorText);
                }
                return;
            }

            var method = compileResult.CompiledAssembly.GetType("ExecClass").GetMethod("Exec", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
            method.Invoke(null, invokeArgs);

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        Console.SetCursorPosition(1, lastTop);
        Console.WriteLine();
        Console.WriteLine();
    } //Main
}

```

With command line arguments like this: -d "1 /| /*/|/\___\2 _*|/ 0n{n-a-1{½}1a{2#1}$}" 3

Will outputs this:

```
01: using System;
02: public class ExecClass { static void Exec( Action<char, char> print,int n) {
03:     for ( int a = 0; a < n ; a++ )
04:     {
05:         for ( int b = 0; b < n-a-1 ; b++ )
06:         {
07:             print('1' , '~');
08:         }
09:         print('1' , ' ');
10:         for ( int c = 0; c < a ; c++ )
11:         {
12:             print('2' , ' ');
13:             print('1' , '#');
14:         }
15:         print('$' , ' ');
16:     }
17: } };

        /\
       /_/\
      /__\_\
     /\ \__/\
    /_/\/ /_/\
   /__\_\/__\_\
  /\ \__/\ \__/\
 /_/\/ /_/\/ /_/\
/__\_\/__\_\/__\_\

```

# Answer
> 5 votes
## JavaScript (ES6), 119 bytes

```
n=>`,/\\ \\__,/_/\\/ ,/__\\_\\`[r=`repeat`](n).split`,`.map((s,i)=>` `[r](n*3-i)+s[r](n).slice(0,i*2)).slice(1).join`\n`

```

Where `\n` represents the literal newline character. If a leading line with `n*3` spaces and a newline is acceptable then the `.slice(1)` can be removed for a saving of 9 bytes.

# Answer
> 3 votes
## Python 2, 118 bytes

```
def f(n,s=["/\\ \\__","/_/\\/ ","/__\\_\\"]):
 print'\n'.join(map(lambda x:' '*(n*3-x)+(n*s[x%3])[:x*2+2],range(n*3)))

```

Similar approach to Level River St's Ruby answer.

Try it online

# Answer
> 2 votes
## Python 2, 142 bytes

```
def f(n,m):return f(n-1,m+3)+[' '*(m+x)+(y*n)[x*2:]for x,y in((2,' \\__/\\'),(1,'/ /_/\\'),(0,'/__\\_\\'))]if n else[]
print '\n'.join(f(n,0))

```

The principle is very similar to other answers: take three repeated strings and then layer them in such a way that you only need to trim some of them to get the triangle, then pad them on the left.

# Answer
> 2 votes
# C++, 395 Bytes

First time code golf with a glorious size of 395 bytes in C++. In my case, it feels a little like a contest for obfuscation : D

```
#include <iostream>
#include <cstring>
#define A for (int k=0;k<((s-(i+1))*3+(2-j));k++) cout<<" ";
using namespace std; string t[3]={"/\\","/_/\\","/__\\_\\"};string r[2]={" \\__","/ "};int tr=3;int main(int,char**argv){int s=atoi(argv[1]);for(int i=0;i<s;i++){for(int j=0;j<tr;j++){A for(int l=1;l<=2*(i+1)-1;l++){if((l%2)==0&&(j<2)){cout<<r[j];}else if ((l%2)==1)cout<<t[j];}A cout<<endl;}}}

```

# Answer
> 0 votes
# Pyth, 66 bytes

```
jmj+L**3-Qhd\ [+*2;j" \\__"*Jhd]"/\\"+;j"/ "*J]"/_/\\"*J"/__\\_\\"

```

Try it online!

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


title: Interpret DOGO!

text:
# Question
Title: Interpret DOGO!
# Interpret DOGO

DOGO is a lesser known programming language. While the original DOGO (a joke language from a Usenet post) has never been implemented, a language resembling it has been created. The commands for the language are:

```
+===========+================================================================+
|  Command  |                          Description                           |
+===========+================================================================+
| SIT       | If the value of the current memory cell is 0, jump to STAY.    |
+-----------+----------------------------------------------------------------+
| STAY      | If the value of the current memory cell is not 0, jump to SIT. |
+-----------+----------------------------------------------------------------+
| ROLL-OVER | Select the next operation from the operation list.             |
+-----------+----------------------------------------------------------------+
| HEEL      | Execute the currently selected operation.                      |
+-----------+----------------------------------------------------------------+

```

The operations are:

```
+========+=======================================================+====+
| Number |                      Description                      | BF |
+========+=======================================================+====+
|      0 | Increment current memory cell.                        | +  |
+--------+-------------------------------------------------------+----+
|      1 | Decrement current memory cell.                        | -  |
+--------+-------------------------------------------------------+----+
|      2 | Move to next memory cell.                             | >  |
+--------+-------------------------------------------------------+----+
|      3 | Move to previous memory cell.                         | <  |
+--------+-------------------------------------------------------+----+
|      4 | Input a byte and store it in the current memory cell. | ,  |
+--------+-------------------------------------------------------+----+
|      5 | Output the current memory cell as ASCII.              | .  |
+--------+-------------------------------------------------------+----+

```

## Examples

Hello World:

```
roll-over roll-over heel roll-over roll-over roll-over roll-over heel heel heel
heel heel heel heel heel heel sit roll-over roll-over roll-over heel roll-over
roll-over roll-over heel heel heel heel heel heel heel heel roll-over roll-over
heel roll-over roll-over roll-over roll-over roll-over heel roll-over roll-over
roll-over roll-over roll-over stay roll-over roll-over roll-over heel roll-over
roll-over heel roll-over roll-over roll-over heel roll-over roll-over roll-over
roll-over heel heel heel heel heel heel heel sit roll-over roll-over roll-over
heel roll-over roll-over roll-over heel heel heel heel roll-over roll-over heel
roll-over roll-over roll-over roll-over roll-over heel roll-over roll-over
roll-over roll-over roll-over stay roll-over roll-over roll-over heel roll-over
roll-over roll-over heel roll-over roll-over roll-over roll-over roll-over heel
roll-over heel heel heel heel heel heel heel roll-over roll-over roll-over
roll-over roll-over heel heel roll-over heel heel heel roll-over roll-over
roll-over roll-over roll-over heel roll-over roll-over roll-over heel heel heel
roll-over roll-over roll-over roll-over heel heel heel heel heel heel heel heel
sit roll-over roll-over roll-over heel roll-over roll-over roll-over heel heel
heel heel roll-over roll-over heel roll-over roll-over roll-over roll-over
roll-over heel roll-over roll-over roll-over roll-over roll-over stay roll-over
roll-over roll-over heel roll-over roll-over heel roll-over roll-over roll-over
heel heel heel roll-over roll-over roll-over roll-over heel heel heel heel heel
heel heel heel heel heel sit roll-over roll-over roll-over heel roll-over
roll-over roll-over heel heel heel heel heel heel heel heel heel roll-over
roll-over heel roll-over roll-over roll-over roll-over roll-over heel roll-over
roll-over roll-over roll-over roll-over stay roll-over roll-over roll-over heel
roll-over roll-over roll-over roll-over heel heel heel roll-over roll-over
roll-over roll-over heel roll-over roll-over roll-over roll-over heel heel heel
heel roll-over roll-over heel roll-over heel heel heel roll-over roll-over
roll-over roll-over roll-over heel roll-over roll-over heel heel heel heel heel
heel roll-over roll-over roll-over roll-over heel roll-over roll-over heel heel
heel heel heel heel heel heel roll-over roll-over roll-over roll-over heel
roll-over roll-over roll-over heel heel roll-over roll-over roll-over roll-over
heel roll-over roll-over roll-over roll-over roll-over heel

```

99 bottles of beer

## Rules

* Each submission should be either a full program or function. If it is a function, it must be runnable by only needing to add the function call to the bottom of the program. Anything else (e.g. headers in C), must be included.
* If it is possible, please provide a link to an online site where your code can be tested.
* Your program cannot write anything to `STDERR` (or something similar).
* You can take input from `STDIN` (or the closest alternative in your language), or as an argument.
* Standard loopholes are forbidden.

## Scoring

Programs are scored according to *bytes*. The default character set is UTF-8, if you are using a different one, please specify.

That aside, this is , and the lowest byte count will be deemed the winner!

## Submissions

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

## Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

```
/* Configuration */

var QUESTION_ID = 79350; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/<a/.test(lang)) lang = jQuery(lang).text();

    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang > b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
```

```
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
```

**Update:**

Sorry for not clarifying the `sit` and `stay` commands very well. They are, as @user6245072 said, like `[` and `]` in BF.

**Update 2:**

To clarify @KennyLau's questions:

* The default operation is `0`.
* Memory consists of 8-bit cells.
* Cells wrap on overflow/underflow.
* Input is required for operation 4.

# Answer
# Ruby, 287 bytes

Runs on an infinite tape in both directions. DOGO input is a file on the command line. If there is no command line argument, a DOGO program will still work if passed in as STDIN, unless it uses operation `3` (get a byte from STDIN) in which case I have no idea. At any rate, file input is best.

Assumes no other text other than the four commands and whitespace exist in the program file.

Hello World Demonstration

```
i=k=o=0;m={}
c=$<.read.upcase.split.map{|e|%w{SIT STAY ROLL-OVER HEEL}.index e}.join
(m[k]||=0
e=c[i].to_i
e>2?o>4?$><<m[k].chr:
o>3?m[k]=STDIN.getc.ord:
o>1?k+=o>2?-1:1:
m[k]=o<1?-~m[k]%256:~-m[k]%256:
e>1?o=-~o%6:
e>0?m[k]>0?i=c.rindex(?0,i):0:
m[k]<1?i=c.index(?1,i):0
i+=1)while c[i]

```
> 1 votes

# Answer
# Python 3, ~~388~~ ~~398~~ ~~373~~ 371 bytes

Assumes 256 memory cells. Just a straightforward implementation, easily beatable, probably can be golfed more. Try it on repl.it.

Thanks to @EasterlyIrk for having me realize that Python 3 is much shorter that Python 2.

EDIT: Realized I only accounted for over/underflow while printing, not in actual value.

Thanks to @KevinLau-notKenney for saving 25 (!) bytes with list multiplication and inversion operator tricks

EDIT: -3 bytes by putting 256 into a variable, -4 messing with operators, +8 making sure it is lowercase

```
def p(s):
 b=256
 l,m=[w[-1]for w in s.lower().split()],[0]*b
 i=p=x=0
 while x<len(l):
  c=l[x]
  if'm'>c:
   if 1>i:m[p]=-~m[p]%b
   if 1==i:m[p]=~-m[p]%b
   if 2==i:p=-~p%b
   if 3==i:p=~-p%b
   if 4==i:m[p]=ord(input()[0])
   if 4<i:print(chr(m[p]),end="")
  if'r'==c:i=-~i%6
  if't'==c and m[p]<1:x+=l[:x].index('y')
  if'x'<c and m[p]>0:x-=l[x::-1].index('t')
  x+=1

```
> 2 votes

---
Tags: code-golf, interpreter
---


title: Building a Bridge

text:
# Question
Title: Building a Bridge
Your task is to build a bridge to connect two cliffs given an input `d`, the distance apart. `d` will always be even

However, the bridge needs columns to hold it up. Each column can hold a max of 6 spaces on each side.

For this example:

```
________                        ________
        |                      |
   A    |                      |   B

        |----------------------|
                d = 22

```

The bridge for `d = 20`should look like this with two columns. Columns do not count in d.

```
_____|__________|_____
12345|1234554321|12345
     |          |

```

**Rules:**

1. Must have enough columns to stand up.
2. Must have minimum number of columns needed to stand up.
3. Must be symmetrical
4. Lowest amount of Bytes Wins

Examples: (#s are only to help you count spaces. Should not be included in your output)

d = 10

```
_____|_____
12345|12345
     |

```

d = 32

```
_____|___________|___________|_____
12345|12345654321|           |
     |           |           |

```

d = 8

```
____|____
1234|1234
    |

```

d = 4

```
__|__
12|34
  |

```

d = 22

```
_____|____________|_____
12345|123456654321|
     |            |

```

or

```
______|__________|______
123456|1234554321|123456
      |          |

```

# Answer
## JavaScript (ES6), 92 bytes

```
d=>[..."_  "].map(c=>(s=c+c[r='repeat'](n%6))+'|'+(c[r](12)+'|')[r](n/6)+s,n=d-1>>1).join`\n`

```

Where `\n` represents the literal newline character. If `d` can be odd, it takes me 128 bytes:

```
d=>[..."_  "].map(c=>[...Array(d+1)].map((_,i)=>(d&1?i&&d-i&&(i>m)+5+i-m:((d-1)%24>11)*6+i-m)%12?'':'|',m=d>>1).join(c)).join`\n`

```
> 4 votes

# Answer
# Ruby, 108 bytes

Probably can be golfed down a lot more. Greedy algorithm.

```
->d{s='',k=6
(s+=?_*[d,k].min+(d>k/2??|:'');d-=k;k=12)while d>0
s=s.chomp(?|)+s.reverse+$/
s+s.tr(?_,' ')*2}

```
> 0 votes

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


title: Tiling by substitution

text:
# Question
Title: Tiling by substitution
**EDIT:** The incorrect A rhomb substitution has been fixed. Apologies to anoyone who had started working on a solution.

Consider the following substitutions, where the substituted rhomb(us) is scaled up and shown in red:

**EDIT:** Note the anchor points (circle) created where a corner of each new rhomb touches the substituted rhomb. Also note the substitution's anchor point (black circle).

**A rhomb (144°, 36°)**

... becomes ...

**B rhomb (72°, 108°)**

... becomes ...

Each substitution is made up of some combination of A rhombs and B rhombs, on which the same substitutions can be performed.

A tiling can be created by repeating the substitutions n times.

After n=2 substitutions of A rhomb:

**EDIT:** The substitution is oriented by aligning the rhomb's anchor point with the substitution's anchor point

**In the fewest bytes of code (given input n\>=0) draw the tiling after n substitutions, where n=0 is A rhomb**

---

*Notes:*

* *The red lines and anchor points shouldn't be included, they only illustrate the substitution.*
* *In each substitution the tiling is scaled up so the rhombs have a constant size.*
* *Any rotation is optional.*
* *Graphical choices (colour, dimensions, cropping etc.) are optional if not exploited for loopholes.*

# Answer
> 3 votes
# Java, 881 bytes

```
import java.awt.image.BufferedImage;import static java.lang.Math.*;class J{BufferedImage o=new BufferedImage(999,999,1);java.awt.Graphics g=o.getGraphics();double v=2.5132,w=1.2566,p=PI,s=(p-v)/2,u=(p+w)/2;public static void main(String[]v){new J(Integer.parseInt(v[0]));}J(int i){d(609,391,v,p/4+s,500,i);try{javax.imageio.ImageIO.write(o,"png",new java.io.File("a.png"));}catch(Exception e){}}void d(int x,int y,double o,double q,double l,int r){int m=(int)(2*l*sin((p-o)/2)),a=(int)(x+cos(q)*l),b=(int)(y+sin(q)*l),c=(int)(x+cos(q+o/2)*m),d=(int)(y+sin(q+o/2)*m),e=(int)(x+cos(q+o)*l),f=(int)(y+sin(q+o)*l);if(r-->0){double n=l/(2*sin((v)/2));if(o>w){d(x,y,v,q-s,n,r);d(c,d,v,q+p+s,n,r);d(a,b,w,q+u,n,r);}else{d(x,y,w,q-s,n,r);d(c,d,w,q+p+s,n,r);d(e,f,w,q-p/2,n,r);d(a,b,v,q+p/2-s-s,n,r);}}else{g.drawLine(x,y,a,b);g.drawLine(a,b,c,d);g.drawLine(x,y,e,f);g.drawLine(c,d,e,f);}}}

```

### Ungolfed

```
import java.awt.image.BufferedImage;

import static java.lang.Math.*;

class Q79373 {
    BufferedImage image = new BufferedImage(999, 999, 1);
    java.awt.Graphics graphics = image.getGraphics();
    double aRad = 2.5132, bRad = 1.2566, pi = PI, aAcuteHalf = (pi - aRad) / 2, bRadHalfPi = (pi + bRad) / 2;

    public static void main(String[] v) {
        new Q79373(Integer.parseInt(v[0]));
    }

    Q79373(int i) {
        draw(609, 391, aRad, pi / 4 + aAcuteHalf, 500, i);
        try {
            javax.imageio.ImageIO.write(image, "png", new java.io.File("a.png"));
        } catch (Exception e) {
        }
    }

    void draw(int x, int y, double rad, double rot, double length, int recDepth) {
        int
                height = (int) (2 * length * sin((pi - rad) / 2)),
                a = (int) (x + cos(rot) * length),
                b = (int) (y + sin(rot) * length),
                c = (int) (x + cos(rot + rad / 2) * height),
                d = (int) (y + sin(rot + rad / 2) * height),
                e = (int) (x + cos(rot + rad) * length),
                f = (int) (y + sin(rot + rad) * length);

        if (recDepth-- > 0) {
            double lengthNew = length / (2 * sin((aRad) / 2));
            if (rad > bRad) {
                draw(x, y, aRad, rot - aAcuteHalf, lengthNew, recDepth);
                draw(c, d, aRad, rot + pi + aAcuteHalf, lengthNew, recDepth);
                draw(a, b, bRad, rot + bRadHalfPi, lengthNew, recDepth);
            } else {
                draw(x, y, bRad, rot - aAcuteHalf, lengthNew, recDepth);
                draw(c, d, bRad, rot + pi + aAcuteHalf, lengthNew, recDepth);
                draw(e, f, bRad, rot - pi / 2, lengthNew, recDepth);
                draw(a, b, aRad, rot + pi / 2 - aAcuteHalf - aAcuteHalf, lengthNew, recDepth);
            }
        } else {
            graphics.drawLine(x, y, a, b);
            graphics.drawLine(a, b, c, d);
            graphics.drawLine(x, y, e, f);
            graphics.drawLine(c, d, e, f);
        }
    }
}

```

### Notes

* The results arent 100% acurate thanks to integer precision. I used integers for the coordinates because `Graphics::drawLine` only takes integers as arguments, and I would've ended up with way more integer casts than I have now.
* I'll probably golf a bit more later, still not optimal.

### Results

```
Full image filled

```

```
Recursion 1

```

```
Recursion 2

```

```
Recursion 3

```

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