# Question
Title: How long will it take Santa to deliver his presents?
I posted this challenge a while ago, which concerns *how many* elves Santa needs to deliver presents.

Due to population increase, Santa is a little more pressed for time this year. Although in the past we operated very asynchronously, we are beginning to experiment with being more and more synchronized. So, Santa needs to know how long it will take him to deliver presents to each region with a given number of elves.

The weight of coal hasn't changed over the past two years — it's still heavier than presents, so Santa needs three elves per naughty person in the house, and two elves per nice person in the house.

Elves spend all year training for Christmas, so they don't need any rest between deliveries. They can only deliver presents to one house at a time, and must go back Santa's sleigh and collect the next gift before going to the next house. For reasons that I am not at liberty to share, elves do not spend time traveling between Santa's sleigh and houses (but can only travel when Santa's sleigh is on the roof), nor does his sleigh spend time moving from house to house. (Santa's sleigh *does* needs to move from house to house in order to collect fuel, but I'm already saying too much).

Elves that are delivering presents need to spend **four seconds*** each delivering the presents, and Elves that are delivering coal need to spend **five seconds*** each delivering it (as per Santa Aviation Administration regulations, gloves with coal dust on them must be incinerated immediately upon boarding the sleigh, which takes up some time). Additionally, the houses must be visited in the order they are on the map, from left to right, and elves can not begin delivering presents to other houses until all presents have been delivered to the house they are currently at.

If we assumed that Santa had more than enough elves for this region, it would take only as long as it takes to deliver a present to someone on the naughty list, 5 seconds, per house, or 4 seconds per house if everyone is nice.

Yet, as opposed to previous seasons, this coming Christmas Santa may not have more than enough elves for each region, so 4 seconds is the absolute minimum amount of time* that it will take to deliver presents to any given house, unless there are 0 nice people and 0 naughty people in which case it will take 0 seconds.

Additionally, if even one of the houses has someone on the naughty list, Santa will need at least three elves. If at least one of the houses has someone on the nice list and none of them have people on the naughty list, Santa will need at least two elves. If none of the houses are in the Christmas spirit, any number of elves (including 0) will takes 0 seconds.

On Santa's map, a house is represented by a `*`, and each house is split by a `+`. Santa still uses the same maps as in the other challenge, but I'll include documentation about them here.

There will be a number on either side of the house - the one on the left representing the number of naughty people in the house, and the one on the right representing the number of nice people in the house. If there is no number on one side it is interpreted as a 0.

I know it may sound crazy, but some people "don't like Christmas", so sometimes, a house may not have a number on either side of it.

One of Santa's maps could look something like this.

```
1*3+2*+*5+*+4*7

```

Let's say Santa has nine elves in his sleigh.

1. (0s) The first house has 1 naughty and 3 nice people. Three of the elves deliver coal, taking five seconds, and six deliver presents, taking four seconds. After five seconds, Santa's sleigh moves to the next house
2. (5s) The second house has 2 naughty and 0 nice people. Six of the elves deliver coal, taking five seconds. After five seconds, Santa's sleigh moves to the next house
3. (10s) The third house has 0 naughty and 5 nice people. Eight of the elves go to deliver four presents (the one that is left behind can't deliver a present). After four seconds, all of the elves are back, and two of them go to deliver the other present (the sleigh must wait for the elves to get back before going to the next house), taking another four seconds
4. (18s) The fourth house is not in the Christmas spirit, so has 0 naughty and 0 nice people, and is skipped
5. (18s) The fifth house has 4 naughty and 7 nice people. This gets a bit complicated...

I. All nine of the elves go to deliver three gifts of coal (leave t+0s, return t+5s) II. After 5s, they are all back on the sleigh, and three of them go to deliver the last present of coal (leave t+5s, return t+10s) while the other six of them go to deliver three nice presents (leave t+5s, return t+9s).

III. After four seconds, six of the elves are back and go to deliver three more nice presents (leave t+9s, return t+13s).

IV. One second after they leave, the three elves that were delivering the coal present get back, and two of them leave to deliver the last nice present (leave+10s, return t+14s)
6. (18 + 14 = **32 seconds**) Santa is finished delivering presents to that region.

As we can see, it takes Santa a total of **32 seconds** to deliver presents to this region. That was an over-simplified version of one of Santa's maps, though. Normally, Santa's maps have multiple lines, and are in a square shape as to better fit on his list. A normal map might look something like this (a `\n` at the end of each line)

```
1*2+*+*4+1*
2*4+3*+1*6+*
*+*+4*2+1*1
*4+*3+1*+2*3
3*10+2*+*5+*

```

With **26 elves** (or any higher amount), it would take Santa **71 seconds**.
With **20 elves**, it would take Santa **76 seconds**.
With **15 elves**, it would take Santa **80 seconds**.
With **3 elves**, it would take Santa **288 seconds**.
With **2 elves** (or any lower amount), it would be **impossible.**

Oh, and one more thing — **the order in which the elves deliver presents matters** (because of the time difference of delivering presents naughty/nice people), so your code should **always output the least amount of time that the elves can take delivering presents.**

## Challenge

Help Santa determine how long it will take for a given number of elves to deliver presents.

**Houses**

* A house is represented by a `*`
* Houses are split by `+`
* The number on the left of the house symbolizes the number of naughty people (no number means 0)
* The number on the right symbolizes the number of nice people (no number means 0)
* There may be newlines (`\n`) in the input, which should also be handled as a split

**Elves**

* Santa needs help from **three** elves for naughty people (coal is much heavier than presents), and it will take these elves **five seconds*** to deliver the presents
* Santa needs help from **two** elves for nice people, and it will take these elves **four seconds*** to deliver the presents
* If there is no number on either side of the house, Santa will not visit that house, and therefor it will not take any time (people not in the Christmas spirit don't even deserve coal)

**Santa**

* Santa must deliver presents to the houses one-by-one
* Santa can not move onto the next house until all of the elves are back on the sleigh and all of the presents have been delivered to that house (we don't want to leave elves behind, now do we?)
* Santa's sleigh doesn't spend any time traveling from house to house (Again, for reasons which I am not at liberty to share)

**What to do**

Given a map of a houses and a number of elves, print how long it will take Santa to deliver presents to the houses on the map.

***** (I may not share the amount of time it takes elves to deliver presents. I can neither confirm nor deny that the times included in this challenge are correct)

## Rules

* There are two inputs — the map and the number of elves. The inputs can be either taken as arguments to a function, or from **STDIN** or equivalent. If taking two inputs is impossible in your language, then and only then may you accept the two inputs as a single input string, delimited by some character not normally in an input (not one of `+*\n` or `0-9` — the input string can't be ambiguous) e.g. `,`.
* The number of elves will always be a non-negative integer (0 is valid)
* The output can either be the return value of a function, or printed to **STDOUT** or equivalent. If it is impossible for Santa to deliver presents to the given region with a given number of elves, you must output a consistent negative number, or a consistent message *without any numbers in it*
* Everything printed to **STDERR** will be ignored, so you may not print the result or the error message to **STDERR**
* Your program can not crash given an invalid number of elves for a region
* The output should be only the total amount of time it will take Santa to deliver the presents with the given number of elves.
* The output should always be the least amount of time it takes for the elves to deliver presents
* The input will only contain numbers, `+`, `*`, and newlines `\n` (unless you specify another character which the input will include if your language can't take two inputs (look at the first rule))
* Standard loopholes apply

## Test Cases

```
"1*1", 5 elves => 5
"1*1", 3 elves => 9
"1*2", 7 elves => 5
"1*2", 5 elves => 10
"1*2", 3 elves => 13
"2*1", 8 elves => 5
"2*1", 5 elves => 9
"2*1", 3 elves => 14
"1*" , 3 elves => 5
"1*" , 2 elves => (error message)
"*1" , 2 elves => 4
"*1" , 0 elves => (error message)
"*"  , 0 elves => 0

"1*1+1*1",   5 elves => 10
"1*1+1*1",   3 elves => 18
"1*1+*+1*1", 3 elves => 18
"1*2+2*1",   8 elves => 10
"1*2+2*1",   7 elves => 14
"1*2+2*1",   6 elves => 18
"1*2+2*1",   3 elves => 27
"1*2+2*1",   2 elves => (error message)
"*+*+*+*",   2 elves => 0
"*+*+*+*",   0 elves => 0

"1*3+2*+*5+*+4*7", 9 elves => 32

```

(hopefully I got all of that correct)

## Scoring

Santa spends every single day always looking at *a lot* of things — all of the presents he's going to deliver, all of the elves he has, all of the houses he's delivering presents to... For Santa, the best Christmas present would be being able to see a little bit of a something. For this reason, **the shortest submission in bytes wins**.

## Leaderboard

This is a Stack Snippet that generates both a leaderboard and an overview of winners by language.

To ensure your answer shows up, please start your answer with a headline using the following Markdown template

```
## Language Name, N bytes

```

Where N is the size, in bytes, of your submission

If you want to include multiple numbers in your header (for example, striking through old scores, or including flags in the byte count), just make sure that the actual score is the *last* number in your header

```
## Language Name, <s>K</s> X + 2 = N bytes

```

```
var QUESTION_ID=151568;var OVERRIDE_USER=20634;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 6 votes
# Ruby, ~~433~~ ~~400~~ 392 bytes

Well, this one is indeed hard, because it turns out the elf scheduling is NP hard.

Also, please be nice, this is my first submission, so I might have missed some obvious optimizations:

```
->e,h{h.split(/\+|\n/).map{|h|n,g=h.split(?*).map(&:to_i)+[0,0];return-1if(g>0&&e<2)||(n>0&&e<3);([[3,5]]*n+[[2,4]]*g).permutation.map{|j|c=[0]*e;j.map{|q|w,y=q;i=j=0;r=c.map{|x|a=b=0;c[i..e].map{|r|r<=x ?a+=1:p};(t=i+=1).times{c[t-=1]<=x ?b+=1:p};[a,b]};d=r.inject([]){|k,x|k<<j if x[0]>=w;j+=1;k}.min{|a,b|c[a]<=>c[b]};b=d-r[d][1]+1;z=c[d]+y;(b..(b+w-1)).map{|x|c[x]=z}};c.max}.min||0}.sum}

```

Try it online!

I initially had longer test cases, but because I'm iterating over all possible permutations for the scheduling in some cases it takes to long, so I removed them.

# Answer
> 3 votes
# Java (OpenJDK 8), 344 bytes

Elf scheduling is more difficult than I thought so this took a little while, and is pretty long.

Despite that, this has definitely been my favourite challenge to code golf!

```
(e,d)->{int r=0,x,y,c,p,b,g,m;for(String h:d[0].split("\\+")){d=h.split("\\*",-1);b=new Byte("0"+d[0]);g=new Byte("0"+d[1]);m=-1>>>1;for(y=1;y<=e/3&(x=(e-y*3)/2)>0;c=b/y+(b%y++<1?0:1),p=g/x+(g%x<1?0:1),x=c*5>p*4?c*5:p*4,m=x<m?x:m);for(y=0;b+g>0;b-=c,g-=p){c=e/3<b?e/3:b;x=(e-c*3)/2;p=x<g?x:g;if(c+p<1)return-1;y+=c>0?5:4;}r+=m<y?m:y;}return r;}

```

Try it online (with all tests)!

# Explanation;

*Brace yourself: It's a long one*

```
    int r=0,x,y,c,p,b,g,m;               // Define all the variables I need

    for(String h:d[0].split("\\+")){     // Split houses on '+' and loop through them

        d=h.split("\\*",-1);             // Split the current house on '*' using the limit
                                         // to preserve empty strings.

        b=new Byte("0"+d[0]);            // Parse the naughty (b) and nice (g) people
        g=new Byte("0"+d[1]);

        m=-1>>>1;                        // Initialise minimum time as max integer using
                                         // overflow

        for(y=1;y<=e/3&(x=(e-y*3)/2)>0;  // For each number of elves that can concurrently
                                         // deliver coal, and still leave enough elves to
                                         // deliver presents

            c=b/y+(b%y++<1?0:1),         // Determine the number of runs needed to deliver
                                         // all coal using this number of elves

            p=g/x+(g%x<1?0:1),           // Determine the number of runs needed to deliver
                                         // all presents using this number of elves

            x=c*5>p*4?c*5:p*4,           // Get the maximum time required for the
                                         // delivery of coal or presents

            m=x<m?x:m);                  // If this is less than the current minimum time,
                                         // set it as the minimum time

        for(y=0;b+g>0;b-=c,g-=p){        // While there are still people to deliver to;

            c=e/3<b?e/3:b;               // Determine the max amount of coal to deliver

            x=(e-c*3)/2;                 // Determine how many presents can be
                                         // delivered with the remaining elves.

            p=x<g?x:g;                   // If this number is more than nice people
                                         // remaining, just use the nice people remaining

            if(c+p<1)return-1;           // If no presents can be delivered, return the
                                         // error code (-1)

            y+=c>0?5:4;                  // Increase the time by 5 if coal was
                                         // delivered, and 4 if only presents

        }                                // At the end of each loop (see above)
                                         // remove the presents and coal delivered
                                         // from the number of naughty and nice houses

        r+=m<y?m:y;                      // Increment the total time by which ever
                                         // is smaller of the calculated times
    }
    return r;                            // Return the total time

```

*NB: This answer depends on my corrections to the test cases being correct*

---
Tags: code-golf, string
---


title: Polynomial -> Integrate

text:
# Question
Title: Polynomial -> Integrate
Given a polynomial in one variable with rational coefficients, output an equivalent expression containing only `1`, variables, and definite integrals. For example, -*x*2 can be expressed as ∫*x*111d*t**x*d*u*.

`E := 1 | var | ∫<sub>E</sub><sup>E</sup>Edvar`

Any reasonable input/output method is allowed.

Examples:

Your score will be the your code length multiplied by the number of  symbols used on the test cases. You should be able to score your program. Lowest score wins.

Test cases:

```
4/381*x^2+49/8*x^3-17/6
311/59*x^2-92/9*x^3-7/15*x
333/29*x^3+475/96*x^8

```

> Golfing is going to be difficult, because I can't golf just the code or just the output, and I therefore do not know if a change will help or hurt my score until I try it, which sucks in my opinion.

Don't let the score restrict your creation. You are welcomed to answer with mainly one part of the score well optimized, even if the other one badly left.

# Answer
> 0 votes
# JavaScript (Node.js), 220 bytes * 616 integrals = 135520 score

```
O=[1,T='t',1,1]
D=(q,t)=>[t,'c',[q,T,1,O],q]
N=n=>n>0?[N(-n),T,1,O]:n?[D(1,1),'c',n&1?[T,T,O,1]:O,N(n/2|0)]:O
P=n=>n?[D(n%2?'x':1,T),T,O,P(n>>1)]:1
F=([e,...s])=>e?[1,T,[F(s),T,'x',O],[N(e[0]),T,O,[P(e[1]-1),'x',O,1]]]:O

```

Try it online!

# Answer
> 5 votes
# Python 2, 315 bytes * 5113 = 1610595 score

I'm still working on golfing the score. Golfing is going to be difficult, because I can't golf just the code or just the output, and I therefore do not know if a change will help or hurt my score until I try it, which sucks in my opinion.

Despite the annoyance of golfing this, I did enjoy the calculus.

```
t='t'
Z=lambda n:N(Z(-n))if n<0else[1,t,N(1),Z(n-1)]if n>1else[[1,t,1,1],1][n]
N=lambda a:[1,t,a,Z(0)]
x=lambda n:n>1and[x(n-1),t,Z(0),'x']or'x'
M=lambda a,b:[b,t,Z(0),a]
print reduce(lambda a,b:[1,t,N(a),b],[M((lambda a,b:M(Z(a),[x(b-1)if b>1else 1,'x',Z(0),1]))(*c),x(i)if i else 1)for i,c in enumerate(input())])

```

**Try it online!**

Run all test cases \- to score, count all `[` in the output.

The input polynomial is taken as a list of (numerator, denominator) coefficient pairs in order from lowest to highest power of `x`. `(0, 1)` (zero) is used for missing powers.

Output is given with each integral represented by a list `[f,t,a,b]` to represent ∫ab*f* d*t*

### Verification

**Here** is a slightly less golfed version that outputs valid Mathematica syntax for integration, which may be tested in an online notebook. Unfortunately, decently-sized programs will not complete in a free notebook.

Go here, scroll to bottom, "Create New Notebook", paste (Wolfram Language Input), and evaluate (Shift+Enter) *(Note that using num-pad Enter doesn't work)*.

### Explanation

Uses these equations:

### Links

# Answer
> 1 votes
# JavaScript (Node.js), 152 bytes * 5113 integrals = 777176 score

```
T='t';P=n=>--n?[T,'u',O,P(n)]:1;N=n=>n-1?n>-1?[1,T,N(1-n),1]:[1,T,N(-n),O]:1;O=N(0)
F=([e,...s])=>e?[1,T,[F(s),T,'x',O],[N(e[0]),T,O,[P(e[1]),T,O,1]]]:O

```

Try it online!

Mainly use these two equations:

---
Tags: math, code-challenge, polynomials
---


title: A pile of weights

text:
# Question
Title: A pile of weights
### Challenge:

You'll be given an ASCII image of a pile of weights as input, and must output the combined weight of the pile.

### Format:

There are 5 different weights, weighing **1, 2, 5, 10, 20** Passerees (or some other arbitrary unit).

The weights looks like this, in ascending order:

```
1:   __
    |__|

2:   ______
    |______|

5:   ______
    |      |
    |______|

10:  ______________
    |              |
    |______________|

20:  ____________________
    |                    |
    |____________________|

```

The weighs will be symmetrically placed (as in the example image), not necessarily in a sorted order. Weighs will share boundaries, where applicable:

### Test cases:

You may use all the single weights as test cases too.

```
   __
 _|__|_
|______|
|      |
|______|
1 + 2 + 5 = 8

```

```
 ____________________
|                    |
|____________________|
   |              |
   |______________|
        _|__|_
       |______|
       |      |
       |______|
20 + 10 + 1 + 2 + 5 = 38

```

```
 ______
|______|
|______|
|______|
|______|
2 + 2 + 2 + 2 = 8

```

### Additional rules:

* You may **not** assume additional leading spaces. The largest weight will be all the way to the left.
* You may assume trailing spaces and newlines.
* You may assume there will be maximum 10 weights
* You may take the input on an optional format, but you can't substitute the characters used by something else

This is so the shortest code in bytes each languages wins. Explanations are encouraged as always.

# Answer
# Jelly,  ~~24~~  23 bytes

```
ḟ⁶Ỵẹ€”|IFṚ’œṗ$Ḅ:3“ÇÞ‘yS

```

**Try it online!**

### How?

The weights may be identified by their widths and heights. The widths may be measured by looking at the distance between the line's `|` characters. If we first remove all the spaces then those weights of height two will contribute such a line with a measured width of one.

The different weights have widths of `3, 7, 7, 15, 21` (for weights `1, 2, 5, 10, 20` respectively). Adding a trailing `1` for those of height two we find `[3],[7],[7,1],[15,1],[21,1]` converting from binary these are `3,7,15,31,43`, integer dividing by three gives us `1,2,5,10,14`, which are the weights except `14` needs replacing by `20`.

```
ḟ⁶Ỵẹ€”|IFṚ’œṗ$Ḅ:3“ÇÞ‘yS - Link: list of characters    e.g. <example 2>
 ⁶                      - literal space character
ḟ                       - filter discard
  Ỵ                     - split at new lines
     ”|                 - literal pipe character
   ẹ€                   - get indices for €ach             [[],[1,2],[1,22],[1,2],[1,16],[2,5],[1,8],[1,2],[1,8]]
       I                - incremental differences          [[],[1],[21],[1],[15],[3],[7],[1],[7]]
        F               - flatten                          [1,21,1,15,3,7,1,7]
         Ṛ              - reverse                          [7,1,7,3,15,1,21,1]
             $          - last two links as a monad:
          ’             -   decrement                     [6,0,6,2,14,0,20,0]
           œṗ           -   partition at truthy indices   [[],[7,1],[7],[3],[15,1],[21,1]]
              Ḅ         - convert from binary             [0,15,7,3,31,43]
               :3       - integer divide by three         [0,5,2,1,10,14]
                 “ÇÞ‘   - code-page-indices               [14,20]
                     y  - translate                       [0,5,2,1,10,20]
                      S - sum                             38

```

---

Alternatively replace the measured widths of `21` with `30` prior to the conversion using `“ßœ‘y`:

```
ḟ⁶Ỵẹ€”|IF“ßœ‘yṚ’œṗ$Ḅ:3S

```
> 7 votes

# Answer
# Python 2, 77 bytes

```
lambda x:sum(i/21*x.count('|'+i%21*' _'[i<50]+'|')for i in[23,48,69,224,440])

```

Try it online!

`[i/21, i%21, ' _'[i<50] for i in [23,48,69,224,440]]` will generate the following triplets `[1, 2, '_'], [2, 6, '_'], [3, 6, ' '], [10, 14, ' '], [20, 20, ' ']` that represent the weight, the lenght and the character in the base of each weight, that will be used to make a unique single-line representation of each weight.
Since the 3rd weight would overlap with the 2nd, I replace it's base with it's body (`_` -\> ) and reduced the value to `3` (it will count the base as `2` and the body as `3`, resulting in `5`)
> 4 votes

# Answer
# Retina 0.8.2, 60 bytes

```
T`|`!
!__!
1
!_{6}!
11
! {6}!
3$*
!.{14}!
5$*
!.{20}!
10$*
1

```

Try it online! Explanation: The `|`s are replaced with `!`s for ease of matching, then the weights are converted into unary and totalled. The only interesting portion is that the `5` weight is considered to be the sum of a `2` and a `3` weight, while the `10` and `20` weights are just two lines of half the weight.
> 4 votes

# Answer
# JavaScript (Node.js), 73 bytes

```
x=>x.replace(/\|.*\|/g,s=>u+=s.length/4*(s[1]<1?s[21]?29/11:1.5:1),u=0)|u

```

Try it online!
> 3 votes

# Answer
# Python 3, 76 bytes

```
lambda t:sum([1,2,3,5,5,9,11][len(x)//4+(x<'_')]for x in t.split('|')[1::2])

```

Try it online!

### How?

```
sum([1,2,3,5,5,9,11][len(x)//4+(x<'_')]for x in t.split('|')[1::2])
                                                t.split('|')         - split ascii art into pieces
                                                            [1::2])  - weights are at odd indexes
                                       for x in                      - iterates over the weights
                     len(x)//4                                       - map widths to 0,1,3,5,7
                              +(x<'_')                               - add 1 if the first row of 2-row weight
    [1,2,3,5,5,9,11][                 ]                              - value of each part of a weight
sum(                                                              )  - add 'em all up

```
> 2 votes

# Answer
I'm sure there are some improvements to be made, but this is what I have at the moment:

# Groovy, 131 bytes

`def f(s){s.split('\n').sum{n=0;[2:1,6:2,14:5,20:10].each{k,v->if(it==~".*\\|[ _]{$k}\\|.*"){n=v+(!it.contains('_')&&k==6?1:0)}};n}}`

Converts the input `String` into a `Collection<String>` and then sums the results for each line to get the total. Uses a `Map` where the key is the number of spaces or underscores in between the pipe characters and the value is the corresponding Passerees amount. The key is plugged into the regex to determine if the line matches a significant pattern. The one caveat is the ternary to add 1 in the case where the length of the substring between the pipes is 6 and is composed of spaces (as opposed to underscores). If no pattern matches, the line has a value of 0.
> 1 votes

# Answer
# Perl 6, 57 bytes

```
{sum map {.comb+>2*(1.5,3)[.comb>16]**!/_/},m:g/\|.*?\|/}

```

Try it online!
> 0 votes

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


title: Prime Factor Encoding

text:
# Question
Title: Prime Factor Encoding
# How the encoding works

Given a list of bits:

* Hold a prime (starting with `2`)
* Have a list
* For each bit in the input
    + If it's the same as the previous bit, add the prime you're holding to the list
    + If it's different, hold the next prime and add that to the list
* Return the product of all the numbers in your list
* For the first bit, assume the previous bit was `0`

> Note: these steps are for illustration purposes only, you are not required to follow them.

# Examples

```
Input: 001
hold 2

0:         add 2 to the list
0:         add 2 to the list
1: hold 3, add 3 to the list

list: 2,2,3
Output: 12

```

---

```
Input: 1101
hold 2

1: hold 3, add 3 to the list
1:         add 3 to the list
0: hold 5, add 5 to the list
1: hold 7, add 7 to the list

list: 3,3,5,7
Output: 315

```

### Some more examples:

```
000000000 -> 512
111111111 -> 19683
010101010 -> 223092870
101010101 -> 3234846615
011101101 -> 1891890
000101101010010000 -> 3847834029582062520

```

# Challenge

Write an encoder **and** a decoder for this encoding method.

(The decoder reverses the process of the encoder).

# Input / Output

* The encoder can take input in any reasonable format
* The encoder must output either an integer or a string
* The decoder must take input in the same format that the encoder outputs
* The decoder must output the same format that the encoder takes as input

In other words `decoder( encoder( input ) ) === input`

### Notes

* The decoder may assume that its input is decodable
* Your answer only has to deal with integers that your language can natively support without using (`long`, `bigInt`, etc.), be reasonable, if you language only supports ints up to 1, maybe reconsider posting an answer

# Scoring

Your score is the sum of the lengths in bytes of the encoder and decoder.

If you need to import a module, the import can be counted only once provided that your encoder and decoder can coexist in the same file and be reused (like functions).

Default loopholes are forbidden.

This is so the shortest score for every language wins.

# Answer
# 05AB1E, 13 bytes

## Encoder, 8 bytes

```
0ì¥ĀηOØP

```

Try it online!

**Explanation**

```
0ì          # prepend 0 to input
  ¥         # calculate deltas
   Ā        # truthify each
    η       # calculate prefixes
     O      # sum each
      Ø     # get the prime at that index
       P    # product

```

## Decoder, 5 bytes

```
Ò.ØÉJ

```

Try it online!

**Explanation**

```
Ò       # get prime factors of input
 .Ø     # get their indices among the primes
   É    # check for oddness
    J   # join

```
> 8 votes

# Answer
# Jelly, 17 bytes

### Encoder (10 bytes):

```
0;IA+\‘ÆNP

```

**Try it online!**

### Decoder (7 bytes):

```
ÆEĖŒṙḂ¬

```

**Try it online!**

### How?

Encoder:

```
0;IA+\‘ÆNP - Link: list of integers (1s and 0s)  e.g. [1,1,1,1,0]
0;         - prepend a zero                           [0,1,1,1,1,0]
  I        - incremental differences                  [1,0,0,0,-1]
   A       - absolute values                          [1,0,0,0,1]
    +\     - cumulative reduce with addition          [1,1,1,1,2]
      ‘    - increment each of the results            [2,2,2,2,3]
       ÆN  - get the nth prime for each result        [3,3,3,3,5]
         P - product of the list                      405

```

Decoder:

```
ÆEĖŒṙḂ¬ - Link: integer         e.g. 405
ÆE      - prime exponent array       [0,4,1] (representing 2^0*3^4*5^1)
  Ė     - enumerate                  [[1,0],[2,4],[3,1]]
   Œṙ   - run-length decode          [2,2,2,2,3]
     Ḃ  - bit (mod 2)                [0,0,0,0,1]
      ¬ - logical NOT                [1,1,1,1,0]

```
> 7 votes

# Answer
# JavaScript (ES6), 130 bytes

**I/O:** array of bits ↔ integer

## Encoder, 71 bytes

```
a=>a.map(p=k=>r*=(g=i=>n%--i?g(i):i<2?n:g(++n))(n+=p^(p=k)),r=1,n=2)&&r

```

Try it online!

## Decoder, 59 bytes

```
D=(n,k=2,x=b=0)=>k>n?[]:n%k?D(n,k+1,1):[b^=x,...D(n/k,k,0)]

```

Try it online!
> 5 votes

# Answer
# Python 2, ~~234~~ ~~193~~ 174 bytes

## Encoder, ~~116~~ ~~101~~ 97 bytes:

Uses Wilson's theorem.

```
i=input()
P=n=x=r=1
while i:
 P*=n*n;n+=1
 if P%n:t=(i+[x]).index(x);i=i[t:];r*=n**t;x^=1
print r

```

Try it online!

## Decoder, ~~118~~ ~~92~~ 77 bytes:

```
i=input()
r=[]
n=x=1
while~-i:
 n+=1;x^=i%n<1
 while i%n<1:r+=x,;i/=n
print r

```

Try it online!
> 3 votes

# Answer
# Java 10, 209 bytes

## Encoder, 124 bytes

```
s->{long p=48,P=2,r=1,n,i;for(int c:s.getBytes()){if(p!=(p=c))for(n=0;n<2;)for(n=++P,i=2;i<n;n=n%i++<1?0:n);r*=P;}return r;}

```

Try it online.

**Explanation:**

```
s->{                // Method with String parameter and long return-type
  long p=48,        //  Previous character, starting at '0'
       P=2,         //  Current prime, starting at 2
       r=1,         //  Result, starting at 1
       n,i;         //  Temp-integers
  for(int c:s.getBytes()){
                    //  Loop over the digits of the input-String as bytes
    if(p!=(p=c))    //   If the current and previous digits are different
      for(n=0;      //    Reset `n` to 0
          n<2;)     //    And loop as long as `n` is still 0 or 1
        for(n=++P,  //     Increase `P` by 1 first with `++P`, and set `n` to this new `P`
            i=2;i<n;n=n%i++<1?0:n);
                    //     Check of the current `n` is a prime
                    //     If it remains the same it's a prime, if it becomes 0 or 1 not
    r*=P;}          //   Multiply the result by the current prime `P`
  return r;}        //  Return the result

```

## Decoder, 85 bytes

```
n->{var r="";for(long P=2,f=0,i=1;++i<=n;)for(;n%i<1;n/=P=i)r+=i!=P?f^=1:f;return r;}

```

Try it online.

**Explanation:**

```
n->{                // Method with long parameter and String return-type
  var r="";         //  Result-String, starting empty
  for(long P=2,     //  Current prime, starting at 2
      f=0,          //  Flag integer, starting at 0
      i=1;++i<=n;)  //  Loop `i` in the range [2,`n`]
    for(;n%i<1;     //   Inner loop over the prime factors of `n`
        n/=P=i)     //     After every iteration: divide `n` by `i`,
                    //     and set `P` to `i` at the same time
      r+=i!=P?      //    If `i` and `P` are not the same
          f^=1      //     Append the opposite of the flag `f` (0→1; 1→0)
         :          //    Else:
          f;        //     Append the flag `f`
  return r;}        //  Return the result

```
> 3 votes

# Answer
# Husk, 18 bytes

### Encoder, 11 bytes

```
Πmo!İp→∫Ẋ≠Θ

```

Try it online!

### Decoder, 7 bytes

```
mȯ¬%2ṗp

```

Try it online!

### How they work

Encoder:

```
Πmo!İp→∫Ẋ≠Θ – Full program. Takes input from the first CLA, outputs to STDOUT.
          Θ – Prepend a default element (0 in this case).
        Ẋ≠  – Map over pairs of adjacent elements with ≠ (not equals). In Husk,
              some operators return other useful things than just boolean values.
              Here, ≠ returns the absolute difference between its two arguments.
       ∫    – Cumulative sums.
 mo         – Map the following function over the list of sums:
    İp        – Yield the infinite list of primes.
   !  →       – And index into it with the current sum incremented.
Π           – Take the product.

```

Decoder:

```
mȯ¬%2ṗp – Full program.
      p – Prime factorization.
mȯ      – Map the following function over the list of factors:
     ṗ    – Retrieve the index in  the list of primes.
   %2     – Modulo 2.
  ¬       – Logical NOT.

```
> 3 votes

# Answer
# C (gcc), ~~180~~ 184 bytes

* Added four bytes so that output formats match.

# 102 bytes -- Encoder

```
p,r,i,m;e(char*_){for(m=0,p=1,i=2;*_;m=*_++-48,p*=i)if(*_-48-m)for(i++,r=2;r<i;i%r++||(r=2,i++));i=p;}

```

Try it online!

# 82 bytes -- Decoder

```
d(C){for(m=C%2,r=2+m,p=2;C>1;p++)if(C%p<1)p-r&&(m=!m,r=p),putchar(m+48),C/=p,p=1;}

```

Try it online!
> 1 votes

# Answer
# , 34 bytes

Heavily inspired by Jonathan Allan's Jelly solution!

## Encoder: 23 bytes

```
[:*/[:p:[:+/\2|@-~/\0,]

```

Try it online!

```
                    0,]  NB. prepend 0 to the input
             2  -~/\     NB. find the differences
              |@         NB. and their absolute values
        [:+/\            NB. running sums
    [:p:                 NB. n-th prime
[:*/                     NB. product

```

I don't like those many cap forks `[:` \- it should be golfable.

## Decoder: 11 bytes

```
2|[:_1&p:q:

```

Try it online!

```
        q:    NB. prime factorization
  [:_1&p:      NB. find the number of primes smaller than n
2|             NB. modulo 2

```
> 1 votes

# Answer
# Jelly, 15 bytes

### Encoder, 9 bytes

```
0;ŒgL€ÆẸH

```

Try it online!

### Decoder, 6 bytes

```
Æf’ÆCḂ

```

Try it online!
> 1 votes

# Answer
# Gol\>\<\>, 29 + 39 = 68 bytes

## Encoder, 29 bytes

```
021IEh{$:}-Q$TP:SP?!t$|1k*3R!

```

Try it online!

## Decoder, 39 bytes

```
02I:MZ;:2k%:z}Q$TP:SP?!t$|1k,{{-z:N}3R!

```

Try it online!

### How these work

```
Encoder

021IEh{$:}-Q$TP:SP?!t$|1k*3R!

021                            Setup the stack as [last bit, current prime, current output]
   IEh                         Take input as int; if EOF, print top as number and halt
      {$:}-Q          |        If the next bit is different from the last bit...
            $                    Move the prime to the top
             T      t            Loop indefinitely...
              P:SP?!               Increment; if prime, skip `t` i.e. break
                     $           Move the prime to the correct position
                       1k*     Multiply the prime to the output
                          3R!  Skip 3 next commands (the init part)
                               Loop the entire program until EOF

---

Decoder

02I:MZ;:2k%:z}Q$TP:SP?!t$|1k,{{-z:N}3R!

02I                  Setup the stack as [last bit, current prime, encoded]
   :MZ;              If encoded == 1, halt
       :2k%          Compute encoded modulo prime
           :z}       Store NOT of the last at the bottom of the stack
              Q...|  Same as encoder's next-prime loop
1k,                  Divide encoded by prime (assume it is divisible)
   {{                Pull out the two bits at the bottom
     -z              Compute the next bit
       :N}           Print as number with newline, and move to the bottom
          3R!        Skip 3 init commands
                     Loop the entire program until finished

```

It'd be better if I could golf down the next-prime loop...
> 1 votes

---
Tags: code-golf, primes, factoring, encoding
---


title: Creating a Y-shaped Recursive Tree

text:
# Question
Title: Creating a Y-shaped Recursive Tree
**Challenge**

In this challenge you will construct trees, in the form of ASCII Art using recursion. Basically you will generate the ASCII version of the Fractal Tree

**Input**

* Number of iterations `0 < N <= 5`

**Output**

* The `Nth` iteration of the Fractal Tree. It must be a matrix of 63 rows and 100 columns. (i.e. 6300 printable characters) It should be composed entirely of underscores and ones.

**Rules**

* Tree must be Y-shaped
* Input `0 < N <= 5`
* It must be a matrix of `63 rows` and `100 columns`
* It must be composed entirely of underscores `_` and ones `1`
* Do not include any extra leading or trailing spaces.

---

## Examples

**N = 1**

```
[encoded data, 6300 characters]

```

**N = 2**

```
[encoded data, 6300 characters]

```

**N = 5**

```
[encoded data, 6300 characters]

```

---

This is , so the shortest answer in bytes win.

# Answer
> 1 votes
# Python 2, ~~902~~ ~~518~~ 472 bytes

```
u='_';n='1';c=(31,47,55,59,62)[input()-1]
p=[u*100]*64+[u*18+'1_'*32+u*18]+[u*19+'1___'*15+n+u*20]*2+[u*20+'1_1_____'*8+u*16]+[u*21+(n+u*7)*8+u*15]*3+[u*22+(n+u*5+n+u*9)*4+u*14]+[u*23+('1___1'+u*11)*4+u*13]+[u*24+('1_1'+u*13)*4+u*12]+[u*25+(n+u*15)*4+u*11]*4
m=13;r=17
for x in range(26,33):p+=[u*x+n+u*m+n+u*r+n+u*m+n+u*(x+1)];m-=2;r+=2
p+=[u*33+n+u*31+n+u*34]*9
m=29
for x in range(34,49):p+=[u*x+n+u*m+n+u*(x+1)];m-=2
p+=[u*49+n+u*50]*16
print'\n'.join(p[:63-c]+p[-c:])

```

Try it online!

Needs a whole load of golfing but at least it works.

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


title: Braille graphics

text:
# Question
Title: Braille graphics
Cut a boolean matrix in 4x2 blocks and render them as Braille characters `U+2800`...`U+28FF`.

```
[[0,1,0,0,1,0],
 [1,0,0,0,0,0],
 [1,0,0,0,1,0],
 [1,1,1,1,0,0]]

⣎⣀⠅

```

Pad with 0-s if dimensions are not multiples of 4 and 2.

```
[[0,1,0],
 [1,0,0],
 [1,1,1]]

⠮⠄

```

Usual golfing rules apply, flexible on input format. Output should either have the structure of a matrix or look like a matrix, e.g. list of strings; single string with newlines.

Hint: `chr(0x2800 + 128*b7 + 64*b6 + 32*b5 + 16*b4 + 8*b3 + 4*b2 + 2*b1 + b0)` is the dot pattern

```
b0 b3
b1 b4
b2 b5
b6 b7

```

Larger test:

```
[[0,0,1,1,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,1,0],
 [0,1,1,1,1,1,1,0,0,0,0,0,1,1,1,0,0,0,1,1,1,1,1],
 [0,1,1,0,0,1,1,1,0,0,0,1,1,1,1,0,0,1,1,0,0,0,1],
 [1,1,0,0,0,0,1,1,0,0,0,0,0,0,1,0,0,1,1,0,0,1,1],
 [1,1,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,1,1,1,0,1,0],
 [1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,1,0,0,0],
 [1,1,0,1,1,1,1,1,1,0,0,0,0,0,1,0,0,0,0,1,0,0,0],
 [1,1,0,1,1,1,1,1,0,0,1,1,0,0,1,0,0,1,1,1,1,1,1],
 [1,1,0,1,1,1,1,0,0,1,1,1,1,0,1,0,1,1,1,1,1,1,0],
 [1,1,0,1,0,1,1,0,1,1,0,1,1,0,1,0,0,0,0,1,1,0,0],
 [1,1,0,0,0,1,1,0,1,0,0,0,1,0,1,1,0,0,0,1,1,0,0],
 [1,1,0,0,0,1,1,0,1,0,0,0,1,0,1,1,1,0,0,1,1,0,0],
 [0,1,1,0,1,1,1,0,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0],
 [0,1,1,1,1,1,0,0,1,1,1,1,1,0,0,1,1,0,1,1,1,0,0],
 [0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,0,1,1,1,1,0]]

⣰⠟⠻⣦⠀⠠⠾⡇⢠⡞⢛⡆
⣿⢠⣬⣥⠄⣀⠀⡇⢈⣻⣈⡀
⣿⠘⢹⡇⡞⠙⡇⣧⡉⢹⡏
⠘⠷⠟⠁⠳⠾⠃⠘⠇⠾⠧

```

# Answer
# Jelly,  ~~31~~  30 bytes

```
sz0Z
ç€2ZF€ç€8Zœ?@€€-36Ḅ+⁽$ṁỌY

```

**Try it online!**

### How?

```
sz0Z - Link 1, split & right-pad with zeros: list, items; number, chunkSize
s    - split items into chunks of length chunkSize
 z0  - transpose with filler zero
   Z - transpose

ç€2ZF€ç€8Zœ?@€€-36Ḅ+⁽$ṁỌY - Main link: list of lists of numbers (1s & 0s), M
ç€2                       - call the last link (1) as a dyad for €ach (left=M, right=2)
                          -  ((left,right) bits read left-right then top-bottom)
   Z                      - transpose the resulting list of lists of lists
                          -  ((left, right) bits read top-bottom then left-right)
    F€                    - flatten €ach
      ç€8                 - call the last link (1) as a dyad for €ach (left=^, right=8)
         Z                - transpose the resulting list of lists of lists
                          -  ("blocks" each and all read left-right top-to bottom)
               -36        - literal -36
             €€           - for €ach (block-wise row) for €ach (block)
          œ?@             -   lexicographical permutation with reversed arguments
                          -    (get the permutation at index -36 (modular) in a list of
                          -     all permutations of the indexes sorted lexicographically.
                          -     That is the 8!-36 = 40284th - equivalently the values at
                          -     indexes [8,7,6,4,2,5,3,1])
                  Ḅ       - convert from binary list to integer (vectorises)
                    ⁽$ṁ   - base 250 literal = 10240
                   +      - add
                       Ọ  - cast to character (vectorises)
                        Y - join with newlines
                          - implicit print

```
> 10 votes

# Answer
# Mathematica, ~~126~~ ~~110~~ ~~97~~ 90

```
FromCharacterCode[10240+ListCorrelate[2^{{0,3},{1,4},{2,5},{6,7}},#,1,0][[;;;;4,;;;;2]]]&

```

---

This solution takes advantage of `ListCorrelate` to convolve a (reversed) kernel over a matrix, which is essentially a sliding matrix multiplication (or dot product). See a visual explanation here. Padding is done by using `0` as the fourth argument. In the following example, we expect the result to match the hint above:

```
ListCorrelate[
  2^{{0, 3}, {1, 4}, {2, 5}, {6, 7}},
  {{b0, b3}, {b1, b4}, {b2, b5}, {b6, b7}}
]

(* returns {{b0 + 2 b1 + 4 b2 + 8 b3 + 16 b4 + 32 b5 + 64 b6 + 128 b7}} *)

```

Note that `ListConvolve` is not any shorter, since the third argument would be `-1`.

Since this applies the kernel at every position of the matrix, we just need to extract the elements in every fourth row and second column. We use shorthands for `Span` and `Part`: `[[;;;;4,;;;;2]]`.

Helpfully, `FromCharacterCode` can take a matrix of character codes and return a list of strings.

---

This solution returns a list of strings, which is one of the allowed output formats. Simply prepend `Column@` for the output to “look like a matrix.”

---

You can play around with this in a free online Mathematica notebook. Go here, click Create a New Notebook, wait a moment, paste in this code, then press `shift+enter`.

```
m1={{0,1,0,0,1,0},{1,0,0,0,0,0},{1,0,0,0,1,0},{1,1,1,1,0,0}};
m2={{0,1,0},{1,0,0},{1,1,1}};
m3={{0,0,1,1,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,1,0},{0,1,1,1,1,1,1,0,0,0,0,0,1,1,1,0,0,0,1,1,1,1,1},{0,1,1,0,0,1,1,1,0,0,0,1,1,1,1,0,0,1,1,0,0,0,1},{1,1,0,0,0,0,1,1,0,0,0,0,0,0,1,0,0,1,1,0,0,1,1},{1,1,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,1,1,1,0,1,0},{1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,1,0,0,0},{1,1,0,1,1,1,1,1,1,0,0,0,0,0,1,0,0,0,0,1,0,0,0},{1,1,0,1,1,1,1,1,0,0,1,1,0,0,1,0,0,1,1,1,1,1,1},{1,1,0,1,1,1,1,0,0,1,1,1,1,0,1,0,1,1,1,1,1,1,0},{1,1,0,1,0,1,1,0,1,1,0,1,1,0,1,0,0,0,0,1,1,0,0},{1,1,0,0,0,1,1,0,1,0,0,0,1,0,1,1,0,0,0,1,1,0,0},{1,1,0,0,0,1,1,0,1,0,0,0,1,0,1,1,1,0,0,1,1,0,0},{0,1,1,0,1,1,1,0,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0},{0,1,1,1,1,1,0,0,1,1,1,1,1,0,0,1,1,0,1,1,1,0,0},{0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,0,1,1,1,1,0}};

MatrixToBraille := Column@
  FromCharacterCode[10240+ListCorrelate[2^{{0,3},{1,4},{2,5},{6,7}},#,1,0][[;;;;4,;;;;2]]]&

MatrixToBraille/@{m1,m2,m3}

```

Then you should see this:

>
> 7 votes

# Answer
# JavaScript ES7 ~~210~~ ~~207~~ ~~201~~ ~~200~~ ~~198~~ ~~194~~ ~~185~~ 183 bytes

```
a=>eval('for(y=0,c="";A=a[y];y+=4,c+=`\n`)for(x=0;A[x]+1;x+=2)c+=String.fromCharCode(10240+eval("for(N=k=0;k<6;k++)N+=(g=(X,Y=3)=>(a[Y+y]||0)[X+x]|0)(k>2,k%3)*2**k")|g(0)+g(1)*2<<6)')

```

4 bytes saved thanks to ngn

3 bytes saved thanks to Luke

# How it works

I'm going to split the code up into parts and speak about them separately:

```
for(y=x=0, c=""; a[y]; x+=2)
    !((a[y] || [])[x]+1) && (y+=4,x=0,c+=`\n`)

```

This is where every variable gets declared. `x` and `y` is the position of the "cursor" (the upper left edge of the current braille character). The x coordinate increases by 2 every iteration, and it stops, when there's no row with the index `y` (a\[x\] returns `undefined` if it doesn't exist, which gets converted to false).

There are multiple tricks in the second row. `(a[y] || [])[x]` ensures that looking up the value at the `(x, y)` position doesn't throw an error. The `&&` is the usual and operator, and it only checks the right side of the expression, if the left was true. This can be translated to

```
if (!((a[y] || [])[x] + 1))
    y+=4,x=0,c+=`\n`

```

The next part:

```
c+=String.fromCharCode(10240+eval("for(N=k=0;k<6;k++)N+=(g=(x,y)=>(a[y]||[])[x]||0)(~~(k/3)+x,k%3+y)*2**k,N")+g(x,y+3)*64+g(x+1,y+3)*128)

```

`String.fromCharCode` simply converts the passed number to a unicode character with the same character code. The expression in the parentheses calculates the index of the Braille character:

```
for(N=k=0;k<6;k++)N+=(g=(x,y)=>(a[y]||[])[x]||0)(~~(k/3)+x,k%3+y)*2**k

```

Goes through the position in the

```
1 4
2 5
3 6

```

order, multiplies the values at those positions with 2i, where i is the index and adds them together. The

```
g=(x,y)=>(a[y]||[])[x]||0

```

part declares a lambda function called `g`, which given an `x` and `y` coordinate returns either the value at the `(x, y)` position or 0 if the position lies outside the bounds of the array.

```
+g(x,y+3)*64+g(x+1,y+3)*128

```

This part adds up the last two positions with the correct weights using the function defined a bit earlier.

Last but not least, the

```
a=>eval('...')

```

part has 2 functions. It defines an anonymous lambda and ensures, that the for loop doesn't cause any problems (a single line lambda such as this one can't contain a single for loop only, an evaluation circumvents this).
> 6 votes

# Answer
# Dyalog APL, ~~133~~ ~~122~~ ~~114~~ ~~112~~ ~~101~~ ~~100~~ ~~98~~ ~~95~~ ~~94~~ ~~93~~ ~~90~~ ~~88~~ 86 bytes

Assumes `⎕IO←0`

```
{C⍴{⎕UCS 10240+2⊥(∊S⌷⍨⍵+⍳¨A)[⍎¨⍕76531420]}¨(,b)/,⍳⍴b←{0 0≡A|⍵}¨⍳⍴S←⍵↑⍨A×C←⌈(⍴⍵)÷A←4 2}

```

-~~8~~ ~~9~~ 12 bytes thanks to @Adám in chat

-2 bytes thanks to @ngn

Try it online!

## How (input is )?

* `A←4 2`, store the vector `4 2` in variable `A`
* `(⍴⍵)÷`, the dimensions of  divided by `A`
* , ceiling
* `C←`, stored in `C`
* , multiplied by `A`
* `⍵↑⍨`, fit  to those dimensions
* `S←`, stored in `S`
* `⍳⍴`, indexes of `S`
* `{0 0≡A|⍵}¨`, `1` where the top left of a cell is, `0` everywhere else
* `(,b)/,⍳⍴b←`, truthy indexes
* `{⎕UCS 10240+2⊥(∊S⌷⍨⍵+⍳¨A)[⍎¨⍕76531420]}¨`, turn each element into braille
* `C⍴`, reshape the dimensions to `C`
> 5 votes

# Answer
# Python 2 \+ drawille, ~~141~~ ~~125~~ ~~120~~ 116 bytes

Saved 16 bytes thanks to ngn and L3viathan

Saved 5 bytes thanks to L3viathan

Saved 4 bytes thanks to ngn

```
from drawille import*
def a(d,c=Canvas(),e=enumerate):[c.set(j,i)for i,x in e(d)for j,y in e(x)if y];print c.frame()

```

Try it online!

tio does not have drawille installed so it does not work
> 4 votes

# Answer
# JavaScript, 136 bytes

```
a=>(b=a.map(x=>[]),a.map((l,i)=>l.map((c,j)=>b[i>>2][j>>1]|=c<<'01263457'[i%4+j*4%8])),b.map(l=>l.map(c=>String.fromCharCode(10240+c))))

```

Thanks to ngn, using bit shifts save 4 bytes.
> 4 votes

# Answer
# APL (Dyalog), ~~57~~ 54 bytes\*

-3 thanks to OP. Prompts for Boolean matrix. Prints character matrix.

```
1↓⎕UCS{2⊥40,⌽(,⍉3↑⍵),⊢⌿⍵}⌺(2 2⍴4 2)⊢0⍪⍣3⍪∘0⍣3⊢⎕,0

```

Try it online!

`⎕,0` append a zero on right (ignored if even number of columns)

yield that (to separate `3` and )

`⍪∘0⍣3` append zeros on bottom thrice (because  drops partial windows)

`0⍪⍣3` stack zeros on top thrice (because  starts in the top left corner)

yield that (separates the parenthesis and the `0`)

`{``}⌺(2 2⍴4 2)` on each 4-row 2-column window, with 4-row vertical and 2 row horizontal step:

`⊢⌿⍵` last row (lit. vertical right reduction); `[b6,b7]`

`(``),` prepend:

`3↑` take three rows; `[[b0,b3],[b1,b4],[b2,b5]]`

transpose; `[[b0,b1,b2],[b3,b4,b5]]`

`,` ravel; `[b0,b1,b2,b3,b4,b5]`

now we have `[b0,b1,b2,b3,b4,b5,b6,b7]`

reverse; `[b7,b6,b5,b4,b3,b2,b1,b0]`

`40,` prepend 40 (for 40×29 = 10240); `[40,b7,b6,b5,b4,b3,b2,b1,b0]`

`2⊥` evaluate as base-2 (binary)

`⎕UCS` convert to character

`1↓` drop the first row (all-zero because of 's padding)

---

* In Classic, counting  as `⎕U233A`.
> 3 votes

# Answer
# Haskell, 145 bytes

```
(a!b)c=take b$c++repeat a
r([]:_)=[]
r l=['⠀'..]!!(sum.zipWith(*)[1,8,2,16,4,32,64,128]$l>>=0!2):r(drop 2<$>l)
b[]=[]
b s=r(([]!4)s):b(drop 4s)

```

Try it online!
> 3 votes

# Answer
# Python 3, ~~168~~ ~~165~~ 161 bytes

```
def f(m):
 while m:
  r,m,s=[*zip(*m)],m[4:],''
  while r:s+=chr(10240+sum(q<<int(w)for(q,w)in zip((r[0]+(0,)*3)[:4]+(r+[()])[1],'01263457')));r=r[2:]
  print(s)

```

Try it online!
> 2 votes

# Answer
# Python 3, 169 bytes

```
a=[]
y=0
for l in eval(input()):
 y-=1;a+=y%4//3*[-~len(l)//2*[10240]];x=0
 for v in l:a[-1][x//2]|=v<<(6429374>>y%4*6+x%2*3&7);x+=1
for l in a:print(*map(chr,l),sep='')

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog), 53 bytes

```
4 2∘{⎕ucs 2⊥40⍪(⍎¨⍕76531420)∘.⊃,¨⍺∘↑¨↓∘⍵¨⍺∘×¨⍳⌈⍺÷⍨⍴⍵}

```

Try it online!
> 2 votes

# Answer
# Perl 5, 164 bytes

163 bytes of code + 1 flag `-p`

```
@a=eval}{for(;$r<@a;$r+=4){for($c=0;$c<@{$a[0]};$c+=2){$n="0b";map$n.=0|$a[$r+3][$c+$_],1,0;for$y(1,0){map$n.=0|$a[$r+$_][$c+$y],2,1,0}$\.=chr 0x2800+oct$n}$\.=$/}

```

Try it online!

Takes each row comma separated on one line.
> 1 votes

---
Tags: code-golf, ascii-art, unicode, binary-matrix
---


title: It's bulking season

text:
# Question
Title: It's bulking season
The barbells at my gym look like this:

```
=========[]-----------------------[]=========

```

They can hold plates of five different sizes, 2.5 pounds, five pounds, ten pounds, 25 pounds, and 45 pounds:

```
                .
        .   !   |
.   !   |   |   |
|   |   |   |   |
'   !   |   |   |
        '   !   |
                '

```

For safety, we also add a clip `]` or `[` on the outside of all of our plates if there are any. The bar itself weighs 45 pounds. We always put the heaviest plates closest to the center, with no gaps between any plates, and put identical plates on both sides. We also always use the minimum number of plates possible, e.g. we never use two five-pound plates on one side instead of a single ten-pound plate. So if I want to lift 215 pounds, my bar looks like this:

```
        .                           .
      .!|                           |!.
     !|||                           |||!
====]||||[]-----------------------[]||||[====
     !|||                           |||!
      '!|                           |!'
        '                           '

```

Your code, a function or complete program, must take an integer from 45 to 575, always a multiple of 5, and output the bar that adds up to that weight. For example:

Input: `45`

Output (note there are no clips on an empty bar):

```
=========[]-----------------------[]=========

```

Input: `100`

Output:

```
        !                           !
       .|                           |.
======]||[]-----------------------[]||[======
       '|                           |'
        !                           !

```

Input: `575`

Output:

```
    .....                           .....
  .!|||||                           |||||!.
 !|||||||                           |||||||!
]||||||||[]-----------------------[]||||||||[
 !|||||||                           |||||||!
  '!|||||                           |||||!'
    '''''                           '''''

```

You can have trailing spaces on each line or not, but your output cannot have leading or trailing empty lines (the output for 45 should be one line, for 50 should be three lines, for 65 should be five lines, and so on.)

This is code golf, shortest code wins!

# Answer
> 1 votes
# Pyth, 126 bytes

```
K[Z5TyT50 90)jfrT6.e::++J+?qk3\=dsm@bxKdhfqQ+45sTSSM^K8?qk3r"[]23-[]"9*27d_J"=\|""]|""\|=""|["c7s@L". !|='"jC"¾ª±À£¤¯aàI7"6

```

The source code contains unprintable characters, so here it is as an XXD dump:

```
0000000: 4b5b 5a35 5479 5435 3020 3930 296a 6672  K[Z5TyT50 90)jfr
0000010: 5436 2e65 3a3a 2b2b 4a2b 3f71 6b33 5c3d  T6.e::++J+?qk3\=
0000020: 6473 6d40 6278 4b64 6866 7151 2b34 3573  dsm@bxKdhfqQ+45s
0000030: 5453 534d 5e4b 383f 716b 3372 225b 5d32  TSSM^K8?qk3r"[]2
0000040: 332d 5b5d 2239 2a32 3764 5f4a 223d 5c7c  3-[]"9*27d_J"=\|
0000050: 2222 5d7c 2222 5c7c 3d22 227c 5b22 6337  ""]|""\|=""|["c7
0000060: 7340 4c22 2e20 217c 3d27 226a 4322 04be  s@L". !|='"jC"..
0000070: aa1f b1c0 a3a4 81af 61e0 4937 2236       ........a.I7"6

```

This code is **extremely slow**, to the point of no actual use. You can speed it up by about 1000 times by adding a `.{` (`set`) call in between, while keeping the code functionally equivalent. Here's a copy-paste friendly version of the resulting code:

```
K[Z5TyT50 90)jfrT6.e::++J+?qk3\=dsm@bxKdhfqQ+45sTS.{SM^K8?qk3r"[]23-[]"9*27d_J"=\|""]|""\|=""|["c7s@L". !|='"j96235640060099376576144045263159 6

```

# Answer
> 2 votes
# Python 2, 295 bytes

```
i=input()-45
w=90,50,20,10,5;p=".|||||'"," !|||! "," .|||' ","  !|!  ","  .|'  "
a=[' '*46]
b=zip(*a*3+['='*9+'[]'+'-'*24+'[]'+'='*9]+a*3)
v=8
j=0
while i:
 if i>=w[j]:i-=w[j];b[v]=b[-v-1]=p[j];v-=1
 else:j+=1
if v<8:b[v]=b[10];b[-v-1]=b[9]
for l in zip(*b):
 L=''.join(l).rstrip()
 if L:print L

```

Builds the bar vertically, then rotates and prints non-empty lines.

# Answer
> 1 votes
# Charcoal, 65 bytes

```
¹²[]Ｐ×=⁹≔⁻Ｎ⁴⁵θＷΦ⟦⁵χ²⁰¦⁵⁰¦⁹⁰⟧¬›κθ«Ｐ|§⪪”{⊞⧴＆β1←Z↶ＲΣ”,Ｌι→Ｐ[≧⁻⊟ιθ»‖Ｂ←

```

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

```
¹²[]Ｐ×=⁹

```

Print 12 `-`s, the `[]` and 9 `=`s. This comprises half of the bar. The cursor is left at the beginning of the `=`s.

```
≔⁻Ｎ⁴⁵θ

```

Subtract 45 from the input to allow for the weight of the bar.

```
ＷΦ⟦⁵χ²⁰¦⁵⁰¦⁹⁰⟧¬›κθ«

```

Filter a list of the possible weights of pairs of weights for those that are not greater than the input, and repeat while the list is not empty.

```
Ｐ|§⪪”{⊞⧴＆β1←Z↶ＲΣ”,Ｌι

```

Split the string `|||.,|.,|!,||.,||!` on commas and select the piece corresponding to the heaviest possible weight, and print it both upwards and downwards. (Alternatively, it's possible to just print it upwards and reflect in the `¬` direction at the end; a number of variations have the same length.)

```
→Ｐ[

```

Print the clip (will get overwritten by the next weight if any).

```
≧⁻⊟ιθ»

```

Subtract the weight from the input.

```
‖Ｂ←

```

Reflect to complete the barbell.

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


title: Knight Distance

text:
# Question
Title: Knight Distance
In Chess, a Knight on grid \\$(x, y)\\$ may move to \\$(x-2, y-1)\\$, \\$(x-2, y+1)\\$, \\$(x-1, y-2)\\$, \\$(x-1, y+2)\\$, \\$(x+1, y-2)\\$, \\$(x+1, y+2)\\$, \\$(x+2, y-1)\\$ or \\$(x+2, y+1)\\$ in one step. Imagine an infinite chessboard with only a Knight on \\$(0, 0)\\$:

> How many steps is required for moving a Knight from \\$(0, 0)\\$ to \\$(t\_x, t\_y)\\$?

## Inputs

Two integers: \\$t\_x\\$, \\$t\_y\\$;

\\$-100 \< t\_x \< 100\\$, \\$-100 \< t\_y \< 100\\$

## Output

Minimal steps needed to move a Knight from \\$(0, 0)\\$ to \\$(t\_x, t\_y)\\$

## Rules

This is so the shortest code in bytes wins

## Testcases

```
  x    y -> out
  0,   0 ->  0
  0,   1 ->  3
  0,   2 ->  2
  1,   1 ->  2
  1,   2 ->  1
  3,   3 ->  2
  4,   0 ->  2
 42,  22 -> 22
 84,  73 -> 53
 45,  66 -> 37
 99,  99 -> 66
-45, -91 -> 46
-81,   1 -> 42
 11,  -2 ->  7

```

```
document.write('<div>');[..."EFEDEDCDCBCBCBCBCBCBCBCBCBCBCBCBCBCDCDEDEFE;FEDEDCDCBCBABABABABABABABABABABABCBCDCDEDEF;EDEDCDCBCBABABABABABABABABABABABABCBCDCDEDE;DEDCDCBCBABA9A9A9A9A9A9A9A9A9A9ABABCBCDCDED;EDCDCBCBABA9A9A9A9A9A9A9A9A9A9A9ABABCBCDCDE;DCDCBCBABA9A9898989898989898989A9ABABCBCDCD;CDCBCBABA9A989898989898989898989A9ABABCBCDC;DCBCBABA9A98987878787878787878989A9ABABCBCD;CBCBABA9A9898787878787878787878989A9ABABCBC;BCBABA9A989878767676767676767878989A9ABABCB;CBABA9A98987876767676767676767878989A9ABABC;BABA9A9898787676565656565656767878989A9ABAB;CBA9A989878767656565656565656767878989A9ABC;BABA98987876765654545454545656767878989ABAB;CBA9A987876765654545454545456567678789A9ABC;BABA98987676565454343434345456567678989ABAB;CBA9A987876565454343434343454565678789A9ABC;BABA98987676545434323232343454567678989ABAB;CBA9A987876565434323232323434565678789A9ABC;BABA98987676545432341214323454567678989ABAB;CBA9A987876565434321232123434565678789A9ABC;BABA98987676545432323032323454567678989ABAB;CBA9A987876565434321232123434565678789A9ABC;BABA98987676545432341214323454567678989ABAB;CBA9A987876565434323232323434565678789A9ABC;BABA98987676545434323232343454567678989ABAB;CBA9A987876565454343434343454565678789A9ABC;BABA98987676565454343434345456567678989ABAB;CBA9A987876765654545454545456567678789A9ABC;BABA98987876765654545454545656767878989ABAB;CBA9A989878767656565656565656767878989A9ABC;BABA9A9898787676565656565656767878989A9ABAB;CBABA9A98987876767676767676767878989A9ABABC;BCBABA9A989878767676767676767878989A9ABABCB;CBCBABA9A9898787878787878787878989A9ABABCBC;DCBCBABA9A98987878787878787878989A9ABABCBCD;CDCBCBABA9A989898989898989898989A9ABABCBCDC;DCDCBCBABA9A9898989898989898989A9ABABCBCDCD;EDCDCBCBABA9A9A9A9A9A9A9A9A9A9A9ABABCBCDCDE;DEDCDCBCBABA9A9A9A9A9A9A9A9A9A9ABABCBCDCDED;EDEDCDCBCBABABABABABABABABABABABABCBCDCDEDE;FEDEDCDCBCBABABABABABABABABABABABCBCDCDEDEF;EFEDEDCDCBCBCBCBCBCBCBCBCBCBCBCBCBCDCDEDEFE"].forEach(c=>document.write(c==';'?'<br>':`<span class="d-${c}">${c}</span>`));
document.write('<style>body{line-height:16px;color:rgba(255,255,255,0.2);}span{display:inline-block;width:16px;font-size:16px;text-align:center;}div{white-space:pre;}');[...'0123456789ABCDEF'].map((c,i)=>document.write(`.d-${c}{background:hsl(${60-4*i},80%,${65-2*i}%)}`));
```

## Related OEIS

Here are some OEIS for further reading

* A018837: Number of steps for knight to reach \\$(n,0)\\$ on infinite chessboard.
* A018838: Number of steps for knight to reach \\$(n,n)\\$ on infinite chessboard.
* A065775: Array \\$T\\$ read by diagonals: \\$T(i,j)=\\$ least number of knight's moves on a chessboard (infinite in all directions) needed to move from \\$(0,0)\\$ to \\$(i,j)\\$.
* A183041: Least number of knight's moves from \\$(0,0)\\$ to \\$(n,1)\\$ on infinite chessboard.

# Answer
> 12 votes
# Wolfram Language (Mathematica), 64 bytes

Using the built-in `KnightTourGraph`.

Saved 2 bytes thanks to Mathe172.

```
GraphDistance[KnightTourGraph@@({x,y}=Abs@{##}+4),y+2,(x-2)y-2]&

```

Try it online!

# Answer
> 9 votes
# JavaScript (ES6), ~~90~~ ~~75~~ 72 bytes

Inspired by the formula given for A065775. Slow as hell for (not so) long distances.

```
f=(x,y,z=x|y)=>z<0?f(-y,x):z>1?1+Math.min(f(x-1,y-2),f(x-2,y-1)):z*3^x&y

```

Try it online!

## How?

We define **z** as the bitwise OR between **x** and **y**.

### Step #1

We first ensure that we are located in a specific quadrant by forcing both **x** and **y** to be non-negative. As long as **z \< 0** (which means that either **x** or **y** is negative), we process the recursive call **f(-y, x)**:

```
(+1, -2) --> (+2, +1)
(-1, +2) --> (-2, -1) --> (+1, -2) --> (+2, +1)
(-1, -2) --> (+2, -1) --> (+1, +2)

```

### Step #2

While we have **z \> 1** (which means that either **x** or **y** is greater than **1**), we recursively try the two moves that bring us closer to **(0, 0)**: **f(x-1, y-2)** and **f(x-2, y-1)**. We eventually keep the shortest path.

### Step #3

When **z** is less than or equal to **1**, we're left with 3 possibilities which are processed with `z*3^x&y` (we could use `z*3-x*y` instead):

* **x & y == 1** implies **x | y == 1** and means that **x = y = 1**. We need two more moves to reach **(0, 0)**:
* **x & y == 0** and **x | y == 1** means that we have either **x = 1** / **y = 0** or **x = 0** / **y = 1**. We need three more moves to reach **(0, 0)**:
* **x & y == 0** and **x | y == 0** means that we already have **x = y = 0**.

*Graphics borrowed from chess.com*

# Answer
> 6 votes
# Python 3, 90 bytes

Thanks tsh for -11 bytes!

`def f(x,y):x=abs(x);y=abs(y);s=x+y;return(.9+max(x/4,y/4,s/6)-s/2+(s==1or x==y==2))//1*2+s`

Try it online!

(inline code formatting to avoid readers having to scroll. Sorry, but I have to golf my program)

Very very efficient.

---

### How could I come up with this!?

**1. Parity**

Assumes that the whole board is colored in the checkerboard pattern (that is, cells with `x+y` odd and `x+y` even are colored with different colors).

Note that each step must jump between two differently-colored cell. Therefore:

* The parity of the number of steps must be equal to the parity of `x+y`.

**2. Approximation**

Assumes the knight starts from coordinate `(0,0)`, and have moved `n` steps, and is currently at `(x,y)`.
For simplicity, assumes `x ≥ 0`, `y ≥ 0`.
We can conclude:

* Since each step `x` increases by at most `2`, `x ≤ 2×n`. Similarly, `y ≤ 2×n`.
* Since each step `x+y` increases by at most `3`, `x+y ≤ 3×n`.

Therefore, `n ≥ l(x,y)` where `l(x,y) = max(max(x,y)/2, (x+y)/3`. (note that we don't need to include `-x` or `x-y` in the formula because by assumption, `x ≥ 0 and y ≥ 0`, so `x+y ≥ max(x-y,y-x,-x-y)` and `x ≥ -x`, `y ≥ -y`)

It turns out that `a(x,y) = round(0.4 + l(x,y))` is a good approximation to `n`.

* Assume `a(x,y)` is an approximation with error less than `1`, the correct value is given by

```
f(x,y) = round((a(x,y) - (x+y)) / 2) * 2 + (x+y)

```

(round under subtracting `x+y` and dividing by 2)

**3. Special cases that fails the formula**

Assume `x ≥ 0` and `y ≥ 0`. There are 2 special cases where the algorithm fails:

* `x == 1 and y == 0` or `x == 0 and y == 1`: The algorithm incorrectly returns `1` while the correct answer is `3`.
* `x == y == 2`: The algorithm incorrectly returns `2` while the correct answer is `4`.

So, just special-case those. Add the result by `2` if the value of `x` and `y` are one of those.

# Answer
> 5 votes
# Python 2, 87 bytes

```
f=lambda z,a={0}:1-({z}<=a)and-~f(z,{k+1j**i*(2-i/4*4+1j)for k in a for i in range(8)})

```

Try it online!

Takes input as a complex number `z = complex(tx, ty)`.

# Answer
> 5 votes
# TI-Basic, ~~86~~ 54 bytes

Based on @user202729's older solution

```
Input :abs(X->C:abs(Y->D:C+Ans
Ans+2int(.9+(S=1 or C=2 and D=2)-.5Ans+max({C/4,D/4,Ans/6

```

# Answer
> 3 votes
# MATL, 29 bytes

```
`JEQ2J-htZjht_h@Z^2&sG=~}@Gg*

```

Input is a complex number with integer real and imaginary parts.

The code is very inefficient. Its memory requirements increase exponentially with the output. It times out in TIO for the test cases with output exceeding 7.

**Try it online!**

# Answer
> 3 votes
# Jelly, ~~27~~ ~~26~~ ~~25~~ 23 bytes

```
1,-pḤµ;UÆị
¢ṗS€;0i
0ç1#

```

Try it online!

Very slow; times out on TIO for outputs over 6. Takes a complex number as input.

### Explanation

The code uses complex numbers because it was shorter in an intermediate step and it also seems a lot faster; you could also use pairs by removing `Æi` and replacing `0` with `0,0` on the second line.

```
1,-pḤµ;UÆị    Helper link. No arguments.
1,-             Get the pair [1,-1].
    Ḥ           Double each to get [2,-2].
   p            Cartesian product: get [[1,2],[1,-2],[-1,2],[-1,-2]].
     µ          Start a new chain with the list of pairs as argument.
       U        Reverse each pair.
      ;         Append the reversed pairs to the list.
        Æi      Convert each pair [real,imag] to a complex number.

¢ṗS€;0i    Helper link. Arguments: iterations, target
¢            Call the previous link to get knight moves as complex numbers.
 ṗ           Get the iterations-th Cartesian power of the list. This will
             yield 8^n tuples containing move sequences.
  S€         Sum each move sequence to get the resulting square.
    ;0       Add the starting square, since the zeroth iteration results
             in no move sequences.
      i      Find the target squares (1-based) index in the results, or 0.

0ç1#    Main link. Argument: target
0         Starting from 0,
   #      find the
  1       first number of iterations where
 ç        calling the previous link results in a nonzero result.

```

# Answer
> 3 votes
## Haskell, ~~79~~ 72 bytes

```
p l|elem(0,0)l=0|r<-[-2..2]=1+p[(x+i,y+j)|(x,y)<-l,i<-r,j<-r,(i*j)^2==4]

```

Try it online!

Takes the input as a singleton list of pairs of numbers.

A simple brute force. Needs a lot of time and memory for results \> 8. Starting with a single element list of coordinates (the input), repeatedly add all positions that can be reached for every element until `(0,0)` is in this list. Keep track of the recursion level and return it as the result.

Edit: -7 bytes thanks to @Lynn.

# Answer
> 2 votes
## JavaScript (ES6), ~~90~~ 78 bytes

```
f=(x,y)=>y<0?f(x,-y):x<y?f(y,x):x+y<3?4-x-y&3:x-3|y-1?x-4|y-3?f(x-2,y-1)+1:3:2

```

Edit: Saved 12 bytes thanks to @supercat pointing out that `x<0` implies either `y<0` or `x<y`. Explanation: This is a recursive solution. The first two conditions just ensure the right quadrant for the other conditions. The third condition generates the answer for coordinates near the origin, while the last two conditions deal with the other two special cases (1 byte shorter than testing both moves):

```
0
32
2++
+2++
+++3+
++++++
(etc.)

```

All squares marked `+` can be determined by moving directly towards the origin and then recursing.

# Answer
> 2 votes
# Kotlin, ~~148~~ ~~146~~ 140 bytes

```
fun s(x:Int,y:Int):Int=if(y<0)s(x,-y)else
if(x<y)s(y,x)else if(x+y<3)4-x-y and 3
else if(x!=3||y!=1)if(x!=4||y!=3)s(x-2,y-1)+1
else 3 else 2

```

Try it online!

---
Tags: code-golf, integer, graph-theory, chess
---


title: Binary tree fractal

text:
# Question
Title: Binary tree fractal
Today's challenge is to draw a binary tree as beautiful like this example:

```
                               /\
                              /  \
                             /    \
                            /      \
                           /        \
                          /          \
                         /            \
                        /              \
                       /                \
                      /                  \
                     /                    \
                    /                      \
                   /                        \
                  /                          \
                 /                            \
                /                              \
               /\                              /\
              /  \                            /  \
             /    \                          /    \
            /      \                        /      \
           /        \                      /        \
          /          \                    /          \
         /            \                  /            \
        /              \                /              \
       /\              /\              /\              /\
      /  \            /  \            /  \            /  \
     /    \          /    \          /    \          /    \
    /      \        /      \        /      \        /      \
   /\      /\      /\      /\      /\      /\      /\      /\
  /  \    /  \    /  \    /  \    /  \    /  \    /  \    /  \
 /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\

```

You will be given a positive integer as input. This input is the height of the tree. The above example has a height of six.

You may submit either a full-program or a function, and you are free to use any of our default IO methods. For example, printing the tree, returning a string with newlines, returning a 2d char array, saving the tree to a file, etc. would all be allowed.

Trailing spaces on each line are permitted.

Here are some examples of inputs and their corresponding outputs:

```
1:
/\

2:
 /\
/\/\

3:
   /\
  /  \
 /\  /\
/\/\/\/\

4:
       /\
      /  \
     /    \
    /      \
   /\      /\
  /  \    /  \
 /\  /\  /\  /\
/\/\/\/\/\/\/\/\

5:
               /\
              /  \
             /    \
            /      \
           /        \
          /          \
         /            \
        /              \
       /\              /\
      /  \            /  \
     /    \          /    \
    /      \        /      \
   /\      /\      /\      /\
  /  \    /  \    /  \    /  \
 /\  /\  /\  /\  /\  /\  /\  /\
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\

```

Unfortunately, the output grows exponentially, so it's hard to show larger examples. Here is a link to the output for 8.

As usual, this is a challenge, so standard loopholes apply, and try to write the shortest program possible in whatever language you choose.

Happy golfing!

# Answer
> 5 votes
## Python 2, 77 bytes

```
S=s=i=2**input()
while s:print S/s*('/'+' '*(s-i)+'\\').center(s);i-=2;s/=s/i

```

Prints with trailing spaces, terminating with error.

I took this code from my submission to a challenge I posed on Anarchy Golf, plus a one-byte improvement found by xsot. The hardcoded value of 128 was changed to `2**input()`.

The idea is that each row of the output is a segment copied one or more times. The half after the input split has one copy of each segment, the quarter after the next split has two copies, and so on, until the last line with many segments of `/\`.

Each segment had a `/` and `\`, with spaces in between, as well as on the outside to pad to the right length. The outer padding is done with `center`.

The variable `s` tracks the current with of each segment, and the number of segments is `S/s` so that the total width is the tree width `S`. The line number `i` counts down by 2's, and whenever the value `s` is half of it, a split occurs, and the segment width halves. This is done via the expression `s/=s/i`. When `i` reaches `0`, this gives an error that terminates the program.

Since anagolf only allows program submissions, I didn't explore the possibility of a recursive function, which I think is likely shorter.

# Answer
> 4 votes
# , 32 bytes

```
é\é/ÀñLyPÄlx$X>>îò^llÄlxxbPò
|

```

Try it online!

Hexdump:

```
00000000: e95c e92f c0ad f116 4c79 50c4 6c78 2458  .\./....LyP.lx$X
00000010: 3e3e eef2 5e6c 6cc4 6c78 7862 50f2 0a7c  >>..^ll.lxxbP..|

```

# Answer
> 4 votes
# Canvas, 11 bytes

```
/║╶╷［ｌ＼；∔↔║

```

Try it here!

Explanation:

```
/║          push `/\` ("/" palindromized so this is a Canvas object)
  ╶╷[       repeat input-1 times
     l        get the width of the ToS
      \       create a diagonal that long
       ;∔     prepend that to the item below
         ↔    reverse the thing horizontally
          ║   and palindromize it horizontally

```

# Answer
> 3 votes
# Haskell, ~~140 138~~ 135 bytes

```
e n=[1..n]>>" "
n!f=(e n++).(++e n)<$>f
f 0=[]
f n=1!f(n-1)++['/':e(2*n-2)++"\\"]
b n|n<2=f 1|t<-b$n-1,m<-2^(n-2)=m!f m++zipWith(++)t t

```

Try it online! Call with `b 5`, returns a list of strings.

**Pretty print usage:**

```
*Main> putStr . unlines $ b 5
               /\
              /  \
             /    \
            /      \
           /        \
          /          \
         /            \
        /              \
       /\              /\
      /  \            /  \
     /    \          /    \
    /      \        /      \
   /\      /\      /\      /\
  /  \    /  \    /  \    /  \
 /\  /\  /\  /\  /\  /\  /\  /\
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\

```

(some) **Explanation:**

* `e n` generates a string of `n` spaces
* `n!f` pads each string in the list of strings `f` with `n` spaces left and right
* `f n` draws a "peak" in a `n` by `2n` rectangle
* `b n` draws the binary tree by concatenating two smaller trees and centers a new peak above them

Edit: -3 bytes thanks to Zgarb!

# Answer
> 2 votes
## , ~~49 43~~ 42 bytes

```
' /\'{~(|.,-)"1@(=@i.@#,-)^:(<:`(,:@,&*-))

```

This evaluates to a verb that takes a number and returns a 2D character array. Try it online!

## Explanation

I first construct a matrix of the values -1, 0 and 1 by iterating an auxiliary verb, and then replace the numbers by characters. The auxiliary verb constructs the right half of the next iteration, then mirrors it horizontally to produce the rest. In the following explanation, `,` concatenates 2D arrays vertically and 1D arrays horizontally.

```
' /\'{~(|.,-)"1@(=@i.@#,-)^:(<:`(,:@,&*-))  Input is n.
                          ^:(            )  Iterate this verb
                             <:             n-1 times
                               `(       )   starting from
                                    ,&*-    the array 1 -1 (actually sign(n), sign(-n))
                                 ,:@        shaped into a 1x2 matrix:
                                             Previous iteration is y.
                      #                      Take height of y,
                   i.@                       turn into range
                 =@                          and form array of self-equality.
                                             This results in the identity
                                             matrix with same height as y.
                       ,-                    Concatenate with -y, pad with 0s.
       (    )"1@(        )                   Then do to every row:
        |.,-                                 Concatenate reversal to negation.
' /\'{~                                     Finally index entry-wise into string.

```

# Answer
> 2 votes
# Charcoal, 12 bytes

```
ＦＮ«→↗⌈Ｘ²⊖ι‖Ｍ

```

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

```
 Ｎ              Input as a number
Ｆ «             Loop over implicit range
   →            Move right (because mirroring moves the cursor)
         ι      Current index
        ⊖       Decremented
      Ｘ²        Power of 2
     ⌈          Ceiling
    ↗           Draw diagonal line
          ‖Ｍ    Mirror image

```

The line lengths are 1, 1, 2, 4, 8 ... 2^(N-2), thus the awkward calculation.

# Answer
> 2 votes
# Stax, ~~20~~ 19 bytes

```
≡mX░R○k╣∙╒ab^◘⌐╖x▼;

```

Run and debug it

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

```
f=n=>n<2?"/\\":" "+f(n-1).split`/`[0].replace(/|/g,"$`$'$'/$`$`\\$'$'$` \n")+f(n-1).replace(/.*/g,"$&$&")

```

Works by building the result up recursively from the base case `/\`. The bottom half is just the previous case with each line duplicated. The top half was a little trickier; it looks as if you want to take the previous case and only keep the two sides but you also have to worry about padding the strings to double the width, so instead I do some regex magic. By taking the leading spaces from the previous case and splitting at every point, I can consider the spaces before and after that point. At each match the spaces before increase by 1 and the spaces after decrease by 1; this can be used to position the `/` and `\` in the correct places. The newlines and padding are also added here; this takes care of all the padding except a trailing space on each line and a leading space on the first line which I have to add manually. (Leading spaces on subsequent lines come from the matched string).

# Answer
> 0 votes
## Batch, 218 bytes

```
@echo off
set/a"n=1<<%1"
set s=set t=
%s%/\
set l=for /l %%i in (2,1,%n%)do call
%l% %s% %%t%%
%l%:l
:l
echo %t%
set/an-=1,m=n^&n-1
%s%%t: /=/ %
%s%%t:\ = \%
if %m% neq 0 exit/b
%s%%t:/ =/\%
%s%%t: \=/\%

```

Note: Line 6 ends in a space. Works by moving the branches left and right appropriately each time, except on rows that are 2n from the end, in which case the branches get forked instead.

# Answer
> 0 votes
# Haxe, 181 bytes

```
function g(n):String return(n-=2)==-1?"/\\":[for(y in 0...1<<n)[for(x in 0...4<<n)x+y+1==2<<n?"/":x-y==2<<n?"\\":" "].join("")].concat([for(y in g(n+1).split("\n"))y+y]).join("\n");

```

Or, with some optional whitespace:

```
function g(n):String
  return
    (n -= 2) == -1
    ? "/\\"
    : [ for (y in 0...1 << n)
        [ for (x in 0...4 << n)
          x + y + 1 == 2 << n
          ? "/"
          : x - y == 2 << n
            ? "\\"
            : " "
        ].join("")
      ].concat([ for (y in g(n + 1).split("\n"))
        y + y
      ]).join("\n");

```

I was working for a while on a solution which created an array of space characters of the right size first, then iteratively put the forked paths lower and lower (and more densely at each iteration). It remained 230+ bytes, though. The approach here is pretty much what @Laikoni's Haskell approach is. I couldn't get away with not having `:String`, because Haxe is not smart enough to identify that the return type will always be a String.

This is a function only, here's a full programme to test it:

```
class Main {
    public static function main(){
        function g(n):String return(n-=2)==-1?"/\\":[for(y in 0...1<<n)[for(x in 0...4<<n)x+y+1==2<<n?"/":x-y==2<<n?"\\":" "].join("")].concat([for(y in g(n+1).split("\n"))y+y]).join("\n");
        Sys.println(g(Std.parseInt(Sys.args()[0])));
    }
}

```

Put the above in `Main.hx`, compile with `haxe -main Main.hx -neko frac.n` and test with `neko frac.n 4` (replace `4` with the desired order).

# Answer
> 0 votes
# PHP, 188 Bytes

Online Version

```
function f($l,$r=0,$m=1){global$a;for(;$i<$l;$i++)$i<$l/2?$a[$i+$r]=str_repeat(str_pad("/".str_pad("",2*$i)."\\",2*$l," ",2),$m):f($l/2^0,$r+$l/2,2*$m);}f(2**$argv[1]/2);echo join("\n",$a);

```

Expanded

```
function f($l,$r=0,$m=1){
global$a;
for(;$i<$l;$i++)
$i<$l/2
    ?$a[$i+$r]=str_repeat(str_pad("/".str_pad("",2*$i)."\\",2*$l," ",2),$m)
    :f($l/2^0,$r+$l/2,2*$m);
}
f(2**$argv[1]/2);
echo join("\n",$a);

```

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