title: ASCII Dandelions

text:
# Question
Title: ASCII Dandelions
These are ASCII dandelions:

```
   \|/      \ /          |
   /|\       |    \|/    |
    |        |     |   _\|/_
    |        |     |    /|\

```

ASCII dandelions have three parameters: Length of the stem (positive number between 1 and 256, number of seeds (positive number between 0 and 7), and orientation (^ or v). The above dandelions have for length, seeds and orientation, (3,5,^), (3,2,^), (2,3,^) and (3,7,v) respectively.

Seeds are filled in in the following order (flipped upside down for head-down dandelions), illustrated on a dandelion with length 2:

```
seeds:  0    1    2    3    4    5     6      7

             |   \ /  \|/  \ /  \|/  _\ /_  _\|/_
        |    |    |    |   /|\  /|\   /|\    /|\
        |    |    |    |    |    |     |      |

```

## The Challenge:

Write a program/function which when given an ASCII dandelion as input, returns its length, seed count, and orientation formatted similarly to the above examples and when given parameters in that format returns an ASCII dandelion with those parameters. You can ignore the parenthesis and assume the input/output will be a number, a comma, a number, a comma, and either `^` or `v`. You may substitute other characters for `^`/`v` so long as they can still be easily interpreted as 'up'/'down' (for example, `u`/`d`). You need not distinguish between dandelions that look the same, such as (2,1,^) and (3,0,^) or (2,1,^) and (2,1,v). Given the ASCII art, either set of parameters would be an acceptable output, and both sets of parameters can give the same ASCII art.

This is , so shortest code in bytes wins.

---

An example program in C# (not even slightly golfed):

```
    string Dandelion(string s)
    {
        if (s.Contains(','))
        {
            //got parameters as input
            string[] p = s.Split(',');
            //depth and width (number of seeds)
            int d = int.Parse(p[0]);
            int w = int.Parse(p[1]);
            //draw stem
            string art = "  |";
            while (d > 2)
            {
                d--;
                art += "\n  |";
            }
            //draw head
            string uhead = (w % 2 == 1 ? "|" : " ");
            string dhead = uhead;
            if (w > 1)
            {
                uhead = "\\" + uhead + "/";
                dhead = "/" + dhead + "\\";
                if (w > 5)
                {
                    uhead = "_" + uhead + "_\n /|\\";
                    dhead = "_\\|/_\n " + dhead;
                }
                else if (w > 3)
                {
                    uhead = " " + uhead + " \n /|\\";
                    dhead = " \\|/ \n " + dhead;
                }
                else
                {
                    uhead = " " + uhead + " \n  |";
                    dhead = "  |\n " + dhead;
                }
            }
            else
            {
                uhead = "  " + uhead + "\n  |";
                dhead = "  |\n  " + dhead;
            }
            //add head to body
            if (p[2] == "^")
            {
                return uhead + "\n" + art;
            }
            return art + "\n" + dhead;
        }
        else
        {
            //ASCII input
            string[] p = s.Split('\n');
            int l = p.Length - 1;
            int offset = 0;
            //find first non-' ' character in art
            while (p[0][offset] == ' ')
            {
                offset++;
            }
            int w = 0;
            if (p[0][offset] == '|')
            {
                //if '|', either head-down or no head.
                if (offset == 0 || p[l][offset - 1] == ' ')
                {
                    //if no space for a head to the left or no head at the bottom, no head.
                    return l.ToString() + ",1,^";
                }
                //head must have at least size 2, or else indistinguishable from no head case
                w = 6;
                if (p[l][offset] == '|')
                {
                    //odd sized head
                    w = 7;
                }
                if (offset == 1 || p[l - 1][offset - 2] == ' ')
                {
                    //not size 6 or 7
                    w -= 2;
                    if (p[l - 1][offset - 1] == ' ')
                    {
                        //not size 4 or 5
                        w -= 2;
                    }
                }
                return l.ToString() + "," + w.ToString() + ",v";
            }
            else if (p[0][offset] == '\\')
            {
                //head at least size 2 and not 6/7, or indistinguishable from no head.
                w = 4;
                if (p[0][offset + 1] == '|')
                {
                    w = 5;
                }
                if (p[1][offset] == ' ')
                {
                    w -= 2;
                }
            }
            else
            {
                w = 6;
                if (p[0][offset + 2] == '|')
                {
                    w = 7;
                }
            }
            return l.ToString() + "," + w.ToString() + ",^";
        }
    }

```

# Answer
# Bean, 321 bytes

Accepts input as single string in stdin without trailing newline. Parameters will be taken in the same manner, but formatted as

```
length (1-256)
orientation (u or d)
seeds (0-7)

```

The output parameters of the program when input is a dandelion will be in the same format as above.

Hexdump:

```
00000000 26 52 ca c1 20 5d d3 d0 80 d5 cd a0 5e 80 4c cc  &RÊÁ ]ÓÐ.ÕÍ ^.LÌ
00000010 a0 45 86 25 3e 88 4d a0 6b 80 4c a0 5e 80 23 60   E.%>.M k.L ^.#`
00000020 cd a0 63 80 43 cd a0 5f 80 50 84 a3 81 00 20 5e  Í c.CÍ _.P.£.. ^
00000030 d0 84 a3 81 01 4d a0 60 80 4a c1 4c a0 45 86 25  Ð.£..M `.JÁL E.%
00000040 3a d0 84 a3 81 02 4c a0 45 92 25 3a d0 84 a3 81  :Ð.£..L E.%:Ð.£.
00000050 03 20 60 a0 5f a3 81 04 cd a0 61 80 50 84 a3 81  . ` _£..Í a.P.£.
00000060 05 20 5e cf 52 cc a0 45 86 25 3c a3 81 06 23 81  . ^ÏRÌ E.%<£..#.
00000070 07 a0 61 cf 53 d0 80 a3 81 08 20 80 b5 4c a0 43  . aÏSÐ.£.. .µL C
00000080 8c 25 3a 00 52 a0 6b d3 50 80 a0 63 20 80 7e 20  .%:.R kÓP. c .~
00000090 63 20 80 7b 23 00 53 d0 80 c3 cc d0 80 a0 78 20  c .{#.SÐ.ÃÌÐ. x
000000a0 80 01 8c 25 3a d2 ce cc a0 5d 80 23 81 09 80 4c  ...%:ÒÎÌ ].#...L
000000b0 d0 84 a0 5e 25 3b 81 23 81 0a ce d3 50 80 a0 78  Ð. ^%;.#..ÎÓP. x
000000c0 20 80 7e 81 23 60 23 71 cc d2 cc d0 84 d0 84 a0   .~.#`#qÌÒÌÐ.Ð.
000000d0 78 25 3a 25 3a 81 23 81 0b cc a5 3d 8b 4c cc d0  x%:%:.#..Ì¥=.LÌÐ
000000e0 84 d0 84 a0 78 25 39 25 39 81 50 84 d0 84 a0 78  .Ð. x%9%9.P.Ð. x
000000f0 25 3a 25 39 8d 25 3b 4c cc d0 84 d0 84 a0 78 25  %:%9.%;LÌÐ.Ð. x%
00000100 39 25 3c 81 23 81 0b 8d 25 3b 8b 4c d0 84 d0 84  9%<.#...%;.LÐ.Ð.
00000110 a0 78 25 39 25 3b 81 23 81 0b 00 20 80 7b 23 81   x%9%;.#... .{#.
00000120 04 a0 df 20 a0 5c a0 7c a0 2f 0a a0 a0 5f af fc  . ß  \ | /.  _¯ü
00000130 5c a0 fc 20 8a a0 a0 fc a0 20 a0 a0 fc a0 20 7c  \ ü .  ü    ü  |
00000140 20
00000141

```

Equivalent JavaScript:

```
+a?                               // if input is parameters
  (
    b=(C>5)<<(o=b=="d"),          // encoding if seeds > 5 and if orientation is down
    g=[                           // storing dandelion as array of characters
      c=" _ "[b],                 // "_" if seeds > 5 and orientation is up, else " "
      " \\"[d=+(C>1)],            // "\" if seeds > 1, else " "
      " |"[C&1],                  // "|" if seeds is odd, else " "
      " /"[d],
      c,                          // "_" if seeds > 5 and orientation is up, else " "
      "\n",
      e="  _"[b],                 // "_" if seeds > 5 and orientation is down, else " "
      ...(                        // spread characters for .reverse() to be correct
        C>3?                      // if seeds > 3 "/|\" else " | "
          "/|\\":
          " | "
      ),
      e,                          // "_" if seeds > 5 and orientation is down, else " "
      ..."\n  |  ".repeat(A-1)    // repeat stem length - 1 times
    ],
    o?                            // if orientation is down, reverse
      g.reverse():
      g
  ).join(""):                     // join array of characters
  [                               // else if input is dandelion
    _.length-1,                   // length of stem is number of rows - 1
    a=="  |  "||b[2]!="|"?        // test orientation of dandelion
      _.reverse()&&"d":           // reverse rows if necessary and return "d" for down
      "u"                         // else return "u" for up
    ,
    (
      _[1][1]!=" "?               // if 1,1 is not " ", seeds is 4 or more
        4+(_[0][0]!=_[1][0])*2:   // if 0,0 or 1,0 is "_", seeds is 6 or 7
        (_[0][3]!=" ")*2          // if 0,3 is not " ", seeds is 2 or 3
    )+
    (_[0][2]!=" ")                // if 0,2 is not " ", seeds is odd
  ].join("\n")                    // join parameters with newline to match input format

```

Implicitly takes stdin as newline separated array of unformatted strings in `_` and implicitly outputs the parameters as a triplet. Test suite below and demo here:

```
const js = String.raw`
+a?                               // if input is parameters
  (
    b=(C>5)<<(o=b=="d"),          // encoding if seeds > 5 and if orientation is down
    g=[                           // storing dandelion as array of characters
      c=" _ "[b],                 // "_" if seeds > 5 and orientation is up, else " "
      " \\"[d=+(C>1)],            // "\" if seeds > 1, else " "
      " |"[C&1],                  // "|" if seeds is odd, else " "
      " /"[d],
      c,                          // "_" if seeds > 5 and orientation is up, else " "
      "\n",
      e="  _"[b],                 // "_" if seeds > 5 and orientation is down, else " "
      ...(                        // spread characters for .reverse() to be correct
        C>3?                      // if seeds > 3 "/|\" else " | "
          "/|\\":
          " | "
      ),
      e,                          // "_" if seeds > 5 and orientation is down, else " "
      ..."\n  |  ".repeat(A-1)    // repeat stem length - 1 times
    ],
    o?                            // if orientation is down, reverse
      g.reverse():
      g
  ).join(""):                     // join array of characters
  [                               // else if input is dandelion
    _.length-1,                   // length of stem is number of rows - 1
    a=="  |  "||b[2]!="|"?        // test orientation of dandelion
      _.reverse()&&"d":           // reverse rows if necessary and return "d" for down
      "u"                         // else return "u" for up
    ,
    (
      _[1][1]!=" "?               // if 1,1 is not " ", seeds is 4 or more
        4+(_[0][0]!=_[1][0])*2:   // if 0,0 or 1,0 is "_", seeds is 6 or 7
        (_[0][3]!=" ")*2          // if 0,3 is not " ", seeds is 2 or 3
    )+
    (_[0][2]!=" ")                // if 0,2 is not " ", seeds is odd
  ].join("\n")                    // join parameters with newline to match input format`;

// bean binary
const bin = bean.compile(js);

// program as function
const prog = bean.program(bin);

(document.body.onchange = function () {
  const parameters = stem.value + '\n' + orientation.value + '\n' + seeds.value;
  dandelion.textContent = prog(parameters);
  params.value = prog(dandelion.textContent);
})();
```

```
textarea {
  resize: none;
}
```

```
<script src="https://cdn.rawgit.com/patrickroberts/bean/master/dst/bean.min.js"></script>
<input id=stem type=number min=1 max=256 value=5>
<select id=orientation>
  <option value="u">u</option>
  <option value="d">d</option>
</select>
<input id=seeds type=number min=0 max=7 value=5>
<p>Dandelion (output from program given parameters)</p>
<pre id=dandelion></pre>
<p>Parameters (output from program given dandelion)</p>
<textarea id=params rows=3></textarea>
```
> 6 votes

# Answer
## Javascript ~~513~~ ~~391~~ ~~379~~ 355 bytes

Thanks to @Neil for helping golf off 134 bytes and @Kritixi Lithos for helping golf off 13 bytes This program assumes that any ASCII dandelions it is trying to identify have a line width of 5 for all lines of the string. ie: the stem is 2 spaces, the vertical line then another 2 spaces. (It can not classify dandelions it creates due to this issue)

```
(x,y,z)=>{a=Array(x+1).fill(1);if(x.length>1){a=x.split`
`;h=a.length-1;t=b=i=0;for(;i<(h>1)+1;i++)for(j=0;j<5;a[h-i][j++]!=' '&&b++)a[i][j]!=' '&&t++;return[h,(t>b?t:b)-(h>1),t>b?'^':'v']}z<'v'?(a[0]=y&4?y-2:y,a[1]=y&4?7:1):(a[x-1]=1+(y>4)*2+(y>4)*(y&2),a[x]=y&1+(y>2)*6);return a.map(n=>',  |, \\ /, \\|/,_\\ /_,_\\|/_, / \\, /|\\'.split`,`[n]).join`
`}

```

## How it Works

The function checks if the first argument it is given has a length \>1 (is a string). If the first argument is a string, it identifies the details of the ASCII dandelion.

To get the height of the dandelion, it splits the string around newline characters and counts the number of elements - 1. To get the number of seeds, it counts the number of non space characters on the top two and bottom two lines. if there are more characters in the top, it is declared to be upright and it uses the top count-1, otherwise it is declared to be upside down and uses the bottom count-1. If the total height is only 2, it determines uprightness by checking the counts of each line individually and choosing the side with more non space characters.

Otherwise, the function uses bitwise math in order to assign values from 0 to 7 according to the shape of each level of the dandelion to be drawn before converting each level into the appropriate string.

```
0:
1:  |
2: \\ /
3: \\|/
4:_\\ /_
5:_\\|/_
6: / \\
7: /|\\

```

Try it online
> 2 votes

# Answer
# Python 3.6, ~~476~~ ~~453~~ ~~448~~ ~~413~~ 394 bytes

**Solution** :

```
def h(i):
 l,s,o=i.split(",");s=int(s);z=["  |  "];q=(int(l)-1)*z;b,d,f,h,g,c,a=["  ","\\/"][s>1]+["  ","\\/"][s>3]+["| ","||"][s%2==1]+[" ","_"][s>5]
 if"d"==o:b,d,h,f,c,g=f,h,d,b,g,c
 r=[[a+b+c+d+a]+[" "+h+g+f+" "],z][s==0];return"\n".join([q+r,r+q]["u"==o])
def j(i):
 if","in i:print(h(i))
 else:[print(f"{m},{j},{k}")for m in range(257)for j in range(8)for k in"ud"if i==h(f"{m},{j},{k}")]

```

**Result**

```
>>> j("6,5,u")
 \|/
 /|\
  |
  |
  |
  |
  |
>>> j("5,2,d")
  |
  |
  |
  |
  |
 / \
>>> j("3,2,u")
 \ /
  |
  |
  |
>>> j("_\|/_\n /|\ \n  |  \n  |  \n  |  \n  |  \n  |  ")
6,7,u
>>> j(" \|/ \n /|\ \n  |  \n  |  \n  |  \n  |  ")
5,5,u
>>> j("  |  \n  |  \n  |  \n  |  \n  |  ")
4,1,u
4,1,d
5,0,u
5,0,d

```

**Unfold**

```
def g(i):
    def h(i):                       # this function draw dandelion
        l, s, o = i.split(",")      # split argument
        s = int(s)

        # Calcul the string in the flower for up case
        #   _\|/_   --> abcdb  --> when s=7 we have a=_ b=\ c=| d=/ h=/ g=| f=\
        #    /|\    -->  hgf
        a = "_" if s > 5 else " "
        b = "\\" if s > 1 else " "
        d = "/" if s > 1 else " "
        h = "/" if s > 3 else " "
        f = "\\" if s > 3 else " "
        c = "|" if s%2 == 1 else " "
        g = "|" if s%2 == 1 else "|"

        # Shuffle a bit if the position is down
        if"d"==o:
            b,d,h,f,c,g=f,h,d,b,g,c

        # treate the case to remove the line with ony white space
        if s==0:
            res=["  |  "]
        else:
            # assemble all piece of the flower
            res += [a+b+c+d+a]
            res += [" "+h+g+f+" "]

        # add stem up or down
        if o=="u":
            res = res + (int(l)-1) * ["  |  "]
        else:
            res = (int(l)-1) * ["  |  "] + res
        return "\n".join(res)

    if "," in i:
        print(h(i))
    else:
        # search in all flower posibility if we can recreate the input
        [print(m,j,k) for m in range(1, 257) for j in range(0, 8)for k in "ud"if i == h(f"{m},{j},{k}")]

```
> 1 votes

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


# Question
Title: Your Base to 1-2-3-Tribonacci to Binary back to Your Base
# Background

## The 1-2-3-Tribonacci Sequence

Imagine for a second that you could make a fibonacci sequence by replacing the standard iteration formula with the following:

Basically, instead of summing the last two to get the next, you sum the last three. This is the basis for the 1-2-3-Tribonacci sequence.

## Brown's Criterion

Brown's Criterion state that you may represent any integer value as a sum of members of a sequence provided that:

1.
2. For all `n` greater than 1,

## What this means for the challenge

You may describe any positive integer as a sum of members of the 1-2-3-Tribonacci sequence formed by the following initial conditions:

This is known as, for every value in this sequence, the ratio between terms is never greater than 2 (the ratio averages out at about 1.839).

## How to write in this numerical representation system

Let's say that you use a little-endian representation. Line up members of the sequence like so:

```
1  2  3  6 11 20 37 68

```

Then, you take your number to be represented (for our tests, let's say it's `63`) and find the values of the given 1-2-3-Tribonacci which sum to 63 **(using the largest values first!)**. If the number is part of the sum, put a 1 under it, 0 if not.

```
1  2  3  6 11 20 37 68
0  0  0  1  0  1  1  0

```

You may do this for any given integer - just verify that you use the largest values below your given input first!

# Definition (finally)

Write a program or function that will do the following given some positive integer input `n` (written in any standard base) between 1 and your language's maximum value:

1. Convert the value into the defined 1-2-3-Tribonacci's numerical representation.
2. Using this binary-like representation, and read it as if it were binary. This means that the digits stay the same, but what they mean changes.
3. Take this binary number and convert it into the base of the original number.
4. Output or return this new number.

However, as long as the output is valid, you needn't follow these steps. If you magically find some formula that is shorter (and mathematically equivalent), feel free to use it.

# Examples

Let the function `f` be the function described by the definition, and let `[]` represent steps taken (as little-endian, though it shouldn't matter) (you do not need to follow this process, this is just the process described):

```
>>> f(1)
[1]
[1]
[1]
1

>>> f(5)
[5]
[0, 1, 1]
[6]
6

>>> f(63)
[63]
[0, 0, 0, 1, 0, 1, 1]
[104]
104

```

# Answer
> 7 votes
## Javascript ~~117~~ 111 bytes

Thanks to @theonlygusti for helping golf off 5 bytes

```
x=>{r=0;a=[1,2,3];i=1;while(a[++i]<x)a[i+1]=a[i]+a[i-1]+a[i-2];for(;x;i--)if(x>=a[i]){r+=1<<i;x-=a[i]}return r}

```

## How It Works

First, the function generates all tribonacci numbers until it finds one greater than the input

```
a=[1,2,3];i=1;for(;a[++i]<x;)a[i+1]=a[i]+a[i-1]+a[i-2];

```

Next, it reverse searches the list of numbers. If a number is less than the input, it adds 2^(index of that number) to the return value and reduces the input by that number.

```
for(;x;i--)if(x>=a[i]){r+=1<<i;x-=a[i]}

```

Finally it returns the result.

Try it Online

# Answer
> 7 votes
# Python 2, ~~110~~ 102 bytes

-3 bytes thanks to Rod (neat trick for casting boolean `i` to an int with `+i` so the repr ``+i`` works)

```
n=input()
x=[3,2,1]
r=''
while x[0]<n:x=[sum(x[:3])]+x
for v in x:i=n>=v;n-=v*i;r+=`+i`
print int(r,2)

```

**Try it online!**

# Answer
> 7 votes
## JavaScript (ES6), ~~97~~ 93 bytes

Here, we are using `reduce()` on a recursive function. We assume that the output is 31-bit (which is the largest unsigned quantity that JS can easily work with for bitwise operations anyway).

```
n=>[...Array(x=31)].reduce(p=>(c=(F=k=>k<4?k:F(--k)+F(--k)+F(--k))(x--))>n?p:(n-=c,p|1<<x),0)

```

Performance wise, this is clearly not very efficient.

For the curious:

* The ratio between the number of calls to `F()` for N+1 `reduce()` iterations vs N iterations quickly converges towards the Tribonacci Constant (≈ 1.83929). Therefore, each additional bit in the output costs approximately twice as much time as the previous one.
* With 31 bits, the `F()` function is called a good 124 million times.

### Test

*NB:* This may take 1 or 2 seconds to complete.

```
let f =

n=>[...Array(x=31)].reduce(p=>(c=(F=k=>k<4?k:F(--k)+F(--k)+F(--k))(x--))>n?p:(n-=c,p|1<<x),0)

console.log(f(63))
```

# Answer
> 6 votes
# Mathematica, ~~78~~ 74 bytes

```
Fold[#+##&,#~NumberDecompose~Reverse@LinearRecurrence[{1,1,1},{1,2,3},#]]&

```

`LinearRecurrence[{1,1,1},{1,2,3},#]` generates a list, of length equal to the input, of the 1-2-3 tribonacci numbers. (The `{1,1,1}` represents the sum of the previous three terms, while `{1,2,3}` are the initial values.) Then `#~NumberDecompose~` finds the greediest way to write the input as a sum of elements of the list (this is the same function that would decompose a monetary amount into multiples of the available currencies, for example). Finally, `Fold[#+##&,...]` converts the resulting binary list into a (base-10) integer.

Previous submission:

```
Fold[#+##&,#~NumberDecompose~Reverse@Array[If[#<4,#,Tr[#0/@(#-Range@3)]]&,#]]&

```

As is often the case (though not above), this golfed version is super slow on inputs larger than 20 or so, because it generates (with non-optimized recursion) a list of tribs whose length is the input; replacing the final `#` by a more reasonable bound like `Round[2Log@#+1]` results in much better performance.

# Answer
> 5 votes
## Haskell, 95 bytes

```
(a!b)c=a:(b!c)(a+b+c)
e#(r,c)|c-e<0=(2*r,c)|1<2=(2*r+1,c-e)
f n=fst$foldr(#)(0,n)$take n$(1!2)3

```

Usage example: `f 63` -\> `104`. Try it online!.

How it works: `!` builds the 1-2-3-Tribonacci sequence. Given `1`, `2` and `3` as the start parameters, we take the first `n` elements of the sequence. Then we fold from the right function `#` which subtracts the next element `e` from `n` and sets the bit in the return value `r` if `e` is needed or lets the bit unset. Setting the bit is doubling `r` and adding `1`, letting it unset is just doubling.

# Answer
> 4 votes
# Jelly, 31 bytes

```
S=³
3RUµḣ3S;µ<³Ạµ¿µŒPÇÐfṀe@Ð€µḄ

```

**Try it online!**

I'm almost certain there is a MUCH shorter way to achieve this in Jelly.

### How?

```
S=³ - Link 1, compare sum to input: list
S   - sum
  ³ - 3rd command line argument which is 1st program argument.
 =  - equal?

3RUµḣ3S;µ<³Ạµ¿µŒPÇÐfṀe@Ð€µḄ - Main link: n
3RU                         - range(3) upended -> [3,2,1]
   µ    µ   µ¿              - while
         <³                 - less than input (vectorises)
           Ạ                - all?
    ḣ3S;                    -     head(3), sum, and concatenate
                                  [3,2,1] -> [6,3,2,1] -> [11,6,3,2,1] -> ...
              µ             - monadic chain separation, call the result x
               ŒP           - power set of x - e.g. for [6,3,2,1] -> [[],[6],[3],[2],[1],[6,3],[6,2],[6,1],[3,2],[3,1],[2,1],[6,3,2],[6,3,1],[6,2,1],[3,2,1],[6,3,2,1]]
                  Ðf        - filter keep
                 Ç          -     last link (1) as a monad (those that sum to the input)
                    Ṁ       - maximum (e.g. an input of 63 would yield [[37,20,6],[37,20,3,2,1]], the maximum of which is [37,20,6], the one with the largest numbers used)
                         µ  - monadic chain separation (to have x as the right argument below)
                     e@Ð€   - exists in with reversed arguments mapped over x (e.g. [37,20,6] with x = [68,37,20,11,6,3,2,1] yields [0,1,1,0,1,0,0,0])
                          Ḅ - convert from binary to integer.

```

# Answer
> 4 votes
# Perl 6, ~~93~~ 91 bytes

*-2 bytes thanks to b2gills*

```
{my@f=1,2,3,*+*+*...*>$^n;sum @f».&{$_~~any first *.sum==$n,@f.combinations}Z*(2 X**^∞)}

```

### How it works

* First, it generates the 1-2-3-Tribonacci sequence up to the first element larger than the input:

```
my @f = 1, 2, 3, *+*+* ... * > $^n;
```
* Based on that it finds the subset of the sequence which adds up to the input:

```
first *.sum==$n, @f.combinations
```
* Based on that it constructs a list of booleans specifying whether each element of the sequence is part of the sum:

```
@f».&{$_~~any ...}
```
* And finally it interprets that list of True=1, False=0 values as base 2 and returns it as a (base 10) number:

```
sum ... Z* (2 X** ^∞)
```

# Answer
> 3 votes
## JavaScript (ES6), ~~61~~ 60 bytes

```
n=>(g=(x,y,z)=>(n>x&&g(y,z,x+y+z)*2)+!(n<x||![n-=x]))(1,2,3)

```

Calculates the 1-2-3-Tribonacci numbers until it reaches the original number, then as the recursion unwinds, tries to subtract each one in turn, doubling the result as it goes.

Edit: Saved 1 byte thanks to @Arnauld.

# Answer
> 2 votes
## Batch, ~~151~~ ~~148~~ 145 bytes

```
@set/ar=0,n=%1
@call:c 3 2 1
@echo %r%
@exit/b
:c
@set/as=%1+%2+%3
@if %n% gtr %3 call:c %s% %*
@set/ar*=2
@if %n% geq %3 set/an-=%3,r+=1

```

Port of my JavaScript answer. Edit: Saved 3 bytes by passing my subroutine arguments in reverse order and another 3 bytes by using individual `@`s on each line instead of `@echo off`.

# Answer
> 2 votes
# Jelly (fork), ~~17~~ 16 bytes

```
ḣ3S;µ¡
3RṚÇ³æFṪḄ

```

Saved 1 byte thanks to @Dennis who golfed it without even running it.

This relies on a fork of Jelly where I am disappointingly still working on implementing an efficient Frobenius solve atom. For those who are interested, I would like to match Mathematica's speed in `FrobeniusSolve` and luckily there is an explanation of their method in the paper "Making Change and Finding Repfigits: Balancing a Knapsack" by Daniel Lichtblau.

## Explanation

```
ḣ3S;µ¡  Helper link. Input: a list
    µ   Create monadic chain
ḣ3        Take the first 3 items
  S       Sum
   ;      Prepend to the list
     ¡  Repeat it n (initial argument from main) times

3RṚÇ³æFṪḄ  Main link. Input: integer n
3          The constant 3
 R         Range. Makes [1, 2, 3]
  Ṛ        Reverse. Makes [3, 2, 1]
   Ç       Call the helper link on that list.
           Generates the first (n+3) 123-Tribonacci values in reverse
    ³      Get n
     æF    Frobenius solve for n using the first n 123-Tribonacci values in reverse
       Ṫ   Tail. Take the last value. The results of Frobenius solve are ordered
           where the last result uses the least
        Ḅ  Unbinary. Convert digits from base 2 to base 10

```

# Answer
> 2 votes
# Jelly, ~~19~~ ~~18~~ 17 bytes

```
Ḣx3+
BÇL¡2ị
²Ç€»ċ

```

Try it online!

### Background

Instead of trying to convert an integer to 1,2,3-Tribonacci base, then from binary to integer, we'll do the opposite: convert integers to binary, then from 1,2,3-Trionacci base to integer, and return the highest one that matches the input. This is easily accomplished.

We'll exemplify the process for input **63**, in particular the step where **104** is tested. In binary, from most significant to least significant digit, **104** is equal to

```
 1  1  0  1  0  0  0
37 20 11  6  3  2  1

```

where the second row represents the positional values of those digits.

We can extend the 1,2,3-Tribonacci sequence to the right, observing that the added digits comply with the same recursive formula. For three mre digits, this gives

```
 1  1  0  1  0  0  0  0  0  0
37 20 11  6  3  2  1  0  1  0

```

Now, to compute the value of the base 1,2,3-Tribonacci number, we can make use of the recursive formula. Since each number is the sum of the three numbers to its right (in the table above), we can remove the first digit and add this to the first three digits of the remaining array. After **7** steps, which is equal to the number of binary digits of **104**, we rare left with only three digits.

```
 1  1  0  1  0  0  0  0  0  0
37 20 11  6  3  2  1  0  1  0

    2  1  2  0  0  0  0  0  0
   20 11  6  3  2  1  0  1  0

       3  4  2  0  0  0  0  0
      11  6  3  2  1  0  1  0

          7  5  3  0  0  0  0
          6  3  2  1  0  1  0

            12 10  7  0  0  0
             3  2  1  0  1  0

               22 19 12  0  0
                2  1  0  1  0

                  41 34 22  0
                   1  0  1  0

                     75 63 41
                      0  1  0

```

Now, since the first and last remaining digit both have positional value **0**, the result is the middle digit, i.e, **63**.

### How it works

```
²Ç€»ċ   Main link. Argument: n

²       Yield n². Since 1.839² = 3.381921 > 2, the range [1, ..., n²] will contain
        the answer. Better bounds, at the cost of additional bytes are possible.
 Ç€     Map the the second helper link over [1, ..., n²].
   »    Take the maximum of n and each result.
    ċ   Count the occurrences of n.

BÇL¡2ị  Second helper link. Left argument: k. Right argument: n

B       Convert k to binary. Let's call the result A.
  L     Length; count the number of binary digits. Let's call the result l.
 Ç ¡    Apply the first helper link l times to A.
    2ị  Retrieve the second element.

Ḣ×3+    First helper link. Argument: A (array)

Ḣ       Head; pop and yield the first element of A.
 x3     Repeat it thrice.
   +    Add the result, component by component, to the beheaded A.

```

# Answer
> 1 votes
# dc, ~~110~~ 102 bytes

```
?se1sa2sb3sc_1sf[laddSdlbdsalcdsb++sclf1+sfle>y]dsyx0sk[lk2lf^+skler-se]sr[Lddle!<rlf1-dsf0!>z]dszxlkp

```

Well, seems like great minds *do* think alike. Apparently, the algorithm I came up with to get around the limitations of `dc` is coincidentally the exact same one used in @LliwTelrac's answer. Interesting.

Try it online!

# Answer
> 1 votes
# Python 2, 93 bytes

```
n=input();y=k=n*n
while y>n:
 x=y=z=0;k-=1
 for t in bin(k):x+=t=='1';x,y,z=y+x,z+x,x
print k

```

This is a port of my Jelly answer.

Try it online!

# Answer
> 1 votes
# bash + BSD utilities (OS X, etc.), 53 bytes

```
jot $[2#$1**4]|egrep -v '[2-9]|11(1|$)'|sed $[2#$1]!d

```

# bash + GNU utilities (works under BSD also), 59 bytes

```
seq -f2o%.fp $[2#$1**2]|dc|egrep -v '11(1|$)'|sed $[2#$1]!d

```

Input and output in both the above are in binary.

---

Try out the GNU version at TIO. (The example linked to demonstrates input of 111111, which is 63 in binary, and output of 1101000, which is 104 in binary.)

I don't think TIO offers a BSD option, but if you have a Mac available, you can try them both out there. (The 59-byte program is *much* faster than the 53-byte program.)

---

Unfortunately, `seq` can't simply be dropped into the BSD solution in place of `jot`, since the output format for `seq` is different for outputs above 999999. (This starts being a problem for inputs around 32, since 32^4 \> 1000000.)

You can replace `jot` above with `seq -f%.f` to get this to work with GNU utilities, but for the same 59 bytes, you can use the GNU solution above, which is much faster.

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


# Question
Title: Find the submatrix with the smallest mean, 2.0
You're given a **n-by-m** matrix of integers, where **n,m \> 3**. Your task is to find the **3-by-3** sub-matrix that has the lowest mean, and output this value.

**Rules and clarifications:**

* The integers will be non-negative
* Optional input and output format
* The output must be accurate up to at least 2 decimal poins (if it's non-integer)
* The submatrices can be made up of arbitrary columns and rows

**Test cases:**

```
1   0   4   0   1   0
1   0   4   0   1   0
4   3   4   3   4   3
1   0   4   0   1   0

Minimum mean: 0   (We have chosen columns 2,4,6 and rows 1,2,4 (1-indexed)
-----------------------------
4    8    9    7
5   10    1    5
8    5    2    4
8    3    5   10
6    6    3    4

Minimum mean: 4.2222
-----------------------------
1   0   0   0   0
0   2   0   0   0
0   0   3   0   0
0   0   0   4   0
0   0   0   0   5

Minimum mean: 0.11111
-----------------------------
371   565   361   625   879   504   113   104
943   544   157   799   726   832   228   405
743   114   171   506   943   181   823   454
503   410   333   735   554   227   423   662
629   439   191   707    52   751   506   924

Minimum mean: 309.56

```

# Answer
## Mathematica, ~~77~~ 50 bytes

```
±x_:=x~Subsets~{3}
Min[Mean/@Mean/@±#&/@±#]&

```

is Mathematica's transposition operator (and is rendered as a superscript T in Mathematica).

This answer first defines a helper operator `±` which returns all 3-element subsets of a list, and then evaluates to an unnamed function which uses this operator to solve the problem.

This is done by first computing all 3-element subsets of the matrix's rows. Then for each such subset, we transpose it and compute *its* 3-element subset of rows. This gives us all possible 3x3 submatrices (although they are transposed). We then compute the mean on all of them and find the overall minimum.
> 9 votes

# Answer
# Jelly, ~~15~~ 12 bytes

```
œc3S€Zµ⁺FṂ÷9

```

Try it online!

# How it works

```
œc3S€Zµ⁺FṂ÷9  Main link. Argument: M (matrix)

œc3           Yield all combinations of 3 rows.
   S€         Map column-wise sum over the combinations.
     Z        Zip, transposing rows and columns.
      µ       Combine all links to the left into a chain.
       ⁺      Duplicate the chain, executing it twice.
        F     Flatten.
         Ṃ    Take the minimum.
          ÷9  Divide it by 9.

```
> 7 votes

# Answer
# 05AB1E, ~~21~~ 16 bytes

```
2Fvyæ3ùO})ø}˜9/W

```

Try it online!

**Explanation**

* For each row, get the sum of each ordered subset of size 3
* Transpose the resulting matrix
* For each row, get the sum of each ordered subset of size 3
* Flatten the resulting matrix
* Divide by 9
* Get the minimum
> 4 votes

# Answer
# Haskell, 90 bytes

```
import Data.List
t r=[a+b+c|[a,b,c]<-subsequences r]
s=(/9).minimum.(t=<<).transpose.map t

```

Try it online!
> 1 votes

# Answer
# Bean, 198 bytes

Hexdump:

```
00000000 bc 81 bd a0 65 40 a0 5d dd a0 68 50 80 a0 77 20  ¼.½ e@ ]Ý hP. w
00000010 80 01 dd a0 66 25 3b 52 cc cb c0 50 84 a0 5d 20  ..Ý f%;RÌËÀP. ]
00000020 66 87 4c cc a0 68 8b 20 66 8c 25 3b cd d0 84 a0  f.LÌ h. f.%;ÍÐ.
00000030 5d 20 66 80 4e a0 66 81 4c d3 a0 65 a0 5d a0 68  ] f.N f.LÓ e ] h
00000040 4c a0 66 8c 25 3a 8b 25 3a 50 84 a0 5d 20 66 bd  L f.%:.%:P. ] f½
00000050 a0 6e 43 a5 39 a5 3a a5 3b 00 bd a0 5f 43 cf 20   nC¥9¥:¥;.½ _CÏ
00000060 6e 00 3d a0 69 20 12 b6 a7 36 a7 26 4d a0 69 80  n.= i .¶§6§&M i.
00000070 53 d0 80 a0 1f 20 80 45 a0 69 53 d0 80 a0 6e 20  SÐ. . .E iSÐ. n
00000080 80 8b 40 a0 6f a0 75 4c a0 6f 8b 53 d0 80 a0 5f  ..@ o uL o.SÐ. _
00000090 20 80 8b 40 a0 6f a0 74 4c a0 6f 8b 50 84 d0 84   ..@ o tL o.P.Ð.
000000a0 a0 77 20 75 20 74 4c d3 a0 65 a0 5f 50 80 a0 43   w u tLÓ e _P. C
000000b0 20 80 01 81 25 3b 4c d3 a0 65 20 6e 81 25 3b 26   ...%;LÓ e n.%;&
000000c0 4c a0 69 8e 25 42                                L i.%B
000000c6

```

Equivalent JavaScript:

```
// indices array increment function
var i=(a,l=$.length,j=2)=>++a[j]>=l+j-2?a[j]=j&&i(a,l,j-1)+1:a[j],
// row indices
    r=[0,1,2],
// column indices
    c=[...r],
// minimum sum
    m=Infinity;
do{
  do{
// calculate sum of current row/column indices and keep minimum
    m=Math.min(m,
      (r.reduce((s,y)=>s+c.reduce((s,x)=>s+$[y][x])))
    )
// until column indices loop
  }while(i(c,A.length)!=2)
// until row indices loop
}while(i(r)!=2)
// output mean
m/9

```

### Try demo here
> 0 votes

---
Tags: code-golf, math, matrix
---


title: HRNG - Human Random Number Generator

text:
# Question
Title: HRNG - Human Random Number Generator
You know it: keyboard or mouse input is just too mainstream to create Random Numbers through human behavior.

Create the most unique (Pseudo)Random Number Generator that create its numbers through human behavior.

Web-API's are not restricted! Anyone should use the code provided, so any special hardware is restricted. (I think we can assume that everyone has a smartphone) The number should be a 256 bit number.

Example: use the Google Map's API to get current traffic to create the Random Number.

This is a , so most votes wins!

# Answer
## Mathematica on Mac OS X

```
Mod[Tr /@ IntegerDigits[
  Floor[2^15 AudioData@SystemDialogInput@"RecordSound"]
, 2], 2]

```

Opens up a dialog box that lets you record a sound snippet through the computer's microphone, then converts the resulting digital audio data to a list of bits (roughly 50,000 bits per second of audio). Generate random numbers through white noise, singing your favorite tune, exclaiming "Serenity now!", or just yelling at the top of your lungs!
> 8 votes

# Answer
# Python 3

```
import urllib.request
t=0
with urllib.request.urlopen("http://codegolf.stackexchange.com/questions/109658/hrng-human-random-number-generator#109658") as f:
    m = f.read().decode("utf8")
    for c in m:
        t+=ord(c)
print(t/len(m.split()))

```

This version takes each characters ordinals to take into account changing values such as votes.

Leaving the below in as it was my first attempt but as noted it is a little stale.

```
import urllib.request
with urllib.request.urlopen("http://codegolf.stackexchange.com/questions/109658/hrng-human-random-number-generator#109658") as f:
    m = f.read().decode("utf8")
print(len(m)/len(m.split()))

```

Takes this current page gets it's character count and word count divides and returns the number.

Not sure if it's great but first idea that came to mind.
> 2 votes

# Answer
# Bash

```
w|sha256sum|tr -d -

```

Outputs a hex-encoded 256 bit "random" number

> **w** displays information about the users currently on the machine, and their processes. The header shows, in this order, the current time, how long the system has been running, how many users are currently logged on, and the system load averages for the past 1, 5, and 15 minutes.

Try It Online !
> 2 votes

---
Tags: popularity-contest, random
---


title: Detect a Symmetric polynomial

text:
# Question
Title: Detect a Symmetric polynomial
A symmetric polynomial is a polynomial which is unchanged under permutation of its variables.

In other words, a polynomial `f(x,y)` is symmetric if and only if `f(x,y) = f(y,x)`; a polynomial `g(x,y,z)` is symmetric iff `g(x,y,z) = g(x,z,y) = g(y,x,z) = etc`.

For example, `x^2+2xy+y^2`, `xy` and `x^3+x^2y+xy^2+y^3` are symmetric polynomials, where `2x+y` and `x^2+y` are not.

---

# The challenge

You will be given a polynomial, and your program should output truthy/falsy values, depending on if the given polynomial is a symmetric polynomial.

The input format is allowed in two ways. A string, and an array, like `["x^2","2xy","y^2"]`, where the polynomial is the sum of each elements.

---

# Example

```
x^2+2xy+y^2 => true
xy => true
xy+yz+xz-3xyz => true
(x+y)(x-y) => false
2x+y => false
x^2+y => false
x+2y+3 => false

```

---

# Specs

The operation has orders, just like in normal math. the order is like this:

```
() => ^ => * => +-

```

rules apply.

All the characters in the alphabet (`a~z`) are accepted as variables, everything else are numbers.

The given polynomial will have 2 or more variables.

Multiplication does not require the * operator, You only need to detect juxtaposition. (detecting by juxtaposition is not neccessary, use the better option)

# Answer
# Maxima, 40 bytes

```
f(p):=listp(tpartpol(p,showratvars(p)));

```

Try It Online!

A function that takes a polynomial as input and returns true if it is symmetric else returns false
> 5 votes

# Answer
# Mathematica, 43 bytes

```
Last@SymmetricReduction[#,Variables@#]===0&

```

Unnamed function taking as input a polynomial in the given format (except that juxtaposed variables must be separated by a space) and returning `True` or `False`. `Variables@#` detects the variables appearing in the input (and thus the input can contain all kinds of weird variable names, not just single letters). `SymmetricReduction` returns an ordered pair of polynomials, where the first one is symmetric and the two sum to the original polynomial; therefore we can detect whether the input is symmetric by seeing whether the second polynomial is identically `0`.
> 8 votes

# Answer
# TI-Basic, 46 bytes

Basically, how this works is the polynomial is entered into a (two-byte) variable type that is dynamically evaluated. Then, we swap the X and Y values enough times to see if the function is symmetric.

```
Prompt u
For(I,0,8
rand->X
Ans->W
rand->Y
u->Z
Y->X
W->Y
If u=W
End
Ans=9

```
> 1 votes

---
Tags: code-golf, math, abstract-algebra, polynomials
---


title: Recreation of Piet Mondrian Composition

text:
# Question
Title: Recreation of Piet Mondrian Composition
Good Afternoon,

Your goal is to, in the least amount of source code bytes, recreate any of Piet Mondrian's 'Composition' paintings (for instance, Composition #10).

The recreation can either use the actual colors, or replace it with the appropriate colours from the Windows Default 16 Color Palette.

Your recreation can be outputted in PNG, BMP or NetPBM, either to a file or to STDOUT, or directly to the screen.

Your recreation must be a resolution of 512x512 or higher.

Your recreation must not access the internet. If your program requires data files, then their size will be added to the size of your source.

Your score will be the size of your source file in bytes.

Please state with your entry which painting you're recreating, and provide a link to the original and a picture of your recreation.

Good Luck.

# Answer
> 14 votes
# Tikz, 175 bytes

## Composition III in Black and White, 175 bytes

```
\documentclass[tikz]{standalone}\begin{document}\tikz{\def\b{;\draw[line width=}\def\a{)--(}\clip(1,1\a1,5\a5,5\a5,1)\b2mm](0,4\a6,4\a6,3\a4,3)\b1mm](4,0\a4,5);}\end{document}

```

Verify it in the Blogosphere

This is perhaps one of Mondrian's most minimalistic works and I am surprised no one has found it yet. It is not however particularly interesting so I have included several other paintings in my answer.

### Explanation

There is a bit of a wrapper that is associated with every tikz answer. The wrapper is:

```
\documentclass[tikz]{standalone}\begin{document}\tikz{
}\end{document}

```

Once you get past the wrapper there are a few `\def` statements that save bytes but unfortunately obfuscate the code:

```
\def\b{;\draw[line width=}\def\a{)--(}

```

If we make all the proper substitutions our code comes out looking like:

```
\clip(1,1)--(1,5)--(5,5)--(5,1);
\draw[line width=2mm](0,4)--(6,4)--(6,3)--(4,3);
\draw[line width=1mm](4,0)--(4,5);

```

The first bit is a `\clip` and is very important, but we will skip over it for the time being.

Now we draw the first line on the blank canvas, This line is rather thick so we use `[line width=2mm]` to set the thickness to `2mm`:

```
\draw[line width=2mm](0,4)--(6,4)--(6,3)--(4,3);

```

This connects a couple of nodes and produces this shape:

Next we `\draw` a second stroke, however this stroke is thinner so we have to set the line thickness to `1mm`:

```
\draw[line width=1mm](4,0)--(4,5);

```

Now our painting looks like:

This is close to the original but not quite, so here is where the `\clip` comes into play. We use the `\clip` to remove all the extra lines from our canvas and set the canvas to the correct size. With the canvas resized we get the image:

---

## Composition With Yellow Patch, 214 bytes

```
\documentclass[tikz]{standalone}\begin{document}\tikz[line width=2mm]{\clip(1,1)rectangle(7,7);\draw(0,8)rectangle(4,3.5)rectangle(6.5,1.2)rectangle(4,0);\draw[fill=yellow](6.5,3.5)rectangle(8,2.5);}\end{document}

```

Evaluate it in CyberSpace

*Explanation to come*

---

## Composition II in Blue and Yellow, 225 bytes

```
\documentclass[tikz]{standalone}\begin{document}\tikz[line width=2mm]{\clip(1,1)rectangle(7,10);\draw(8,9)rectangle(3,6)rectangle(0,0);\draw[fill=yellow](0,0)rectangle(3,2);\draw[fill=blue](0,11)rectangle(3,9);}\end{document}

```

Assess it over the Webbernetz!

*Explanation to come*

---

## Composition B (No. 2) in Red, 232 bytes

```
\documentclass[tikz]{standalone}\begin{document}\tikz[line width=2mm]{\clip(1,1)rectangle(10,13);\draw[line width=1mm](1.2,5)--(1.2,9);\draw[fill=red](0,14)rectangle(5,9);\draw(0,9)rectangle(11,5)(7,0)rectangle(5,14);}\end{document}

```

Attempt it within the Internet!

### Explanation

First here is the code with line breaks inserted to make it more readable:

```
\documentclass[tikz]{standalone}
\begin{document}
\tikz[line width=2mm]{
\clip(1,1)rectangle(10,13);
\draw[line width=1mm](1.2,5)--(1.2,9);
\draw[fill=red](0,14)rectangle(5,9);
\draw(0,9)rectangle(11,5)(7,0)rectangle(5,14);
}
\end{document}

```

The first command of interest is

```
\draw[fill=red](0,14)rectangle(5,9);

```

This draws a red rectangle with a black outline. For the upper left hand corner of the painting.

We then draw two more rectangles with white interiors and black outlines to create the grid pattern on the painting

```
\draw(0,9)rectangle(11,5)(7,0)rectangle(5,14);

```

We then draw in a thin line

```
\draw[line width=1mm](1.2,5)--(1.2,9);

```

And crop the image to the proper size

```
\clip(1,1)rectangle(10,13);

```

---

## Composition II in Red, Blue and Yellow, 251 bytes

```
\documentclass[tikz]{standalone}\begin{document}\tikz[line width=1mm]{\clip(1,1)rectangle(9,9);\draw[fill=yellow](8.5,6)--(0,6)--(8.5,6)--(8.5,2)rectangle(10,0);\draw[fill=red](3,3)rectangle(10,10);\draw[fill=blue](0,0)rectangle(3,3);}\end{document}

```

Test it upon the World Wide Web!

### Explanation

First I will insert some line breaks to make my code readable

```
\documentclass[tikz]{standalone}
\begin{document}
\tikz[line width=1mm]{
\clip(1,1)rectangle(9,9);
\draw[fill=yellow](8.5,6)--(0,6)--(8.5,6)--(8.5,2)rectangle(10,0);
\draw[fill=red](3,3)rectangle(10,10);
\draw[fill=blue](0,0)rectangle(3,3);
}
\end{document}

```

The first line of importance is:

```
\draw[fill=yellow](8.5,6)--(0,6)--(8.5,6)--(8.5,2)rectangle(10,0);

```

This draws the following shape:

This strange shape is the yellow rectangle in the lower right corner and the two lines that are no the edge of a colored rectangle. Next we insert the red square and cover up the extra lines made by the last shape:

```
\draw[fill=red](3,3)rectangle(10,10);

```

This comes out looking like:

Now we insert our blue square:

```
\draw[fill=blue](0,0)rectangle(3,3);

```

Now all that is left is to crop out all the unnecessary parts of the image using a `\clip`

```
\clip(1,1)rectangle(10,10);

```

---

## Composition II, 308 bytes

```
\documentclass[tikz]{standalone}\begin{document}\tikz[line width=2mm]{\clip(1,1)rectangle(12.6,13);\draw(0,0)rectangle(10,4)rectangle(2,12)--(0,12);\draw[fill=red](10,1.6)rectangle(14,0);\draw[fill=yellow](6,12)rectangle(10,14);\draw[fill=blue](0,4)rectangle(2,8);\fill(10,10)rectangle(14,14);}\end{document}

```

Check it out on the *Information-Super-Highway*

*Explanation to come*

# Answer
> 12 votes
# Mathematica ~~202~~ 287 bytes.

**Just For Fun! 330 bytes: Mondrian with "Boogie Woogie" in Its Title**

```
Column[{"Boogie Woogie", Grid[{{"",i["",b->Red],\[SpanFromLeft]},{"",\[SpanFromAbove],\[SpanFromBoth]},{i["",b->Blue],"",""},{\[SpanFromAbove],\[SpanFromAbove],i["",b -> Yellow]}},Dividers->{{2->t@5,3->t@6},{2->t@9,3->t@7,4->t@6}},ItemSize->{{1->3,2->9,3->1},{1->6,2->6,3->2,4->2}}]},Alignment->Center]

```

---

**Actual Submission \[287 bytes\]**

`\[SpanFromLeft]` and similar expressions take up roughly 85 bytes. In mathematica each such expression has its dedicated one character symbol.

```
t=Thickness;b=Background;i=Item;
Grid[{{"",i["",b->Red], \[SpanFromLeft]},{"",\[SpanFromAbove],\[SpanFromBoth]},{i["",b->Blue],"",""},{\[SpanFromAbove],\[SpanFromAbove],i[ "",b->Yellow]}},
Dividers->{{2->t@5, 3->t@6},{2->t@9,3->t@7,4->t@6}},ItemSize->{{1->3, 2->9, 3->1},
{1->6, 2->6, 3->2, 4->2}}]

```

Output on left; photo of Piet Mondrian, Red Blue Yellow Composition on right.

# Answer
> 11 votes
### Ruby, 112 (111) characters

Piet Mondrian - composition in B (No.II) with Red

```
b="0 "*9
w="2 "*9
puts"P3 609 771 2",["1 0 0 "*267,w*8+b*2+w*79,w*89].map{|x|(x+b*3+w*42+b*3+w*66)*249}*(b*2436)

```

my production on the left, the upscaled reference on the right.

The colors can be tweaked slightly - up to a precision of 1/9 - without loss of score by tweaking the max-value in PPM. I've chosen the "suitable Win16 color" approach. 8/9 white is probably closer to the canvas original color, but 9/9 is closer to the author's intention.

~~One character can be saved if we replace `"1 0 0 "` with `(w+b+b)` (#F00 red). I believe that counts as "close enough"~~

file ouptut version (not golfed)

```
File.open "tmp.ppm", ?w do |f|
    b="0 "
    w="2 "
    s=b*27+w*378+b*27+w*594
    f.puts"P3 609 771 2",["1 0 0 "*267,w*72+b*18+w*711,w*801].map{|x|(x+s)*249}*(b*21924)
end

```

# Answer
> 9 votes
# SmileBASIC, ~~2774~~ 1892 bytes

### Broadway Boogie Woogie

```
GCLS-920851D$="w$BȜąr:BȂąr7?Ƣǘy1SƑǘb<?ŵǘw-/ƶvyFMƮeb<<ŶIr:,ėǭy:Sėǘw-LŒƄw7;ėƎrkLćƄrBMĜey26ğ¸bKBē²y,Bć²w<Dđïw+DüïyDÒïw--çvyU8Òpw.1±syBM¨eb;<Iy28¥żrJNůbwN{ůr?@Ǣb3>Sǭw.Fb¤w24DrMF5¤w,7Nnr[75ny1X=e
FOR I=1TO 36G A(),A(),A(),A(),A()NEXT
D$=" w*+r6,r1+b<*w1+b/+b++r(+w*+w,Br )b+*b()w0,w=+b,,r5+b1+r ,w24-Ȃ  w  w#.r-#-Ǥ  w*+r4,b3+r6*w2+b,-r-,b++r*+b**r(*b(*r*+b<-w@+b -w ,r4+b1+b%-w,5-ǔ  w +r)+w?#-ƹǘ w +r%-b,#-ƭ +w *r +w/,b2,r1-b;-w7+b*.w5+r1+r +-ƒ> w +r'-b*#-ž *r+)w +r?+b:+b1-b2+w:+w*+w3-b4-r4-b6,w2+r--w3+b1+r )w52-ş  w*+r )w ,b>+r7+b :w -b,+r:+w*+w7,r 6w ,r7-r0.w/+bM+b1+b ,w24-ľ *w +r)+r *w5+r9,b7.w++w ,r.+w*+w6*b Dw *r06w -r5+b *w8+w +r1+b ,w *r(7-ü  w*+w )b +w*+r*+bD-rC/r7+b*+r5+bD-r,.b/.w.+b *w8+r +w1+b'+r,4-Ò  w*+b )w+*r+*w +b )w<0wX-w +r*+b /wd-w/.b/*w+-r 7w)+bC+r,3-p *w+)w +b*+w*+b )w@2wU*w+*w++wx-wQ-w.,bT+b,.-* +w +r++r5,w6+w %|üŭ w3+r1*w(+r0+r7*b (w )r3*w+*w,+r-*w +b5+r )w6+w.,r1+w *b*-w +b *w(,r()w ,r+*r :| ȋ+w7*b 1w4)w +r %|şǷ+r,*w)+w.*w*)w ?r -w+'|pǷ)w,)w +b*#| Ƿ+r/+b()w ?r -w+*w),r(*w *b +w *r +| Ǣ w+(w +b1*w(+r0+b7)b *w *r2)w +b *w,+r7+b5+r )w6+b/+b )w1,r7+b.*b9*w +b*8| Ǎ w3+w )b0*w +r4)w +r/+w**w**b +w6+w )r1*b3+w /|üň+b-*w1+w%*r(-w +r *w.+w')r (w5*| ň w3+w )r0*w +b )r5*b/+w3+w *r +w *r,+w9+r3+w-*b (w +r,+b2,w /r3+b0)r *b+-w+*r :| ĳ w3+b )w)*r 'w +b (w+)w *r1+b0*w.+r6+b )w0)w,)w +b4+w +b0)w'*r1*b))w+*b.*b1(w+*r ;| 3w +b )w*)b 'w +b.)r 'w )b0+r <b,+b6+b.,b=+r 3w ,b +w *b 6w *r);b)+b7+b 1w=9| Z w3+r (w.-w +b1+w +r0+r )w +r (w,+r6+b *w),r8+b?+bJ*w:)w+)w.*r1)w+*r 7| >+r )w6+r2*b1+r6*b1*w +b*(| ,
FOR Q=1TO 27S=A()T=A()R=A()L=A()FOR I=1TO L
R A(),89R A(),A()NEXT
NEXT
DEF A()RETURN-32+ASC(POP(D$))END
DEF R L,C
IF L THEN IF R-13THEN G C,L,11,T,S:T=T+L ELSE G C,11,L,T,S:S=S+L
END
DEF G C,H,W,Y,X
GFILL X,Y,X+W-1,Y+H-1,-1716698*(C>88)-2302505*(C==87)-6080725*(C==82)-14597488*(C<67)END

```

Each of the "lines" in the image is stored in this format:

```
x,y,direction,numberOfSegments,
yellowLength,nextColor,colorLength,
yellowLength,nextColor,colorLength,...

```

All the numbers are stored as `CHR$(number+32)`, colors are stored as one character; `w`,`y`,`r`, or `b`, and direction is stored as `|` or `-`

The extra rectangles are just stored as:

```
x,y,width,height,color,
x,y,width,height,color,...

```

In the same way.

# Answer
> 7 votes
# SVG - 455 ~~480~~ \- Mondrian Composition II in Red, Blue, and Yellow

If you can embed Javascript into SVG and make it dynamic, its a programming language. Ergo, this is a program. Turns out if an `x` or `y` coord is missing in SVG it defaults to 0. Also `red` is shorter than `#f00`!

```
<?xml version="1.0" encoding="utf-8"?><svg xmlns="http://www.w3.org/2000/svg"><rect x="145" fill="red" width="455" height="440"/><rect y="432" fill="#00F" width="150" height="168"/><rect x="550" y="517" fill="#FF0" width="50" height="83"/><rect x="140" width="16" height="600"/><rect y="430" width="600" height="16"/><rect y="180" width="140" height="25"/><rect x="550" y="430" width="15" height="170"/><rect x="550" y="515" width="50" height="16"/></svg>

```

Pretty Printed:

```
<?xml version="1.0" encoding="utf-8"?>
<svg xmlns="http://www.w3.org/2000/svg">
  <rect x="145" fill="red" width="455" height="440"/>
  <rect y="432" fill="#00F" width="150" height="168"/>
  <rect x="550" y="517" fill="#FF0" width="50" height="83"/>
  <rect x="140" width="16" height="600"/>
  <rect y="430" width="600" height="16"/>
  <rect y="180" width="140" height="25"/>
  <rect x="550" y="430" width="15" height="170"/>
  <rect x="550" y="515" width="50" height="16"/>
</svg>

```

# Answer
> 3 votes
# SmileBASIC, 67 bytes

```
GCLS-1GFILL 353,0,367,#R,0GFILL.,121,#R,156,0GFILL 367,266,#R,293,0

```

I picked an easy one: Composition III in Black and White

Luckily SB's graphics page is exactly 512x512 pixels, but it won't all fit on the 400x240 screen so I can't get a screenshot easily.

Explained:

```
GCLS -1 'fill screen with &HFFFFFFFF (white)
GFILL 353,0,367,511,0 'draw vertical line in &H00000000 (black)
GFILL 0,121,#R,156,0 'draw horizontal line
GFILL 367,266,#R,293,0 'draw small horizontal line

```

# Answer
> 3 votes
# Processing, ~~15,447~~ ~~15,441~~ 15,439 bytes

```
String i="data:image/jpeg;base64,[encoded data, 15360 characters]";PImage x=loadImage(i);void draw(){image(x);}

```

Brute force, and I haven't managed to find a way to remove the draw function.

It errors in the main processing engine, I think because it's too big of a b64. You can test it here.

JS fiddles does crop it though, to 100\*100px. My base64 works, but the online environment doesn't. :(

# Answer
> 2 votes
# Love2D, 4956 + 395 + 1 = 5351 bytes

```
f=io.open("d","rb")s=f:read("*a"):gsub("(.)(.)",function(a,b)return a:rep(b:byte())end)o=love.image.newImageData(512,512)c={{244,243,248},{173,24,0},{250,209,5},{30,64,164}}o:mapPixel(function(x,y)i=math.floor((x+math.floor(y/4)*512)/4)O=3-i%4 n=s:sub(math.floor(i/4)+1,math.floor(i/4)+1)if n and#n>0 then b=math.floor(n:byte()/(4^O))%4 else b=0 end return unpack(c[b+1])end)o:encode("png","o")

```

The Data file is stored HERE

**Output:**

**Original:**

## Explanation

```
f = io.open("d","rb")                                                   -- Open the image in raw format.
s = f:read("*a"):gsub("(.)(.)",function(a,b)return a:rep(b:byte())end)  -- And read it's contents.
o=love.image.newImageData(512,512)                                      -- Make the output image
c = {{244,243,248},{173,24,0},{250,209,5},{30,64,164}}                  -- Build the Pallet
o:mapPixel(function(x,y)                                                -- Fill the image, based on a function
    i = (x+y*512)                                   -- The position this pixel exists on the string, 0 indexed.
    O = 3-i%4                                       -- The offset. The byte stores 4 pixels, so this is the id among a group of 4.
    n = s:sub(math.floor(i/4)+1,math.floor(i/4)+1)  -- And this gets the byte itself.
    if n and #n > 0 then                            -- Sometimes this is null and I don't like it.
        b = math.floor(n:byte()/(4^O))%4            -- /4^offset % 4 gives us the value of the index on the pallet.
    else
        b = 0                                       -- Fallback plan.
    end
    return unpack(c[b+1])                           -- Set the pixel to the colour required.
end)
o:encode("png","o") -- Store it in Appdata as "o", which is a png file.

```

## The Encoder.

This is just the script I used to encode the image. Gif worked out more compressed, but I wasn't challenged to display a gif.

```
img = love.image.newImageData("mondrian.jpg")
-- white    0
-- blue     3
-- yellow   2
-- red      1

cols = {{244,243,248},{173,24,0},{250,209,5},{30,64,164}}

local s = ""
for y = 0, 511 do
    for x = 0, 511 do
        local r,g,b = img:getPixel(x,y)
        local n = 0
        local D = math.huge
        for k,v in pairs(cols) do
            local d = (v[1]-r)^2 + (v[2]-g)^2 + (v[3]-b)^2
            if d < D then
                n = k-1
                D = d
            end
        end
        s = s .. n
    end
end
-- Convert base 4 to base 256
-- How many digits do we need- Every 4 digits
encd = ""
for str in s:gmatch"...." do
    local n = str:sub(1,1) * 4^3 +
              str:sub(2,2) * 4^2 +
              str:sub(3,3) * 4^1 +
              str:sub(4,4) * 4^0
    encd = encd .. string.char(n)
end

f = io.open("stored.dat","wb")

smlr = ""
lst = ""
c = 0
for s in encd:gmatch"." do
    if s == lst then
        c = c + 1
        while c > 255 do
            smlr = smlr .. lst .. string.char(255)
            c = c - 255
        end
    else
        if c > 0 then
            smlr = smlr .. lst .. string.char(c)
        end
        lst = s
        c = 1
    end
end

f:write(smlr)

```

Mostly competing for the bounty. There are likely better ways to do this, but I thought it would be interesting to try to use a simple pallet and run length decoding.

EDIT: Input image was simplified, slightly less accurate, but a magnitude less bytes.

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


title: Reverse every word in a line in vim

text:
# Question
Title: Reverse every word in a line in vim
Your task is to build a vim script or provide a sequence of keystrokes that will operate on a single line of text with up to 140 printable ASCII characters (anywhere in a file, with the cursor starting anywhere in the line) and reverse every space-separated string in the sentence while keeping the strings in the same order.

For example, the input:

```
roF emos nosaer m'I gnisu a retcarahc-041 timil no siht noitseuq neve hguoht ti t'nseod evlovni .rettiwT RACECAR

```

should return:

```
For some reason I'm using a 140-character limit on this question even though it doesn't involve Twitter. RACECAR

```

The script with the fewest characters, or the sequence of the fewest keystrokes, to achieve this result is the winner.

# Answer
# 28 25 24 keystrokes

```
:se ri<CR>^qqct <C-r>"<Esc>f l@qq@q

```

Recursive macro, I assume that `Ctrl`-`r` counts as one keystroke.

The hardest part was to make sure the macro stays on the same line and does not destroy the rest of the file.
> 10 votes

# Answer
# 24 keystrokes

```
ma:s/ /\r/g
V'a:!rev
gvJ

```

I know this question is very old, but I love vimgolf so I couldn't *not* post an answer on one of the few vim-specific challenges on the site. Plus this solution is tied with Orlp's.

Just like Orlp said, the hardest part was making sure that the rest of the buffer was unmodified. If it weren't for that restriction, we could simply do:

```
:s/ /\r/g
!{rev
V}J

```

(19 keystrokes) but we need a little bit more to keep it buffer-safe. This assumes a unix environment.
> 4 votes

---
Tags: code-golf, vim
---


title: Prime Divisor Table

text:
# Question
Title: Prime Divisor Table
### Intro

Something I've played around with in recreational mathematics has been construction of a divisor table to visually compare/contrast the prime divisors of a set of numbers. The set of input numbers are across the top as column labels, the prime divisors are on the left as row labels, and a mark indicates where the two line up.

For example, for input `6, 9, 14, 22` a table similar to the following would be constructed:

```
    6  9 14 22
 2  *     *  *
 3  *  *
 7        *
11           *

```

This is because `6` has prime divisors of `2` and `3`, `9` has prime divisors of `3`, and so on.

### Construction

* The table is constructed such that the input numbers form column labels that are separated by spaces and in ascending order (you can assume they are pre-sorted), and the prime divisors are listed on the left in ascending order one per line forming the row labels.
* Note that leading spaces on the prime divisors and input numbers may be required if the numbers are different lengths, so that all columns are the same width and line up appropriately.
* Each divisor is represented by a single `*` (or other suitable ASCII character of your choosing, so long as the same character is used for all occurrences).
* Multiple divisors are ignored (e.g., `3 x 3 = 9` but there's only one `*` for that intersection).
* The `*` can be placed anywhere horizontally in the column, so long as it's unambiguous (I have all my examples with the `*` right-aligned).

### Input

* A list of positive integers in any convenient format, each `>1`.
* You can assume that the input is pre-sorted.
* The input is guaranteed to have only unique values.

### Output

The resulting ASCII art representation of the prime divisor table.

### Rules

* Leading or trailing newlines or whitespace are all optional, so long as the characters themselves line up correctly.
* If it's shorter to have a divider line separating the column/row headings from the tabular data, that's allowed, too.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so people can try out your code!
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

### Examples

```
6,9,14,22

    6  9 14 22
 2  *     *  *
 3  *  *
 7        *
11           *

2,3,5,7

  2 3 5 7
2 *
3   *
5     *
7       *

2,4,8,16,32

   2  4  8 16 32
2  *  *  *  *  *

75,99,151,153

     75  99 151 153
  3   *   *       *
  5   *
 11       *
 17               *
151           *

```

# Answer
> 5 votes
# Mathematica, ~~101~~ 90 bytes

*Thanks to ngenisis for saving 11 bytes!*

```
TableForm[Outer[If[#∣#2,Y,""]&,f=#&@@@FactorInteger[1##],g={##}],TableHeadings->{f,g}]&

```

The  character about a third of the way through is U+2223 (3 bytes). Unnamed function of a variable number of arguments, each of which is a nonzero integer, which returns a `TableForm` object (formatted output) like so:

`f=#&@@@FactorInteger[1##]` defines `f` to be the set of all primes dividing any of the inputs (equivalently, dividing their product `1##`), while `g` is the list consisting of the inputs. `Outer[If[#∣#2,Y,""]&,f,g]` makes a table of `Y`s and empty strings corresponding to divisibility (we use the undefined token `Y` instead of a string `"Y"` or `"*"` to save two bytes). Then we use `TableForm[...,TableHeadings->{f,g}]` to format the resulting array with appropriate row and column headings.

Previous submission:

```
Grid[p=Prepend;Thread[q[Outer[If[#∣#2,Y,""]&,f=#&@@@FactorInteger[1##],g={##}]~p~g,f~p~""]]/.q->p]&

```

# Answer
> 3 votes
# Jelly, 18 bytes

```
PÆfQ0;ðḍ€+W}⁸;"o⁶G

```

Uses `1` instead of `*`, as allowed by the rules.

Try it online!

### How it works

```
PÆfQ0;ðḍ€+W}⁸;"o⁶G  Main link. Argument: A (array of integers greater than 1)

P                   Take the product of the integers in A.
 Æf                 Compute all prime factors (with multiplicity) of the product.
   Q                Unique; deduplicate the prime factors.
    0;              Prepend a 0. Let's call the result P.
      ð             Begin a new, dyadic chain. Left argument: P. Right argument: A
       ḍ€           Divisible each; for each p in P, test all integers in A for
                    divisibility by P. Yields one row of the shape of A for each p.
                    Note that the first element of P is 0, so the first row of the
                    resulting matrix contains only zeroes.
          W}        Wrap right; yield [A].
         +          Add the results to both sides. Because of how Jelly's auto-
                    vectorization works, this adds the first row of [A] (just A) to
                    the first row of the divisibility matrix (all zeroes) and
                    leaves the other rows untouched.
            ⁸;"     Prepend the elements of P to the corresponding rows of the
                    previous result.
               o⁶   OR space; replace all zeroes with spaces.
                 G  Grid; format the matrix as requested in the challenge spec.

```

# Answer
> 2 votes
# Jelly, ~~25~~ 23 bytes

```
PÆfQ©ḍþµị⁾* ³;"Z⁶;®¤;"G

```

**Try it online!**

### How?

It may well be shorter to use `ÆE` and filter out empty rows.

```
PÆfQ©ḍþµị⁾* ³;"Z⁶;®¤;"G - Main link: list of numbers, L
       µ                - monadic chain separation
P                       - product of L - multiply them all together
 Æf                     - prime factors (with repetitions, in ascending order)
   Q                    - unique items, maintaining order
                              - note that the product was performed to keep order
    ©                   - place in the register for later use, and yield
      þ                   - form the outer product of that and L using the dyad:
     ḍ                  -     isDivisor - 1 if divides, 0 if not
        ị⁾* <space      - index into "* " (1s to "*", 0s to " ")
            ³           - program's first input, L
             ;"         - zip with concatenation (column headers to the left)
               Z        - transpose (get it around the right way)
                   ¤    - nilad followed by link(s) as a nilad
                ⁶;®     - space (⁶) concatenated with (;) the register value (®)
                    ;"  - zip with concatenation (row labels to the left)
                      G - format the result as a grid (join items with spaces and
                                               rows with line feeds so they align)
                        - implicit print

```

# Answer
> 2 votes
# Python 2 - 197 bytes

Switched to Python 2 for easier input handling and allowing \`\` for string conversion. Uses `gmpy2` for generating the next prime. Output format still based on previous Python 3 submission (see below), namely filling a list `g` with symbols and formatting it.

```
import gmpy2
i=input()
n=len(i)+1
p=1;g=[' ']+i
while p<i[-1]:
 p=gmpy2.next_prime(p)
 t=['*'[m%p:]for m in i]
 if'*' in t:g+=[p]+t
print((('{:>%d}'%(len(`i[-1]`)+1)*n+'\n')*(len(g)/n)).format(*g))

```

Try it online!

## Explanation

For those who don't want to decode it themselves.

```
import gmpy2                    # arithmetic library
i=input()
n=len(i)+1                      # saves bytes by not needing ()
                                # afterwards
p=1                             # starting number
g=[' ']+i                       # initialsing header row
while p<i[-1]:                  # looping until last character
  p=gmpy2.next_prime(p)         # get the next prime
  t=['*'[m%p:] for m in i]      # verify whether p is a
                                # divisor of each number
  if'*'in t:g+=[p]+t            # if any divisor found, append
                                # p + divisors to g.
print(
    (('{:>%d}'%(len(`i[-1]`)+1) # compute right formatting element
                                # for length of last character + 1
        *n+'\n'                 # repeat for each input + once
                                # for the prime and add newline
     )*(len(g)/n)               # repeat row format until g
                                # can be inserted
    ).format(*g)                # format using g
)

```

# Previous

## Python 3 - 251 bytes

Pretty sure someone can do better. Based on this answer for generating the primes \< `k`.

```
i=list(map(int,input().split(',')))
l=len(str(i[-1]))+1
n=len(i)+1
g=[0]+i+sum([l for l in [[k]+[j%k==0for j in i]for k in range(2,i[-1])if all(k%f for f in range(2,k))]if 1in l],[])
print((('{:>%d}'%l*n+'\n')*(len(g)//n)).format(*g).replace('0',' '))

```

Ungolfed version and explanation will follow.

# Answer
> 2 votes
# JavaScript (ES6), ~~264~~ ~~260~~ ... ~~179~~ 173 bytes

```
a=>[for(c of s=' '.repeat(w=a.slice(-1),i=0))if(!+(r=[i++?i:s,...i<2?a:a.map(x=>x%i&&c)].map(y=>(s+y).slice(-(w+1).length),a=a.map(d=x=>i<2|x%i?x:d(x/i))).join``))r].join`
`

```

I think this approach has now permanently exceeded the recursive one (currently 178 bytes):

```
f=(a,i=0,w=a.slice(-1))=>i++-w?(+(r=[i<2?'':i,...i<2?a:a.map(x=>x%i&&' ')].map(y=>(' '.repeat(w)+y).slice(-(w+1).length)).join``)?'':r+`
`)+f(a.map(d=x=>i<2|x%i?x:d(x/i)),i,w):''

```

Uses `0` in place of `*`, which is allowed by the challenge.

### Test snippet

```
let g =

a=>[for(c of s=' '.repeat(w=a.slice(-1),i=0))if(!+(r=[i++?i:s,...i<2?a:a.map(x=>x%i&&c)].map(y=>(s+y).slice(-(w+1).length),a=a.map(d=x=>i<2|x%i?x:d(x/i))).join``))r].join`
`

console.log(g([6,9,14,22]))
console.log(g([2,3,5,7]))
console.log(g([2,4,8,16,32]))
console.log(g([75,99,151,153]))
```

# Answer
> 1 votes
# Mathematica, 165 bytes

Rather verbose - maybe someone can do something with it:

```
(j=Join;a=#[[All,1]]&/@FactorInteger@#;b=Sort@DeleteDuplicates@Flatten@a;Grid[j[{j[{""},#]},Transpose@j[{b},Table[If[MemberQ[a[[t]],#],"*",""]&/@b,{t,Length@a}]]]])&

```

# Answer
> 1 votes
# Bash \+ GNU utilities, ~~134~~ ~~133~~ ~~132~~ ~~125~~ 123 bytes

```
q=printf\ ;u=$q%9s
$u
$q%9d $@
echo
for p in $($u\\n `factor $@`|bc|sort -un)
{
$q%9d $p
for x;{ ((x%p))&&$u||$u X;}
echo
}

```

Try it online!

# Answer
> 1 votes
# MATL, 31 bytes

```
pYfu!Gy\~h0GhwvVZ{'(?<!\d)0'0YX

```

This uses `1` instead of `*`, as allowed by the challenge.

Try it online! Or verify all test cases.

### Explanation (*outdated*)

```
p           % Implictly input array of numbers. Push product of array
Yf          % Prime factors as a row vector
u           % Keep only unique values
!           % Transpose into column vector
G           % Push input again
y           % Duplicate column vector of unique prime factors onto top
\           % Modulo, element-wise with broadcast
~           % Negate
h           % Concatenate horizontally
0           % Push 0
G           % Push input again
h           % Concatenate horizontally
w           % Swap
v           % Concatenate vertically
V           % Char array representation
Z{          % Convert to cell array of strings. Each row gives a string
'(?<!\d)0'  % Push this string: match '0' not preceded by a digit
0           % Push this string: '0' will be replaced by char 0
YX          % Regexp replace
            % Implicit inoput. Char 0 is displayed as space

```

# Answer
> 1 votes
# Python 2, ~~181~~ 179 bytes

<sup> -2 bytes thanks to FlipTack</sup>

```
n=input()
p=[]
t="%%%ss "%len(`n[-1]`)*-~len(n)
print t%(('',)+n)
i=2
while n[-1]/i:
 if all(i%j for j in p):
	p+=[i];s=['*'[m%i:]for m in n]
	if'*'in s:print t%tuple([i]+s)
 i+=1

```

The input must be a tuple.
Try it online!

# Answer
> 1 votes
## Batch, 451 bytes

```
@echo off
set/am=0,w=2,p=1
for %%n in (%*)do set/a"n=m-%%n,m+=(n>>31)*n
for /l %%i in (0,1,9)do set/am/=10,w+=!!m
set s=
for %%n in ("" %*)do set t=%%~n&call:t
set v=%*
:g
if not %s: =%==%p% echo%s%
if %m%==1 exit/b
set/at=p+=1,m=0
set s=
call:t
set v=&for %%n in (%v%)do set n=%%n&set t=&call:c
goto g
:c
set/ar=n%%p
if %r%==0 set/an/=p&set t=*&goto c
set/a"m|=n
set v=%v% %n%
:t
set t=           %t%
call set s=%%s%%%%t:~-%w%%%

```

Explanation: Starts by calculating the field width `w` via the maximum of the input values `m`. Generates the first line of output by padding an empty string and the input numbers to the width `w` using the subroutine `t`. Then loops through the integers starting at 2, generating the line of output by padding the integer and then calling the subroutine `c` to pad an empty string or an asterisk as appropriate for each value, however the generated line is then skipped if it contains no asterisks. As the output is generated, each value is divided by the integer until it would leave a remainder, so the loop terminates when no value is greater than 1.

Note that the `set v=` gets executed *after* the `%v%` is substituted into the `for` loop on the same line.

# Answer
> 1 votes
# Python 2, ~~157~~ ~~148~~ ~~146~~ ~~145~~ 143 bytes

```
def p(*t):print'%%%ds '%len(`x[-1]`)*len(t)%t
def f(x):k=m=1;p(' ',*x);exec"r=[n%k and' 'for n in x]\nif 0in m%k*r:p(k,*r)\nm*=k*k;k+=1;"*x[-1]

```

Uses `0` instead of `*`, as allowed by the rules.

Try it online!

### Background

To identify primes, we use a corollary of Wilson's theorem:

### How it works

The first line defines a helper function.

```
def p(*t):print'%%%ds '%len(`x[-1]`)*len(t)%t

```

**p** takes a variable number of arguments which it stores in the tuple **t**.

The `'%%%ds '%len(`x[-1]`)` uses a format string to construct a format string; `%%` is a literal percent sign, `%d` is a placeholder for the integer that `len(`x[-1]`)` returns, i.e., the number of digits of the last element in **x** (the input, not yet defined), and  is literal.

If, e.g., the last element of **x** has three digits, this yields `%3s`, which `*len(t)` repeats once for every element of **x**. Finally, `%t` applies that format string to the tuple **t**, constructing a string of **t**'s elements, space-separated and all right-justified to a certain length.

The second line defines the actual submission: a function **f** that takes a list **x** as input. After replacing the `exec` statement, which executes the string it precedes `x[-1]` times, with a `for` loop, we get the following code.

```
def f(x):
    k=m=1;p(' ',*x)
    for _ in range(x[-1]):
        r=[n%k and' 'for n in x]
        if 0in m%k*r:p(k,*r)
        m*=k*k;k+=1

```

First, **f** initializes **k** and **m** to **1**. Note that **(k - 1)! = 0! = 1 = m**.

Then, `p(' ',*x)` prints a space and the integers in **x**, using the function **p**.

Now, we enter the loop to print the remaining output.

First, `r=[n%k and' 'for n in x]` constructs the list of the remainders of each integer **n** in **x** divided by **k**. Positive remainders, i.e, remainders that do not correspond to multiples of **k**, are truthy and get replaced with a space by `and' '`.

Next, we construct `m%k*r`. Since **m = (k - 1)!**, by the corollary of Wilson's theorem, this will be simply **r** if **k** is prime, but an empty list if not. If there is at least one **0** in the result, i.e., if **k** is prime and at least one integer in **x** is divisible by **k**, `0in m%k*r` will return *True* and `p(k,*r)` get called, printing **k** and the divisibility indicators: `0` if divisible, a space if not.

Finally, we multiply **m** by  and increment **k**, so the quality **m = (k - 1)!** continues to hold.

# Answer
> 0 votes
## Racket 176 bytes

```
(let((p printf))(display"   ")(for((x nl))(p" ~a " x))(displayln"")(for((i '(2 3 7 11)))
(p"~a  " i)(for((j nl))(if(member i(prime-divisors j))(p" * ")(p"   ")))(displayln"")))

```

Ungolfed:

```
(define (f nl)
  (let ((p printf))

    (display "   ")
    (for ((x nl))
      (p " ~a " x))
    (displayln "")

    (for ((i '(2 3 7 11)))
      (p "~a  " i)
      (for ((j nl))
        (if (member i (prime-divisors j))
            (p " * ")
            (p "   ")))
      (displayln ""))))

```

Testing:

```
(f '(6 9 14 22))

```

Output:

```
    6  9  14  22
2   *     *  *
3   *  *
7         *
11            *

```

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


title: Build the blancmange function

text:
# Question
Title: Build the blancmange function
The blancmange function is used as an example in basic calculus of a function that is continuous everywhere, but differentiable nowhere. It achieves this effect by using the sums of ever-diminishing triangle-wave functions.

Your task is to build a program that takes a binary fractional number in the interval \[0, 1\] and returns the exact height of the blancmange curve at that position. Both fractions can be represented using the notation of your choice, but if you are using a nonstandard one (e.g. not IEEE floating-point or an integer with a fixed radix point), you must explain it in your solution, and your notation must support an accuracy of at least 2<sup>-52</sup>.

# Answer
# Ruby, 53 characters

```
f=->x{x>0?f[2*x=x<0.5?x:1-x]/2+x: 0}
$><<f[gets.to_f]

```

expanded:

```
f = lambda do |x|
  if i>0
    x = 1 - x unless x < 0.5
    return x + f[2*x] / 2
  else
    return 0
  end
end

print f[gets.to_f]

```

The input is a decimal value, assumed to be in the range 0..1 . The output is a decimal value. The platform native double precision numeric type is used, and is assumed to be at least 53 bits of mantissa. Since every floating point value in a binary fraction, this algorithm will always terminate after at most 53 (with the default precision) steps.
> 1 votes

# Answer
# Mathematica 92 chars

This uses exact arithmetic (fractions).

```
b@n_:=FoldList[#+{1,#2}/2^n&,{0,0},
Total/@ (2 Reverse[IntegerDigits[#,2,n]&/@Range[0,2^n-1]]-1)]

```

> {{{0, 0}, {1/2, 1/2}, {1, 0}}, {{0, 0}, {1/4, 1/2}, {1/2, 1/2}, {3/4, 1/2}, {1, 0}}, {{0, 0}, {1/8, 3/8}, {1/4, 1/2}, {3/8, 5/8}, {1/2, 1/2}, {5/8, 5/8}, {3/4, 1/2}, {7/8, 3/8}, {1, 0}}, {{0, 0}, {1/16, 1/4}, {1/8, 3/8}, {3/16, 1/2}, {1/4, 1/2}, {5/16, 5/8}, {3/8, 5/ 8}, {7/16, 5/8}, {1/2, 1/2}, {9/16, 5/8}, {5/8, 5/8}, {11/16, 5/ 8}, {3/4, 1/2}, {13/16, 1/2}, {7/8, 3/8}, {15/16, 1/4}, {1, 0}}}

Source: Borut Levart \[http : // demonstrations.wolfram.com/TakagiCurve/ \]
> 1 votes

# Answer
# Mathcad, 73 "bytes"

The Mathcad worksheet shown here defines the triangle function s(x) and the blancmange function (blanc(x) - but deemed to be just b(x) for golfing purposes). It also presents two variants, one specialized for rational numbers with power of two divisors, and one specialized for number of iterations of the summation. The worksheet also presents plots of the various blancmange functions and tables of their results.

The blancmange function works in both numeric (IEEE floating point) and symbolic (arbitrary arithmetic) modes.

Mathcad uses a virtual 2D worksheet on which the user places text or executable expressions (eg, formula or programs). Mathcad saves its worksheets in an XML format, which means that even a small program can be many hundreds or thousands of text characters long. For the purposes of code golfing, I take a Mathcad "byte" to mean the number of distinct symbols that the user must enter to create a program.

For example, to evaluate an expression, the user types "="; Mathcad will place an evaluation operator on the worksheet, which gives the appearance of an "=" sign bounded by two black box symbols (known as placeholders). Writing an expression in the left hand placeholder will cause Mathcad to evaluate the expression and put the result in the right hand placeholder. If the expression is a simple variable, "a" say, that contains a value, then from an user perspective this would count as 2 byte program "a" and "=". Raising one number to the power of another comprises entering the exponent operator (^) and then entering the two numbers in the appropriate placeholders. So, 3^4 would be a 3 byte program.
> 0 votes

# Answer
Not sure if this counts, but this Pari GP implementation works for any x. **53 bytes**

`s(x)=abs(x-round(x));
bm(x)=sum(i=0,50,s(2^i*x)/2^i);`
> 0 votes

# Answer
## JavaScript (ES6), 35 bytes

```
B=x=>x%1?B(2*x%1)/2+(x<1/2?x:1-x):0

```

A straightforward implementation of this recursive formula.
> 0 votes

---
Tags: code-golf, fractal, calculus
---


title: Determine the type of Cuboid

text:
# Question
Title: Determine the type of Cuboid
## Introduction:

I'm a twisty puzzles collector. Here you can see my current collection of ± 300 puzzles.

I think everyone knows the regular Rubik's Cube (3x3x3 Cube), which is a *NxNxN* Cube. There are also Cuboids (block-shaped puzzles), which come in different forms, perhaps better explained by SuperAntionioVivaldi here:

* **Regular Domino Cuboids** (like the 2x2x3; 2x3x3; 3x3x4; etc.) - They come in the form of *NxNx(N+O)* or *Nx(N+O)x(N+O)*, which have either two odd dimensions and an even, or two even and an odd.
* **Shapeshifter Cuboids** (like the 2x2x4; 3x3x5; 3x3x9; 4x4x6; etc.) - They come in the form of *NxNx(N+P)*, which as the name suggests, shapeshifts (in all directions). All three dimensions are either odd or even.
* **Floppy Cuboids** (like the 1x3x3; 2x4x4; etc.) - They come in the form of *Nx(N+P)x(N+P)*, which are almost the same as the Shapeshifters, but with so-called Floppy Parities.
* **Brick Cuboids** (like the 2x3x4; 3x4x5; 2x3x5; etc.) - They come in the form of Nx(N+O)x(N+P), which just like the Regular Domino Cuboids have either two odd dimensions and an even, or two even and an odd; but don't have any of the same dimensions.
* **Ultimate Shapeshifters** (like the 2x4x6; 3x5x7; 2x4x10; etc.) - They come in the form of *Nx(N+O)x(N+R)*, and shapeshift in any direction. All three dimensions are either odd or even; but don't have any of the same dimensions.

## Challenge:

### Input:

A positive integer ***n*** with the following restriction: 8 \<= ***n*** \<= 125.
***n*** can be uniquely decoded as the product of three values (the dimensions), of which each is between 2 and 5 inclusive.

The reason I've restricted it to 2-5 is to prevent duplicated inputs (like `1x2x4 = 8` and `2x2x2 = 8`), even though there are many lower/higher order Cuboids out there. This also means there are no test cases for Ultimate Shapeshifters.

### Output / Test cases:

These are all the cases your program/function should support, ranging from edge lengths 2 through 5 in every possible three-dimensional configuration:

```
Input   Cuboid/Cube   Type/Output
8       2x2x2         Cube
12      2x2x3         Regular Domino Cuboid
16      2x2x4         Shapeshifter Cuboid
20      2x2x5         Regular Domino Cuboid
18      2x3x3         Regular Domino Cuboid
24      2x3x4         Brick Cuboid
30      2x3x5         Brick Cuboid
32      2x4x4         Floppy Cuboid
40      2x4x5         Brick Cuboid
50      2x5x5         Regular Domino Cuboid
27      3x3x3         Cube
36      3x3x4         Regular Domino Cuboid
45      3x3x5         Shapeshifter Cuboid
48      3x4x4         Regular Domino Cuboid
60      3x4x5         Brick Cuboid
75      3x5x5         Floppy Cuboid
64      4x4x4         Cube
80      4x4x5         Regular Domino Cuboid
100     4x5x5         Regular Domino Cuboid
125     5x5x5         Cube

```

### Challenge rules:

* Any non-Cube/non-Cuboid input within the 8-125 range should result in 'none' as output.
* The output format is your own choice. I think the most reasonable is integers, like `0` = 'none'; `1` = Cube; `2` = Regular Domino Cuboid; `3` = Shapeshifter Cuboid; `4` = Floppy Cuboid; `5` = Brick Cuboid. Any other output format is also fine, as long as you specify which one you've used.

### General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.
* Default Loopholes are forbidden. (*NOTE: Since I don't know if there is a smart formula for the input-to-output conversion, it is allowed to hardcode the answers based on the input.*)
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.

# Answer
> 6 votes
# 05AB1E, ~~26~~ 21 bytes

`None: 0
 Cube: 1
 Regular Domino Cuboid: 2
 Shapeshifter Cuboid: 3
 Brick Cuboid: 4
 Floppy Cuboid: 5`

```
•S3X@I¨%÷'•5L¦3ãPÙIkè

```

Try it online! or as a Test suite

**Explanation**

```
•S3X@I¨%÷'•            # push base-214 compression of the number 123224454212324512210
           5L¦         # push the list [2,3,4,5]
              3ã       # cartesian product with repetion of size 3
                P      # product of each sublist
                 Ù     # remove duplicates
                  Ik   # get the index of input in that list (-1 if non-existant)
                    è  # get the element at this index in the above number

```

The only place I see that we could save bytes here is find a better way of generating the number **123224454212324512210**.

It is only 1-off from a prime, so one possible save would be to find the index of that prime and generate the index in less than 9 bytes.
I don't know how well the pi-function works for 21-digit primes but that could be a possibility.

# Answer
> 3 votes
## JavaScript (ES6), ~~97~~ ~~92~~ 86 bytes

This function first checks the validity of the input, then picks the correct value from a lookup table.

Surprisingly, the longest part is the validity check (is **n** of the form **x\*y\*z** with **x**, **y** and **z** in **\[2,3,4,5\]**?). There must be a shorter way of doing it, but I couldn't figure it out so far.

```
n=>'NBBF..CRCC.BRR..SFRRRRR.B..C'[[34707324,0x80000800,4240,262208][n&3]>>n/4&1&&n%29]

```

Returns a character:

* **N**: None
* **C**: Cube
* **R**: Regular Domino Cuboid
* **S**: Shapeshifter Cuboid
* **B**: Brick Cuboid
* **F**: Floppy Cuboid

### Test

```
let f =

n=>'NBBF..CRCC.BRR..SFRRRRR.B..C'[[34707324,0x80000800,4240,262208][n&3]>>n/4&1&&n%29]

// invalid
;[9,13,99].map(
  n => { console.log(n, f(n)) }
)

// valid
;[8,12,16,20,18,24,30,32,40,50,27,36,45,48,60,75,64,80,100,125].map(
  n => { console.log(n, f(n)) }
)
```

# Answer
> 1 votes
## Ruby, ~~106 98~~ 96 bytes

```
->n{[[x=25,2421],[15,53],[9,21],[4,1232504350200510002]].any?{|a,b|n%a<1&&x="00#{b}"[n/a]}?x:?0}

```

Because, why not, hardcoding.

As specified, 0 = 'none'; 1 = Cube; 2 = Regular Domino Cuboid; 3 = Shapeshifter Cuboid; 4 = Floppy Cuboid; 5 = Brick Cuboid

# Answer
> 1 votes
# Perl 6, ~~69~~ 58 bytes

```
{%(unique([X*] (2..5)xx 3)Z=>:32<AM0K21IHN61H5>.comb){$_}}

```

Uses the integer output format suggested in the task description, except that it returns the uninitialized value `(Any)` instead of `0` in case of inputs that don't form a valid cube/cuboid.

### How it works

1. ```
unique([X*] (2..5)xx 3)
```

Generates the list `8 12 16 20 18 24 30 32 40 50 27 36 45 48 60 75 64 80 100 125`.
2. ```
:32<AM0K21IHN61H5>.comb
```

Generates the list `1 2 3 2 2 5 5 4 5 2 1 2 3 2 5 4 1 2 2 1` (from a base-32 literal).
3. ```
%(   Z=>   )
```

Generates a Hash (associative map) with the first list as the keys, and the second list as the values.
4. ```
   {$_}
```

Indexes the Hash with the input number..

# Answer
> 1 votes
## Batch, 163 bytes

```
@set/as=0,c=29948521
@for /l %%i in (2,1,5)do @for /l %%j in (%%i,1,5)do @for /l %%k in (%%j,1,5)do @set/as+=c%%6*!(%%i*%%j*%%k-%1),c/=6,c+=14081593*!c
@echo %s%

```

Uses the suggested output format. Explanation: The basic idea is to loop over the list of cubes as defined in the question. For each cube, we calculate to see if its volume is the input integer, and if so, calculate the type of cube from a lookup table.

The original lookup table was a string of letters, but doing string manipulation in a `for` loop is tricky, so I switched to digits which can be extracted arithmetically. Sadly Batch is limited to 32-bit integers so I couldn't fit all of the digits into a single variable (even in base 5 you can only get 13 digits) so instead I split the variable up into two parts, encoded in base 6 for convenience. `29948521` is `2545522321` in base 6 which encodes the 10 smallest cuboids in reverse order; when it runs out of digits we add `14081593` which is `1221452321` in base 6 encoding the 10 biggest cuboids.

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


title: Can't see the forest for the trees

text:
# Question
Title: Can't see the forest for the trees
Write a program or function that draws a tree of trees, thus constructing a forest.

The trees are drawn like stacking a pyramid. The first (top) row contains `1` tree, the next row down contains `2` (for a total of `3`), the next contains `3` (for a total of `6`), and so on. If there aren't enough trees to complete a full row, fill it to the left and leave the spots on the right empty. Additionally, lower-level trees slightly overlap upper-level trees due to their placement.

This is a forest of size `1`

```
  /\
 //\\
///\\\
  ||
  ||

```

This is a forest of size `2`

```
      /\
     //\\
  /\///\\\
 //\\ ||
///\\\||
  ||
  ||

```

This is a forest of size `3`

```
      /\
     //\\
  /\///\\\/\
 //\\ || //\\
///\\\||///\\\
  ||      ||
  ||      ||

```

This is a forest of size `4`

```
          /\
         //\\
      /\///\\\/\
     //\\ || //\\
  /\///\\\||///\\\
 //\\ ||      ||
///\\\||      ||
  ||
  ||

```

This is a forest of size `5` (note the top of the fifth tree is covering the trunk of the first tree)

```
          /\
         //\\
      /\///\\\/\
     //\\ || //\\
  /\///\\\/\///\\\
 //\\ || //\\ ||
///\\\||///\\\||
  ||      ||
  ||      ||

```

(skip a few)
This is a forest of size `8` (extending the pattern)

```
              /\
             //\\
          /\///\\\/\
         //\\ || //\\
      /\///\\\/\///\\\/\
     //\\ || //\\ || //\\
  /\///\\\/\///\\\||///\\\
 //\\ || //\\ ||      ||
///\\\||///\\\||      ||
  ||      ||
  ||      ||

```

and so on.

### Input

A single positive integer in any convenient format, `n > 0`.

### Output

An ASCII-art representation of the forest, following the above rules. Leading/trailing newlines or other whitespace are optional, provided that the trees all line up appropriately.

### Rules

* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
> 5 votes
## Haskell 310 bytes

```
w i=putStr$unlines$reverse$b i 0 0[][]
b 0 _ _ w r=e w r
b c l 0 w r=b c(l+1)l(e w r)[]
b c l p w r=b(c-1)l(p-1)w(n(++)["  ||    ","  ||    ","///\\\\\\  "," //\\\\   ","  /\\    "]r)
e w r=t++n(n d)(map(\t->"    "++t)w)c where(t,c)=splitAt 2 r
n f(a:c)(b:d)=f a b:n f c d
n _ a[]=a
n _ _ a=a
d d ' '=d
d _ d=d

```

Call it with `w 5`, for example.

Here the uncompressed code:

```
-- TreeTree
-- by Gerhard
-- 12 February 2017

module TreeTree (wood,test) where

type Tree = [String]

-- Test cases
test = do
 wood 0
 wood 1
 wood 2
 wood 3
 wood 4
 wood 5

-- build wood
wood :: Int -> IO ()
wood i = printTree $ buildWood i 0 0 [] []

-- Prints the trees
printTree :: Tree -> IO ()
printTree = putStr . unlines . reverse

-- build wood
buildWood :: Int -> Int -> Int -> Tree -> Tree -> Tree
buildWood 0 _ _ w r = concatTree w r
buildWood c l 0 w r = buildWood c (l+1) l (concatTree w r) []
buildWood c l p w r = buildWood (c-1) l (p-1) w (addTree r)

-- indent definition
space :: String
space = "    "

-- tree definition
tree :: Tree
tree = reverse [
 "  /\\    ",
 " //\\\\   ",
 "///\\\\\\  ",
 "  ||    ",
 "  ||    "]

-- Add a Tree on the left side
addTree :: Tree -> Tree
addTree = match (++) tree

-- add tree row at the bottom of the wood
concatTree :: Tree -> Tree -> Tree
concatTree w r = trunk ++ matched
 where
  wood = grow w
  (trunk, crown) = splitAt 2 r
  matched = matchTree wood crown

-- elnarge forrest on the left side to match next tree line
grow :: Tree -> Tree
grow = map (\t -> space ++ t)

-- match
match :: (a -> a -> a) -> [a] -> [a] -> [a]
match f (a:az) (b:bz) = f a b : match f az bz
match _ a [] = a
match _ _ a  = a

-- match trees
matchTree :: Tree -> Tree -> Tree
matchTree = match matchLine

-- match lines
matchLine :: String -> String -> String
matchLine = match matchChar

-- match chars
matchChar :: Char -> Char -> Char
matchChar c ' ' = c
matchChar _ c   = c

-- End

```

# Answer
> 4 votes
# C++ (on Windows), ~~330~~ ~~312~~ ~~308~~ ~~304~~ 303 bytes

```
#import<cstdio>
#import<windows.h>
#define P(x,y,s)SetConsoleCursorPosition(GetStdHandle(-11),{X+x,Y+y});puts(s);
int X,Y,R,r,c;t(){P(2,-2,"/\\")P(1,-1,"//\\\\")P(0,0,"///\\\\\\")P(2,1,"||")P(2,2,"||")}f(int n){for(c=R=r=1;c<n;c+=++R);for(;r;r++)for(c=0;++c<r+1;){X=(R-r-2)*4+c*8;Y=r*2;t();r=--n?r:-1;}}

```

Call with:

```
int main()
{
    f(8);
}

```

# Answer
> 4 votes
## JavaScript (ES6), ~~357~~ ~~297~~ 276 bytes

```
f=
n=>{a=`  /\\`;d=`///\\\\\\`;b=d+`/\\`;c=` //\\\\ ||`;d+=`||`;e=`
`;r=`repeat`;s=``;for(i=1;n>i;n-=i++)s=(s+a+b[r](i-1)+e+c[r](i)).replace(/^/gm,`    `)+e;return(s+a+b[r](n-1)+d[r](i-=n)+e+c[r](n)+(s=`      ||`[r](i))+e+d[r](n)+s+(s=e+`  ||    `[r](n))+s).replace(/\|.$/gm,``)}
```

```
<input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o>
```

Edit: Saved 21 bytes thanks to @KritixiLithos.

# Answer
> 1 votes
## Javascript ~~418~~ 377 bytes

Thanks to @Kritixi Lithos for helping golf off 39 bytes

```
x=>{s='';for(t=0;++t<x;x-=t);q='//\\\\';z="///\\\\\\";h="/\\";t--;for(i=0;i<t;i++){a=4*(t-i)+1;s+=" "[w="repeat"](a+1)+h+(z+h)[w](i)+`
`+" "[w](a)+q+(" || "+q)[w](i)+`
`}c=t-x+1>0?t-x+1:0;return x?s+"  "+(h+z)[w](--x)+h+(c?(z+"||")[w](c-1)+z:'')+`
 `+q+(" || "+q)[w](x)+" ||     "[w](c)+`
`+(z+"||")[w](x)+z+(c?"||"+"      ||"[w](c-1):'')+`
`+("  ||    "[w](x+1)+`
`)[w](2):''}

```

Try it Online

# Answer
> 0 votes
# C (on Windows), ~~297~~ ~~295~~ 294 bytes

```
#import<windows.h>
#define P(x,y,s)C.X=X+x;C.Y=Y+y;SetConsoleCursorPosition(GetStdHandle(-11),C);puts(s);
COORD C;X,Y,R,r,c;t(){P(2,-2,"/\\")P(1,-1,"//\\\\")P(0,0,"///\\\\\\")P(2,1,"||")P(2,2,"||")}f(n){for(c=R=r=1;c<n;c+=++R);for(;r;r++)for(c=0;++c<r+1;){X=(R-r-2)*4+c*8;Y=r*2;t(r=--n?r:-1);}}

```

Similar to my C++ answer, but I posted this because it's somewhat shorter in C.

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


title: Fraction Frenzy!

text:
# Question
Title: Fraction Frenzy!
*EDIT: I'm getting a lot of comments about this not terminating - I will give the "correct answer" tag to either the first person who gives me `FF(3)` (as in provides it in their answer) or proves that `FF(3)` does indeed blow up indefinitely.*

## Task:

Your task is make the smallest program possible that generates the list of reciprocals of the Fraction Frenzy function (`FF(n)`) given a positive integer `n`.

## Introduction:

Before I can introduce the FF function, I have to first explain Egyptian fractions.

### Egyptian Fractions:

Egyptian fractions are a way of expressing fractions as the sum of distinct unit fractions - so one way to express the fraction `5/8` is `1/2 + 1/8`. It is not other fraction sums like

```
1/4 + 1/4 + 1/8
1/2 + 1/16 + 1/16

```

because not all of their fractions are distinct (`1/4` is repeated in the first example, and `1/16` in the second).

In our definition of Egyptian fractions, we are including the use of negative denominators in the unit fractions as well.

### FF function:

The FF (Fraction Frenzy) function is described like so:

`FF(1)` is the Egyptian fraction `1/2 + 1/3 + 1/5 + 1/-30`.

`FF(2)` is equal to `FF(1)` "multiplied" by itself (`FF(1)` "squared"):

```
  (1/2 + 1/3 + 1/5 + 1/-30)(1/2 + 1/3 + 1/5 + 1/-30)
= 1/4 + 1/6 + 1/10 + 1/-60 + 1/6 + 1/9 + 1/15 + 1/-90 +
  1/10 + 1/15 + 1/25 + 1/-150 + 1/-60 + 1/-90 + 1/-150 + 1/900

```

This is not a fully reduced Egyptian fraction yet, because there are "repeats" in fractions. To reduce them, the following procedure is done:

1. Sum all "like" unit fractions together.
2. Reduce the sums to their simplest forms - so for example, if a sum from step `1` is `2/6`, that can be reduced to `1/3`.
3. Repeat 1 and 2 until all denominators are distinct: for example, `1/2 + 2/3 + 1/5`, as opposed to `1/2 + 1/3 + 1/3`, which has a repeating denominator `3`.
4. If there is a pair of one positive and one negative fraction that have an equal absolute value, remove both of them (e.g. `1/-5` and `1/5` must both be removed).
5. If fractions are not unit and cannot be reduced further, split it up into unit fractions with a equal denominator, and keep one fraction as it is. With the other ones, multiply them by `FF(1)`: `(1/2 + 1/3 + 1/5 + 1/-30)`.
6. Repeat steps 1-5 until the final fraction sum is a valid Egyptian fraction - i.e. all fractions are distinct from one another, and they are all unit fractions.

This is the reduction of `FF(2)`:

```
  1/4 + 1/6 + 1/10 + 1/-60 + 1/6 + 1/9 + 1/15 + 1/-90 +
  1/10 + 1/15 + 1/25 + 1/-150 + 1/-60 + 1/-90 + 1/-150 + 1/900
= 1/4 + 2/6 + 1/9 + 2/10 + 2/15 + 1/25 + 2/-60 + 2/-90 + 2/-150 + 1/900 (step 1)
= 1/4 + 1/3 + 1/9 + 1/5 + 2/15 + 1/25 + 1/-30 + 1/-45 + 1/-75 + 1/900   (step 2)
= 1/3 + 1/4 + 1/5 + 1/9 + 1/15 + 1/15(1/2 + 1/3 + 1/5 + 1/-30) +        (step 5)
  1/25 + 1/-30 + 1/-45 + 1/-75 + 1/900
= 1/3 + 1/4 + 1/5 + 1/9 + 1/15 + 1/30 + 1/45 + 1/75 + 1/-450 +
  1/25 + 1/-30 + 1/-45 + 1/-75 + 1/900
= 1/3 + 1/4 + 1/5 + 1/9 + 1/15 + 1/25 + 1/-450 + 1/900                  (step 4)

```

For all `n` (except for `1`), `FF(n)` is defined by "squaring" `FF(n-1)`.

## Input and Output:

Given an integer `n`, you must output a list all of the reciprocals of `FF(n)`, sorted in ascending order of their absolute values:

```
1 -> [2, 3, 5, -30]
# 1/2 + 1/3 + 1/5 + 1/-30 = FF(1), reciprocals = [2, 3, 5, -30]

2 -> [3, 4, 5, 9, 15, 25, -450, 900]

```

You are allowed to use a string with any delimiter, or your language's interpretation of a list, so these outputs are all acceptable with the input `1`:

```
2 3 5 -30   (Space-delimited)
2,3,5,-30   (Comma-delimited)
[2 3 5 -30] (Lisp-like lists)
etc. etc.

```

## Specs:

* You must output the results of the `FF(n)` function exactly as specified above.
* You are guaranteed that the input will be a positive integer - it will never be below zero, and it will never be a decimal (or fraction).

This is , so shortest code in bytes wins!

# Answer
# Haskell, 365 bytes

```
import Data.Function;import Data.List;import Data.Ratio;n=numerator;d=denominator
r=until=<<((==)=<<)$filter(/=0).map(sum).groupBy((==)`on`d).sortBy(compare`on`d)
p s=let(o,q)=span((<2).abs.n)s in case q of []->o;(a:b)->let j=a-1%d a*signum a in p.r$o++[a-j]++map(*j)e++b
s s=(*)<$>s<*>s;e=(1%)<$>[2,3,5,-30];f=iterate(p.r.s)e;o i=[abs(d q)*signum(n q)|q<-f!!(i-1)]

```

Try it online!
> 1 votes

---
Tags: code-golf, math, rational-numbers
---