# Question
Title: Shortest Program to Sort a List of numbers into Odd and Even Category
In the New Modern Times, when Charlie Chaplin encounters a computer, he is employed in the sorting Yard, as a validator to determine if the workers are correctly sorting the items. The Items in question are packets of marbles. Packets with Odd number of Marbles are stacked in the Red Basket and Packets with Even Number of Marbles are stacked in the Blue Basket.

Charlie Chaplin is supposed to punch the program that would validate if there is any anomaly in the sorting procedure. Mack Swain his immediate Boss, shares an algorithm which he needs to code.

**Algorithm**

```
L = List of Marble packets that's already sorted
L_ODD = List of packets with Odd Number of Marbles
L_EVEN = List of packets with Even Number of Marbles
Check_Digit = √(ΣL_ODD² + ΣL_EVEN²)

```

His Job is to determine the Check\_Digit and match it with what ever value his Boss calculates.

Charlie Chaplin during his lunch hours, were able to sneak to Mack Swain's drawer and determine, that his drawer has a single card with punches on the first 46 32 columns (which means Mack was able to write a program with only 46 32 characters).

Charlie Chaplin would now need the help of all the code ninja's to write a program with as few lines as possible. He also announces a bonus of 50 points, if someone can come up with a program which is shorter than his Boss.

**Summary**

Given a list/array/vector of positive numbers (odd and even), you need to write a function, which would accept the `array(int [])/vector<int>/list` and calculate the root of the sum of the squares of the sums of odd and even numbers in the list.

The Size of the program is the size of the body of the function, i.e. excluding the size of the function signature.

**Example**

```
List = [20, 9, 4, 5, 5, 5, 15, 17, 20, 9]
Odd = [9, 5, 5, 5, 15, 17, 9]
Even = [20, 4, 20]
Check_Digit = √(ΣOdd² + ΣEven²) = 78.49203781276162

```

**Note**, the actual output might vary based on the implementation's floating point precision.

**Score**

Score is calculated as `Σ(Characters in your Program) - 46`.Score is calculated as `Σ(Characters in your Program) - 32`. Apart from the regular upvoting from the community, the lowest negative score would receive an additional bonus of 50 points.

**Edit**

1. The offset that was used to calculate the Score has been changed from 46 to 32. Note, this would not affect the leader-board/ bounty eligibility or invalidate any solution.

**Verdict**

After a gruesome duel between the Ninjas, Mr. Chaplin received some wonderful answers. Unfortunately few of the answers tried to take undue advantage of the rule and was not very useful. He actually wanted a fair duel and answers where the logic was coded within the function signatures would eventually mean the function signature is an integral part of the solution. Finally, Ninja FireFly was the clear winner and awarded him the bonus he well deserves. **Leaderboard (updated every day)**

```
╒══════╤═════════════════╤══════════════╤═════════╤════════╤═══════╕
├ Rank │      Ninja      │   Dialect    │ Punches │ Scores │ Votes ┤
╞══════╪═════════════════╪══════════════╪═════════╪════════╪═══════╡
│  0   │     FireFly     │      J       │   17    │  -15   │   6   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  1   │     tmartin     │     Kona     │   22    │  -10   │   2   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  2   │ Sven Hohenstein │      R       │   24    │   -8   │   7   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  3   │    Ben Reich    │  GolfScript  │   30    │   -2   │   1   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  4   │    mollmerx     │      k       │   31    │   -1   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  5   │ David Carraher  │ Mathematica  │   31    │   -1   │   3   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  6   │     tmartin     │      Q       │   34    │   2    │   1   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  7   │     daniero     │      dc      │   35    │   3    │   1   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  8   │    psion5mx     │    Python    │   38    │   6    │   2   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  9   │       O-I       │     Ruby     │   39    │   7    │   5   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  10  │      gggg       │    Julia     │   40    │   8    │   1   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  11  │ FakeRainBrigand │  LiveScript  │   50    │   18   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  12  │    Sylwester    │    Perl5     │   50    │   18   │   2   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  13  │     daniero     │     Ruby     │   55    │   23   │   1   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  14  │    vasuakeel    │ Coffeescript │   57    │   25   │   1   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  15  │      dirkk      │    XQuery    │   63    │   31   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  16  │  crazedgremlin  │   Haskell    │   64    │   32   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  17  │   Uri Agassi    │     Ruby     │   66    │   34   │   1   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  18  │     Sumedh      │     JAVA     │   67    │   35   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  19  │      Danny      │  Javascript  │   67    │   35   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  20  │     deroby      │      c#      │   69    │   37   │   1   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  21  │  Adam Speight   │      VB      │   70    │   38   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  22  │    Andrakis     │    Erlang    │   82    │   50   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  23  │      Sp0T       │     PHP      │   85    │   53   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  24  │    brendanb     │   Clojure    │   87    │   55   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  25  │  Merin Nakarmi  │      C#      │   174   │  142   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  26  │    Boopathi     │     JAVA     │   517   │  485   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  27  │      Noyo       │     ES6      │    ?    │   ?    │   2   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  28  │     shiona      │   Haskell    │    ?    │   ?    │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  29  │      Vivek      │     int      │    ?    │   ?    │   0   │
└──────┴─────────────────┴──────────────┴─────────┴────────┴───────┘

```

# Answer
> 7 votes
## J, ~~18~~ 17 chars - 32 = ⁻15

```
[:+/&.:*:2&|+//.]

```

(As a "function body"; has to be parenthesized or bound to a name.)

### Explanation

I tried making an exploded view of what each piece does, like Tobia does in APL answers.

```
               +//. ]    NB. sum up partitions
           2&|           NB.   given by equality on (x mod 2)
        *:               NB. square,
   +/                    NB. sum,
     &.:                 NB. then revert the squaring (square-root)
                         NB. (f&.:g in general acts like g⁻¹(f(g(x))))
[:                       NB. (syntax to indicate composition of +/&.:*: and (2&| +//. ]))

```

`+/&.:*:` could be replaced with `|@j./` making use of O-I's complex magnitude trick to save yet another two characters.

### Example

```
   f =: [:+/&.:*:2&|+//.]
   f 20 9 4 5 5 5 15 17 20 9
78.492

```

# Answer
> 9 votes
## ES6, ~~(48 - 32) = 16~~ (1 - 32) = -31

*Original version:*

```
f=l=>(e=o=0)+l.map(x=>x%2?e+=x:o+=x)&&Math.hypot(e,o)

```

Entire function definition is 53 characters, body only is 48.

**Updated version, taking full advantage of the problem definition and moving pretty much everything out of the body and into the signature:**

```
f=(l,e=0,o=0,g=x=>x%2?e+=x:o+=x,c=l.map(g)&&Math.hypot(e,o))=>c

```

New function definition is now 63 "punches" total, but function BODY is now just **ONE DAMN CHARACTER LONG.** Plus it no longer corrupts the global namespace! :D

Usage:

```
>>> f([20, 9, 4, 5, 5, 5, 15, 17, 20, 9])
78.49203781276161

```

# Answer
> 7 votes
## R, (24 − 32) = −8

```
f=function(x)
    sum(by(x,x%%2,sum)^2)^.5

```

The function body consists of 24 characters.

Usage:

```
f(c(20, 9, 4, 5, 5, 5, 15, 17, 20, 9))
[1] 78.49204

```

# Answer
> 6 votes
### Ruby 2.1+ — (39 characters total - 7 non-body - 32 offset = 0)

Slightly different approach. I create a complex number `a+b*i` such that `a` and `b` are the sums of the even and odd numbers in `list`, respectively. Then I just take the absolute value.

```
f=->l{l.reduce{|s,x|s+x*1i**(x%2)}.abs}

```

My previous solution, which is 5 characters longer but works on 1.9.3+:

```
f=->l{l.reduce{|s,x|s+x*?i.to_c**(x%2)}.abs}

```

On a final note, if Rails + Ruby 2.1+ were allowed, we can use `Array#sum` to get the body down to a mere 25 characters:

```
l.sum{|x|x+1i**(x%2)}.abs

```

# Answer
> 5 votes
# Python 2.7: 45, nay: 40, nay: 38 - 32 = 6

Nothing very new here, just a combination of the complex number trick I saw in the recent Pythagoras challenge, lambda for compactness, and syntax/parenthesis minimisation:

```
lambda x:abs(sum(a*(1-a%2+a%2*1j)for a in x))

```

Update - saved a few chars. Thanks to @DSM for the trick of raising the complex component to 0/1.

```
lambda x:abs(sum(a*1j**(a%2)for a in x))

```

Ok, reading the question and recognising the 'body of the function' count rule saves another 2 chars:

```
def f(x):
    return abs(sum(a*1j**(a%2)for a in x))

```

iPython testing:

```
In [650]: x = [20, 9, 4, 5, 5, 5, 15, 17, 20, 9]

In [651]: print (lambda l:abs(sum(a*(1-a%2+a%2*1j)for a in l)))(x)
78.4920378128

...

In [31]: def f(x):
   ....:     return abs(sum(a*1j**(a%2)for a in x))
   ....:

In [32]: f(x)
Out[32]: 78.49203781276162

```

# Answer
> 4 votes
## APL (27 - 46 = -19)

```
{.5*⍨+/2*⍨+⌿⍵×[1]z,⍪~z←2|⍵}

```

e.g.:

```
      {.5*⍨+/2*⍨+⌿⍵×[1]z,⍪~z←2|⍵} 20 9 4 5 5 5 15 17 20 9
78.49203781

```

# Answer
> 4 votes
# Mathematica 31-32 = -1

```
√Tr[(Tr/@GatherBy[#,OddQ])²]//N &

```

`GatherBy[#,OddQ]` produces the even-packet, odd-packet lists.

The inner `Tr`finds the totals, both of which are squared and then summed (by the outer `Tr`).

`N` converts from an irrational number (the square root of an integer) to a decimal approximation.

## Example

```
√Tr[(Tr/@GatherBy[#,OddQ])²]//N &[{9, 5, 5, 5, 15, 17, 9, 20, 4, 20}]

```

> 78.492

---

If `f[n_]:=` is not included in the count, an additional character can be saved.

```
    f[n_]:=
    √Tr[(Tr/@GatherBy[n,OddQ])²]//N

```

Example

```
f[{9, 5, 5, 5, 15, 17, 9, 20, 4, 20}]

```

> 78.492

# Answer
> 3 votes
# Perl5 : (50 - 32 = 18)

```
map{$0[$_&1]+=$_}@ARGV;print sqrt$0[0]**2+$0[1]**2

```

# Answer
> 3 votes
# dc 3 (35 - 32)

Using arrays, as suggested by @Tomas. This saves some of characters because I can calculate the parity of each number and use it as an index, instead of tweaking the with parity as a method of branching and putting the right values in the right registers. Also it turns out that arrays will give you a 0 even if the array/index haven't been used, so you don't have to initialize anything.

```
[d2%dsP;S+lP:Sz0<L]dsLx0;S2^1;S2^+v

```

Assumes the numbers are already on the stack, and leaves the result as the only value left when it's done.

Test:

```
$ dc
20 9 4 5 5 5 15 17 20 9
[d2%dsP;S+lP:Sz0<L]dsLx0;S2^1;S2^+v
p
78

```

# dc 16 (48 - 32)

First version using registers *o* and *e* to store odd and even numbers.

```
0dsose[dd2%rd1+2%*lo+so*le+sez0<x]dsxxle2^lo2^+v

```

# Answer
> 3 votes
# Kona, 22 - 32 = -10

```
{(+/(+/'x@=x!2)^2)^.5}

```

# Answer
> 3 votes
# Prolog (73 - 32 = 41)

Here we count everything after ':-' as the function body.

```
f([],0,0,0).
f([H|T],O,E,X):-(1 is H mod 2,f(T,S,E,_),O is H+S,!;f(T,O,S,_),E is H+S),sqrt(O*O+E*E,X).

```

Call function like so:

```
f([20, 9, 4, 5, 5, 5, 15, 17, 20, 9],_,_,X).

```

# Answer
> 2 votes
# Julia, 40-46=-6

**Implementation**

```
function f(l)
    a=sum(l);b=sum(l[l%2 .==1]);hypot(a-b,b)
end

```

**Output**

```
julia> f([20, 9, 4, 5, 5, 5, 15, 17, 20, 9])
78.49203781276161

```

# Answer
> 2 votes
**Python, 9 (55 - 46)**

```
lambda x:sum([sum([i*(d-i%2) for i in x])**2for d in(0,1)])**0.5

```

Using a lambda function saves some bytes on newlines, tabs and `return`.

Example:

```
x = [20, 9, 4, 5, 5, 5, 15, 17, 20, 9]
print (lambda x:sum([sum([i*(d-i%2) for i in x])**2for d in(0,1)])**0.5)(x)
78.4920378128

```

# Answer
> 2 votes
# Ruby, 55 - 46 = 9

```
f=->a{h=[0,0];a.map{|v|h[v%2]+=v};e,o=h;(e*e+o*o)**0.5}

```

Test:

```
f[[20, 9, 4, 5, 5, 5, 15, 17, 20, 9]] => 78.49203781276162`

```

# Answer
> 2 votes
# Q, 34 - 32 = 2

```
{sqrt sum{x*x}(+/')(.)x(=)x mod 2}

```

.

```
q){sqrt sum{x*x}(+/')(.)x(=)x mod 2} 20 9 4 5 5 5 15 17 20 9
78.492037812761623

```

# Answer
> 2 votes
# Ruby (66 - 32 = 34)

```
f=->a{o,e=a.partition(&:odd?).map{|x|x.reduce(:+)**2};(e+o)**0.5}

```

test:

```
f.([20, 9, 4, 5, 5, 5, 15, 17, 20, 9])
=> 78.49203781276162

```

# Answer
> 2 votes
**Coffeescript, (57 - 32 =25)**

**Implementaion**

```
f=(a)->r=[0,0];r[e%2]+=e for e in a;[e,o]=r;(e*e+o*o)**.5

```

# Answer
> 2 votes
## GolfScript 30

```
.{2%},]{{+}*}/.@\-]{2?}/+2-1??

```

I don't think GolfScript has much of a chance on this one!

# Answer
> 2 votes
## c#: 69-32=37

```
double t=l.Sum(),o=l.Sum(x=>x*(x%2)),e=t-o;return Math.Sqrt(o*o+e*e);

```

Full code:

```
class Program
{
    static void Main(string[] args)
    {
        int[] list = { 20, 9, 4, 5, 5, 5, 15, 17, 20, 9 };
        Console.WriteLine(F(list));
        Console.ReadKey();
    }

    static double F(int[] l)
    {
        double t = l.Sum(),  // total sum of all elements
               o = l.Sum(x => x * (x % 2)),  // total of odd elements, if even %2 will return zero
               e = t - o; // even = total - odd
        return Math.Sqrt(o * o + e * e);
    }
}

```

PS: Just for fun, this works too, sadly it doesn't change the number of characters needed:

```
double t=l.Sum(),o=l.Sum(x=>x*(x%2));return Math.Sqrt(t*t-2*o*(t-o));

```

# Answer
> 1 votes
**C# 174**

```
using System;class P{static void Main(){double[] L={20,9,4,5,5,5,15,17,20,9};double O=0,E=0;foreach(int i in L){if(i%2==0)E+=i;else O+=i;}Console.Write(Math.Sqrt(E*E+O*O));}}

```

Readable

```
using System;
class P
{
  static void Main()
  {
      double[] L = { 20, 9, 4, 5, 5, 5, 15, 17, 20, 9 };
      double O = 0, E = 0;
      foreach (int i in L)
      {
        if (i % 2 == 0)
            E += i;
        else
            O += i;
      }
      Console.Write(Math.Sqrt(E * E + O * O));
   }
}

```

# Answer
> 1 votes
# Matlab (44 - 46 = -2)

Function body is 44 characters:

```
C=mod(A,2)>0;O=(sum(A(C))^2+sum(A(~C))^2)^.5

```

Total function as follows:

```
function O = Q(A)
C=mod(A,2)>0;O=(sum(A(C))^2+sum(A(~C))^2)^.5
end

```

Tests of the function:

```
>> A = [20 9 4 5 5 5 15 17 20 9];
>> Q(A)

O =

   78.4920

ans =

   78.4920

```

---

```
>> B = [8 3 24 1 9 8 4 5 52];
>> Q(B)

O =

   97.6729

ans =

   97.6729

```

# Answer
> 1 votes
## Python 2.7 - 64-46 = 18

This could be shorter using some `zip` magic, but for now:

```
(sum(s for s in x if s%2)**2+sum(s for s in x if s%2==0)**2)**.5

```

For completion, it turns out you can do zip magic, but it costs you more (by a few characters), so the above stands, unless someone can improve either of these:

```
sum(map(lambda i:sum(i)**2,zip(*[[(0,i),(i,0)][i%2]for i in x])))**.5

```

# Answer
> 1 votes
### Clojure = 87 - 46 = 41

```
(defn cd [v]
  (let [a apply ** #(* % %)]
    (Math/sqrt(a + (map #(** (a + (% 1)))(group-by even? v))))))

```

Hardly idiomatic, though.

# Answer
> 1 votes
## Haskell, 64C - 46 = 18

```
c x=sqrt$fromIntegral$s(f odd x)^2+s(f even x)^2
f=filter
s=sum

```

Not too difficult to read. Example run:

```
*Main> c [1..10]
39.05124837953327

```

# Answer
> 1 votes
**PHP** 85-32=53

`$a=$b=0;foreach($x as $q){if(($q%2)==0)$a=$a+$q;else$b=$b+$q;}echo sqrt($a*$a+$b*$b);`

This is the best i'ld come up being a newbie. I'm sure there must be some shorter versions as well.

**EDIT:**

A reduced version of the code could be:

```
foreach($x as$q)($q%2)?$a=$a+$q:$b=$b+$q;echo sqrt($a*$a+$b*$b);

```

This version only has 64 (21 less than the original answer) chars.

Said so, 64-32=**32**

# Answer
> 1 votes
`int e=0,o=0;for(int i :n){if(i%2==0)e+=i;else o+=i;}System.out.println(Math.sqrt(e*e+o*o));`

## Actual method in java code

```
public static void checkDigit(int[] n)
{
    int e=0,o=0;for(int i :n){if(i%2==0)e+=i;else o+=i;}System.out.println(Math.sqrt(e*e+o*o));
}

```

> Test Class

```
public class Sint
{
    public static void main(String[] args)
    {
        if(args == null || args.length == 0)
            args = "20 9 4 5 5 5 15 17 20 9".split(" ");
        int[] n = null;
        try
        {
            n = new int[args.length];
            for(int i=0; i<args.length; i++)
                n[i] = Integer.parseInt(args[i]);
            System.out.print("int array is: ");
            for(int dd : n) System.out.print(dd+", ");
            System.out.print("\n");
            checkDigit(n);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void checkDigit(int[] n)
    {
        int e=0,o=0;for(int i :n){if(i%2==0)e+=i;else o+=i;}System.out.println(Math.sqrt(e*e+o*o));
    }
}

```

# Answer
> 1 votes
# Erlang: 82C - 32 = 50

```
fun(L)->F={lists,sum},O=[X||X<-L,X rem 2>0],E=F(L--O),math:sqrt(F(O)*F(O)+E*E)end.

```

Erlang isn't great for this. Most shortcuts end up being more characters (tuples etc.)

The only real things of note:

* `{lists,sum}` is a function reference to `lists:sum` and can be called
* Even numbers are calculated by subtracting `--` (*list subtract*) the odd numbers list from the full list

Can call using:

```
fun(L)->F={lists,sum},O=[X||X<-L,X rem 2>0],E=F(L--O),math:sqrt(F(O)*F(O)+E*E)end([20,9,4,5,5,5,15,17,20,9]).

```

Output: `78.49203781276162`

# Answer
> 1 votes
## VB.net (81c - 11c = 70) - 32 = 38

Via liberal usage of the term *Write a function*

```
Function(n)Math.Sqrt(n.Sum(Function(x)x Mod 2=0)^2+n.Sum(Function(x)x Mod 2=1)^2)

```

# Answer
> 1 votes
### XQuery, (63 - 32 = 31)

**Implementation**

```
declare default function namespace 'http://www.w3.org/2005/xpath-functions/math';
declare function local:f($s) {
  sqrt(pow(fn:sum($s[. mod 2=0]),2)+pow(fn:sum($s[. mod 2=1]),2))
};

```

**Output**

```
local:f((20, 9, 4, 5, 5, 5, 15, 17, 20, 9))

```

BaseX was used as XQuery processor.

# Answer
> 1 votes
## Haskell

**57 - 32 = 25**

Straight optimization of crazedgremlins answer:

```
c x=sqrt$read$show$sum(odd%x)^2+sum(even%x)^2
(%)=filter

```

Optimizations:

* `read$show` is shorter than `fromIntegral` \- *3 chars*
* `s=sum\n` and two `s`'s has total length of 8 chars, two `sum`'s is just 6 chars. - *2 chars*
* making filter into operator does away with need of whitespace - *2 chars*

I also tried adding more stuff to the operator, but it ended up being just as long:

```
c x=sqrt$read$show$odd%x+even%x
(%)=(((^2).sum).).filter

```

# Answer
> 1 votes
## LiveScript 50 (or 1 if you're flexible)

The 1 character solution is `r` where the function signature is this:

```
fun = (a,o=(sum a.filter odd),e=(sum a.filter even),r=(e*e+o*o)**0.5) ->

```

But I think that's a technicality.

Actual answer:

```
o=sum a.filter odd
e=sum a.filter even
(e*e+o*o)^0.5

```

# Answer
> 1 votes
# k (31-32 = -1)

```
sqrt{+/b*b:+/'(.)x@=(_a)=a:x%2}

```

Example run:

```
  sqrt{+/b*b:+/'(.)x@=(_a)=a:x%2} 20 9 4 5 5 5 15 17 20 9
78.492037812761623

```

# Answer
> 1 votes
# C (68-32 = 36)

```
float f(int *a, int c)
{int s[2]={0};while(c--)s[a[c]%2]+=a[c];return sqrt(*s**s+s[1]*s[1]);}

```

In action:

```
#include <stdio.h>
#include <math.h>

float f(int *a, int c)
{int s[2]={0};while(c--)s[a[c]%2]+=a[c];return sqrt(*s**s+s[1]*s[1]);}

int main(void)
{
    printf("%f\n", f((int[]){20, 9, 4, 5, 5, 5, 15, 17, 20, 9}, 10));
    return 0;
}

```

# Answer
> 1 votes
# ised (10 characters - 32) = -22

ASCII:

```
@={@+E$1@+O$1}

```

UTF8:

```
@={ΣE$1ΣO$1}

```

The variable `$1` must contain the array. Example invocation from shell:

```
ised --l - '@={ΣE$1ΣO$1}' <<<"20, 9, 4, 5, 5, 5, 15, 17, 20, 9"

```

Example invocation in interactive mode:

```
ised> @1{20, 9, 4, 5, 5, 5, 15, 17, 20, 9}
20 9 4 5 5 5 15 17 20 9
ised> @={ΣE$1ΣO$1}
78.492

```

Explanation: operators `O` and `E` extract odd and even elements of the array. The operator `@+` or `Σ` sums the array. `@=` returns the length of the given vector.

If you want a function, it's even shorter. Saving a function:

```
ised> @2{: @={ΣExΣOx} :}

```

The function body is only 10 characters long. The rest is the function declaration (`{: :}`) and storage of the function handle into memory slot 2 (`@2`). Invocation

```
ised> $2::{20 9 4 5 5 5 15 17 20 9}

```

Link to software: http://ised.sourceforge.net/

# Answer
> 1 votes
# Tcl, 60 bytes (bonuses not included yet)

```
proc C L {lmap c $L {incr [expr $c%2] $c}
expr hypot($0,$1)}

```

Try it online!

# Answer
> 1 votes
# Factor \+ `math.unicode`, 43 - 32 = 11

```
[ [ odd? ] partition [ Σ sq ] bi@ + sqrt ]

```

Try it online!

# Answer
> 1 votes
# Jelly, 10 bytes - 32 = score -22

```
ḟḂƇ,ḂƇ§²S½

```

Try it online!

# Answer
> 0 votes
**JAVA: 67-32=35**

inside function(int\[\] a) :

```
int x=0,y=0;
for(int i:a)
{
if(i%2==0)
x+=i;
else y+=i;
}
Math.hypot(x,y);

```

# Answer
> 0 votes
**JAVA 517 bytes**

```
 public class Link
    {
        public static void main(String[] args)
        {
            int[]a={20, 9, 4, 5, 5, 5, 15, 17, 20, 9};
            int []b=new int[10];
            int[]c=new int[10];
            int j=0,k=0,l=0,m=0;
            for(int i=0;i<a.length;i++)
            {
                if(a[i]%2==0)
                {
                    b[j]=a[i];
                    j++;
                }
                else
                {
                    c[k]=a[i];
                    k++;
                }
            }
            for(int i=0;i<j;i++)
            {
                l=l+b[i];
            }
            l=l*l;
            for(int i=0;i<k;i++)
            {
                m=m+c[i];
            }
            m=m*m;
            l=l+m;
            double t=Math.sqrt(l);
            System.out.print(t);
        }

    }

```

# Answer
> 0 votes
# Javascript 67-32=35

```
function r(a){k=j=0;a.map(function z(i){i%2?j+=i:k+=i});return Math.sqrt(k*k+j*j)}

```

Doesn't seem like there is an easy way of spliting the array into even's and odd's without defining another function :(

```
console.log(r([20, 9, 4, 5, 5, 5, 15, 17, 20, 9]));
78.49203781276162

```

# Answer
> 0 votes
# Vyxal , 7 bytes - 32 = score -25

```
⁽∷ġṠ²∑√

```

Try it Online!

---
Tags: code-golf, sorting
---


title: Crate art stacking

text:
# Question
Title: Crate art stacking
Your task is, given a array of numbers, that is strictly increasing, output the crate stack. The input is an array of positive integers which represents which layer has how many crates there are. So the first number is the top layer and so on. The sum of the array is the size of the crate.

Since the array order follows this rule `layer 1>layer 2>layer 3...`, we have to make sure every layer above the bottom one is centered with respect to the whole width of the layer below it. If it can't be centered, place it so that it's as close as possible to the center (you can choose it to be shifted left or right).

## Testcases

```
[1]
->
*

[1,2]
->
 ***
 * *
 ***
******
* ** *
******

[2,3]
->
  **********
  *   **   *
  *   **   *
  *   **   *
  **********
***************
*   **   **   *
*   **   **   *
*   **   **   *
***************

[2,3,4]
->
        ******************
        *       **       *
        *       **       *
        *       **       *
        *       **       *
        *       **       *
        *       **       *
        *       **       *
        ******************
    ***************************
    *       **       **       *
    *       **       **       *
    *       **       **       *
    *       **       **       *
    *       **       **       *
    *       **       **       *
    *       **       **       *
    ***************************
************************************
*       **       **       **       *
*       **       **       **       *
*       **       **       **       *
*       **       **       **       *
*       **       **       **       *
*       **       **       **       *
*       **       **       **       *
************************************

```

Leading spaces and trailing spaces are allowed

This is , so shortest code wins!

# Answer
# Vyxal, 19 bytes

```
∑×2460ø^↵vẋƛ∩Ṡ;føĊ⁋

```

Try it Online!
> 0 votes

# Answer
# JavaScript, ~~225~~ 219 bytes

-7 thanks to Arnauld's suggestion

```
s=d=>{j=console.log;o=(p,g)=>p.repeat(g);a="*";[t]=d.slice(-1);if(t==1)return j(a);b=t*-~t/2-2;b=b<1?1:b;d.map(i=>{h=o(" ",(t*b-i*b)/2);c=`${h+o(o(a,b+2),i)}${o(`
${h+o(`*${o(" ",b)}*`,i)}`,b)}
${h+o(o(a,b+2),i)}`;j(c)})}

```

Try it online!

Unminified for your enjoyment:

```
function stack(arr) {
    String.prototype.o = function(p) {
        return this.repeat(p);
    }
    const a = "*";
    const [t] = arr.slice(-1);
    if(t == 1) return console.log(a);
    let sum = ((t * t + t) / 2) - 2;
    if(sum < 1) sum = 1;
    arr.forEach(i => {
        const spaces = " ".o((t * sum - i * sum) / 2);
        const crate = `${spaces + a.o(sum + 2).o(i)}${`\n${spaces + `*${" ".o(sum)}*`.o(i)}`.o(sum)}\n${spaces + a.o(sum + 2).o(i)}`;
        console.log(crate);
    });
}

```
> 3 votes

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

```
lambda n:(s:=sum(n))and'\n'.join('\n'.join((n[-1]-N)*s//2*' '+N*('*'+'* '[0<m<s-1]*(s-2)+'*'*(s>1))for m in range(s))for N in n)

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 21 bytes

```
O'*Ž9¦.Λ¶¡¸Iи€øJ€»».c

```

Try it online or verify all test cases or try it online with step-by-step debug lines.

**Explanation:**

```
O              # Sum the (implicit) input-list
 '*           '# Push "*"
   Ž9¦         # Push compressed 2460
      .Λ       # Use the (modifiable) Canvas builtin with these three options
¶¡             # Split this box by newlines
  ¸            # Wrap it in a list
   Iи          # Repeat it each of the inputs amount of times
     €         # Map over each list of boxes:
      ø        #  Zip/transpose; swapping rows/columns
       J       # Join each inner row together to a single string
        €»     # Join all inner lines by newlines
          »    # Join each vertical line of boxes by newlines
           .c  # Centralize all lines
               # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ž9¦` is `2460`.

As for some additional information about the modifiable Canvas builtin :
It takes 3 arguments to draw an ASCII shape:

1. Length of the lines we want to draw
2. Character/string to draw
3. The direction to draw in, where each digit represents a certain direction:

```
7   0   1
  ↖ ↑ ↗
6 ← X → 2
  ↙ ↓ ↘
5   4   3

```

`O'*Ž9¦` creates the following Canvas arguments:

1. Length: the sum of the input (e.g. for `[2,3,4]` this would be `9`)
2. Character: `"*"`
3. Directions: `[2,4,6,0]`, which translates to \\$\[→,↓,←,↑\]\\$

Try just the Canvas portion online.

Step 1: Draw 9 characters (`"*********"`) in direction 2/:

```
*********

```

Step 2: Draw 9-1 characters (`"********"`) in direction 4/:

```
*********
        *
        *
        *
        *
        *
        *
        *
        *

```

Step 3: Draw 9-1 characters (`"********"`) in direction 6/:

```
*********
        *
        *
        *
        *
        *
        *
        *
*********

```

Step 4: Draw 9-1 characters (`"********"`) in direction 0/:

```
*********
*       *
*       *
*       *
*       *
*       *
*       *
*       *
*********

```

After which we can use this string since we're using the modifiable Canvas builtin , instead of the Canvas builtin `Λ` that would output directly.

See this 05AB1E tip of mine for an in-depth explanation of the Canvas builtin.
> 2 votes

# Answer
# Charcoal, 29 bytes

```
ＦＬθ«Ｊ⊘×§θιΣθ×ιΣθＦ§θι«ＢΣθ*ＭΣθ←

```

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

```
ＦＬθ«

```

Loop over each layer.

```
Ｊ⊘×§θιΣθ×ιΣθ

```

Jump to the top left corner of the last box in that layer.

```
Ｆ§θι«

```

Loop over each box in the layer.

```
ＢΣθ*

```

Draw the box of the appropriate size.

```
ＭΣθ←

```

Move to the previous box.
> 1 votes

# Answer
# JavaScript (ES6),  ~~132 128 120~~  119 bytes

Non-centered crates are shifted to the right.

```
f=(a,x=W=a.every(n=>w+=N=n,w=y=0)+w*N)=>(q=W-a[y/w|0]*w)?` *
`[--x?(X=x+q/2)%w<2|-~y%w<2&&X>=q&X<W:++y&&2]+f(a,x||W):''

```

Try it online!

### Commented

```
f = (                  // f is a recursive function taking:
  a,                   //   a[] = input array
                       // and also using:
  x =                  //   (x, y) = current position
  W =                  //   W = total row width, w = crate width
    a.every(n =>       //   for each value n in a[]:
      w += N = n,      //     add n to w and save n in the global scope
      w = y = 0        //     start with w = 0 and y = 0
    )                  //   end of every(), which returns 1
    + w * N            //   add the last value multiplied by w
) =>                   //
( q = W -              // define q as the total row width less the
      a[y / w | 0] * w // total width of the crates on this row
) ?                    // if q is not NaN:
  ` *\n`[              //   character lookup:
    --x ?              //     decrement x; if it's not 0:
      (X = x + q / 2)  //       define X as x + q / 2
      % w < 2 |        //       if we're over a vertical crate edge
      -~y % w < 2      //       or over a horizontal crate edge
      &&               //       and
      X >= q & X < W   //       we're over the crates in this row,
                       //       then put a '*', else put a space
    :                  //     else:
      ++y && 2         //       increment y and put a linefeed
  ] +                  //   end of character lookup
  f(a,                 //   append the result of a recursive call
       x || W)         //   make sure to restart with x = W if x = 0
:                      // else:
  ''                   //   stop the recursion

```
> 1 votes

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


title: How related are two relatives?

text:
# Question
Title: How related are two relatives?
The coefficient of relationship refers to how much DNA two persons have in common. A parent has 50% common DNA with their child (unless the parents are related), so to calculate it we have to find all pairs of directed disjoint paths starting at same node (common ancestor) and ending at each of the two siblings, and sum 2^-(m+n) for all pairs of paths of length m and n.

Your program should accept a list of pairs of numbers (or names if you prefer) representing parent-child relations followed by another pair of number for which it should output the coefficient of relationship (either as a fraction, a decimal number, or a percentage).

For example:

```
Format: [list of parent-child relations] pair of relatives we want to compare -> expected output
-----------------------------------------------
[(1,2)] (1, 2) -> 50% (parent-child)
[(1,2), (2, 3), (3, 4)] (2, 3) -> 50% (still parent-child, make sure your path pairs are disjoint)
[(1,3), (2, 3)] (1, 2) -> 0% (not related, make sure your paths are directed)
[(1, 2), (2, 3)] (1, 3) -> 25% (grandparent-child)
[(1, 3), (1, 4), (2, 3), (2, 4)] (3, 4) -> 50% (siblings)
[(1, 2), (1, 3)] (2, 3) -> 25% (half-siblings)
[(1, 3), (1, 4), (2, 3), (2, 4), (3, 5)] (4, 5) -> 25% (aunt/uncle-nephew/niece)
[(1, 3), (1, 4), (2, 3), (2, 4), (3, 5), (4, 6)] (5, 6) -> 12.5% (cousins)
[(1, 3), (1, 4), (2, 3), (2, 4), (5, 7), (5, 8), (6, 7), (6, 8), (3, 9), (7, 9), (4, 10), (8, 10)] (9, 10) -> 25% (double cousins)
[(1, 3), (1, 4), (2, 3), (2, 4), (3, 5), (4, 5)] (3, 5) -> 75% (parent-(child-with-sibling) incest)
[(1, 2), (1, 3), (2, 3)] (1, 3) -> 75% ((parent-and-grandparent)-(child-with-child) incest)

```

No person will have more than two parents and there will be no cycles in it. You can also assume that the number is the order in which they were born (so `a < b` in all `(a, b)`).

# Answer
> 2 votes
# Python 3, 259 247 226 bytes

```
lambda l,a,b:sum(2**-len({*m}^{*n})for v in{*sum(l,())}for m in p(v,a,l)for n in p(v,b,l)if not{*zip(m,m[1:])}&{*zip(n,n[1:])})
p=lambda i,j,l:sum([[[r+[i]for r in p(y,j,l)],[[y,x]]][j==y]for x,y in l if i==x],[])+[[i]]*(i==j)

```

Try it online!

This can probably be golfed down quite a bit, but for now I'm just happy it works.

# Answer
> 2 votes
# Python3, 206 bytes:

```
lambda l,a:(a in l)/2+sum(2**-len((x|y)-(x&y))for x in f(a[0],l,a)for y in f(a[1],l,a)if x&y)
def f(n,l,o,p=[],K=1):
 for a,b in l:
  if(b==n)&(K:=[a,b]!=o):yield from f(a,l,o,p+[b]);K=0
 if K:yield{*p+[n]}

```

Try it online!

# Answer
> 1 votes
# Wolfram Language (Mathematica), ~~188~~ ~~166~~ 154 bytes

```
e_~h~f_:=4Tr[2^-Tr[Length/@#]&/@Select[Flatten[Tuples[i@r_:=If[#==r,{{r}},FindPath[g,#,r,∞,All]];i/@f]&/@VertexList[g=Rule@@@e],1],DisjointQ@@Rest/@#&]]

```

Try it online!

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


title: Disassemble tables

text:
# Question
Title: Disassemble tables
Given a string that represents a bunch of tables stacked on top of each other and/or arranged side-by-side, disassemble all the tables.

## Tables

A table looks like this:

```
-------
|     |
|     |

```

More formally, a table has a tabletop, composed of `n` dashes, and two visible legs. (Obviously, there are two hidden behind, but for the purposes of this challenge, a table has two legs. (Think of the legs as being thick legs that span the entire length of the table.)

The visible legs are both `m` pipes (`|`) high, and are separated by `n-2` spaces. (Thus, the string representation of a table has `m+1` lines of exactly `n` characters per line.)

Does it sound easy to disassemble a table? Think again.

## Stacked tables and tables arranged side-by-side

The table above is just one of the many tables you could be given as input. In actuality, oftentimes you will have a huge number of tables you wish to disassemble, and to save space in your home, you might decide to stack them on top of each other, and sometimes arrange these stacks side-by-side.

This would not be a problem if the tables were all the same height and length. However, obviously there is the possibility of having a messy arrangement of tables, and you should be able to disassemble these arrangements as easily as you would disassemble a single table.

This is an example of an arrangement:

```
   ---------
   |       |             ---
   |       |             | |
 -------------          -------------------
 |           |          |                 |
---------------         |                 |
|             |         |                 |
|             |-----------------------------------
|             ||                                 |
|             ||                                 |

```

## How to disassemble tables, or arrangements thereof?

Disassembling tables consists of separating the top, leg one, and leg two from each other. Your answer to this challenge should output these separated parts in their appropriate orientation.

For instance, when disassembling the single table shown in the section "Tables", you should get the following:

```
-------

| |
| |

```

Disassembling the complex arrangement above gives this:

```
--------- --- ------------- ------------------- --------------- -----------------------------------

| | | | | | | | | | | |
| |         | | | | | |
            | | | |
                | |

```

Your answer to this challenge can choose to output in this neat format, where the tops are laid next to each other at the top of the output and all the legs are laid next to each other below the tops, with all the parts in their correct orientation, or you can choose to output a list of all the parts, but in the correct orientation. What you may not do, however, is output the input unchanged and say "look, all the parts are there". To assess whether an output format is reasonable, determine whether or not the output format shows a clear separation between the parts. **You may output the parts in any order**, as long as the output format remains reasonable. (No outputting full tables, for instance.) Note also that if outputting in the neat format, all tabletops must be at the top of the output, and the legs below all the tabletops. However, the order of the tabletops and the order of the legs are both flexible.

Additionally, output may also be in the form of two lists, one representing a list of tabletop lengths and one representing a list of leg lengths. This output form may only be used if the lists are clearly separate.

Input may be ASCII art as shown above, a list of lines, or a character matrix.

## More examples

Input:

```
--
||

```

Output, which will hereinafter be in the neat format:

```
--

| |

```

Why? Your answer should not treat `||` as one leg; a leg is only one pipe "thick".

Input:

```
----
||||

```

Output:

```
-- --

| | | |

```

Why? Tables have only two legs. Once your answer sees the first leg of a table, it should only treat the area from that leg until the next leg it sees, as a table. Thus, there are two tables in the above example, not one.

Input:

```
---------
|   ||  |

```

Output:

```
----- ----

| | | |

```

Why? See above.

Input:

```
---
| |---
---| |
| || |

```

Output:

```
--- --- ---

| | | | | |
        | |

```

Input:

```
---
| |
--------
|||    |

```

Output:

```
--- -- ------

| | | | | |

```

Input:

```
                           ---
---------------------------| |
|                         || |
|                         || |
|                         || |
------------------------------
||||||||||||||||||||||||||||||
||||||||||||||||||||||||||||||
||||||||||||||||||||||||||||||

```

Output:

```
--------------------------- --- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
                                                                | |

```

## More notes

You may assume that tables will not be "completely underneath tables", that is, no input like this will be given:

```
--------------------
|                  |
|    -------       |
|    |     |       |
|    |     |       |

```

You may assume that the arrangement is "stable", so there are no legs "hanging in midair":

```
-----------------
|               | <- this leg is hanging in midair
|               |
----------
|        |

```

On a related note, the heights of the legs of a table are the same (this is stated above, but I want to make it extremely clear). This means that this input will not be given:

```
-----------
|         |
-------   |
|     |   |

```

You may assume that tables are stacked only in the correct orientation, so no arrangements like this:

```
|-------
|
|
|-------
-----------
|         |

```

or this:

```
|           |
|           |
|           |
-------------
-------------
|           |

```

This is , so the shortest code, measured in bytes, wins.

*Related*

# Answer
> 7 votes
# , 55 bytes

```
([:(1+_2-~/\])@I.,.@'-|'E.]);&(0-.~,)'\|+'#&>@rxall"1|:
```

Attempt This Online!

-12 after seeing rule change allowing lists of lengths as the output.

## original answer outputting art, 78 67 bytes

```
([:('-'<@#~"+1+_2-~/\])@I.,.@'-|'E.]),&(a:-.~,)'\|+',.&.>@rxall"1|:

```

Try it online!

Note: Regex in J is broken on TIO, so the link above is just for the byte count. I will paste below some output run on my computer on J903.

Also, note that we pre-process the input into lines of text, and that J requires boxing for heterogeneous lists, hence the boxed output.

```
echo f ];._2 ] 0 :0
---    ----
| |--- |  |
---| |
| || |
)

echo f ];._2 ] 0 :0
---
| |
--------
|||    |
)

```

Outputs:

```
┌───┬────┬───┬───┬─┬─┬─┬─┬─┬─┬─┬─┐
│---│----│---│---│|│|│|│|│|│|│|│|│
│   │    │   │   │ │ │ │ │|│|│ │ │
└───┴────┴───┴───┴─┴─┴─┴─┴─┴─┴─┴─┘
┌───┬──┬──────┬─┬─┬─┬─┬─┬─┐
│---│--│------│|│|│|│|│|│|│
└───┴──┴──────┴─┴─┴─┴─┴─┴─┘

```

## how

* The "legs" part is just doing a regex search for repeated pipes `\|+` in the transpose of the input, and then converting it back to one pipe per line.
* The "tabletop" part is slightly more interesting, because we have to account for tables that are pushed up next to each other -- ie, sometimes we can only find the demarcations between tabletops by looking at the legs. J has a built-in ability to search for box-shape strings withing a 2D grid, and so we use `E.` to find instances of:

```
-
|

```

within the input. We then do some arithmetic on those found indexes to find the length of all tabletops, and convert those lengths back to ascii strings like `-----`.

# Answer
> 5 votes
# Jelly, 23 bytes

```
=”|µZṣ€0Ẏ¹Ƈ,<ƝT€Fr2/ƲẈ€

```

A monadic Link accepting a list of lines that yields a list of lists of leg lengths and tabletop lengths.

**Try it online!**

### How?

```
=”|µZṣ€0Ẏ¹Ƈ,<ƝT€Fr2/ƲẈ€ - Link: list of lists of characters, L
=”|                     - L equals '|'? (vectorises)
   µ                    - new monadic chain - f(X=that)
    Z                   - transpose X
     ṣ€0                - split each at zeros
        Ẏ               - tighten
         ¹Ƈ             - keep truthy (non-empty) ones
                          -> our legs (as lists of 1s)
                    Ʋ   - last four links as a monad - f(X):
             Ɲ          -   for neighbours:
            <           -     less than?
              T€        -   truthy indices of each
                F       -   flatten
                  2/    -   reduce pairs by:
                 r      -     inclusive range
                            -> our tabletops (as lists of positive integers)
           ,            - pair legs and tabletops
                     Ẉ€ - for each: length of each

```

# Answer
> 3 votes
# Charcoal, ~~64~~ 62 bytes

```
ＷＳ⊞υι≔Ｅθ⪫⪪⭆υ§λκ-|¦#|θＦθＦΦ⪪ι#λ«Ｐ↓№κ|→→»←⸿⸿ＦＥυ⌕Ａ⭆θ§λκ#Ｗι«⊕⁻⊟ι⊟ι→

```

Try it online! Link is to verbose version of code. Takes input as a rectangular list of newline-terminated strings. Explanation:

```
ＷＳ⊞υι

```

Input the stack of tables.

```
≔Ｅθ⪫⪪⭆υ§λκ-|¦#|θ

```

Transpose the stack and identify the ends of the tabletops i.e. those parts above the legs.

```
ＦθＦΦ⪪ι#λ«

```

For each column of the original stack split it on tabletop ends, dropping the first element (which is the space above the first end) and loop over the resulting legs.

```
Ｐ↓№κ|→→

```

Print the length of the leg vertically (which Charcoal automatically translates into a line of `|`s) without moving the cursor and then allow two columns for the next leg.

```
»←⸿⸿

```

Move up to the start of the previous row but one.

```
ＦＥυ⌕Ａ⭆θ§λκ#

```

Transpose the stack back and find all of the tabletop ends.

```
Ｗι«⊕⁻⊟ι⊟ι→

```

Loop over the ends in pairs, print the inclusive difference between each pair (which Charcoal automatically translates into a line of `-`s) and then allow a column for the next tabletop.

# Answer
> 0 votes
# 05AB1E (legacy), 27 bytes

```
ζD„-|T:ζS®Ãƶþι`α>sS'|QγO0K‚

```

Input as a list of lines; output as a pair of integer-lists, the first being the width of the table-tops and the second the length of the table-legs.

Try it online or verify all test cases.

**Explanation:**

Uses the legacy version of 05AB1E because it can zip/transpose on a list of strings, whereas the new version of 05AB1E would require a character-matrix.

Step 1: Get the lengths of the table-tops:

```
ζ         # Zip/transpose the (implicit) input-list; swapping rows/columns
 D        # Duplicate this list of columns
  „-|T:   # Replace each "-|" with "10"
       ζ  # Zip/transpose back to a list of lines
S         # Convert the list to a flattened list of characters
 ®Ã       # Only keep all "-" and "1" characters
   ƶ      # Multiply each by its 1-based index
    þ     # Only keep the integers, removing any "-"-strings
     ι    # Uninterleave into two lists
      `   # Pop and push both lists separated to the stack
       α  # Get the absolute difference between the values at the same positions
          # of the two lists
        > # Increase these integers by 1

```

Step 2: Get the lengths of the table-legs:

```
s         # Swap so the duplicated list of columns is at the top
 S        # Convert it to a flattened list of characters
  '|Q    '# Check for each character if it's equal to "|"
     γ    # Group the list of 0s/1s into equal adjacent values
      O   # Sum each group
       0K # Remove all 0s

```

Step 3: Output the result:

```
‚         # Pair the two lists of lengths together
          # (after which it is output implicitly as result)

```

# Answer
> 0 votes
# SnakeEx, 81 bytes

```
m:[({a<R>A}{b<R>A}*{a<R>P}~([^|]*(|[^|]*)%{2}*$))(<R>(~\-)|+!|)]
a:\-<L>~|
b:\-~

```

Highlights each tabletop and each leg as a separate match. Try it here!

### Explanation

Here's a somewhat ungolfed version:

```
main:[{top<>}{leg<>}]
leg:<R>(~\-)|+!|
top:{left<R>A}{mid<R>A}*{right<R>P}{check<>S}
left:\-~|
mid:\-~
right:\-<L>~|
check:[^|]*(|[^|]*)%{2}*$

```

The `main` snake uses brackets to match *either* a `top` *or* a `leg`.

To match a `leg`:

```
<R>           Turn right (initially, the match pointer faces east, so turn south)
     \-       Match a literal hyphen
   (~  )      but don't mark it as part of the result
        |+    Match one or more pipes
          !|  Assert that it's impossible to match another pipe

```

To match a `top`:

```
{left    }                                 Match the left edge of a table
     <R>                                   turning right (south) to do so
        A                                  and advance one step to the east afterward
          {mid    }*                       Match 0 or more middle sections
              <R>                          turning right (south) to do so
                 A                         and advance one step to the east each time
                    {right    }            Match the right edge of the table
                          <R>              turning right (south) to do so
                             P             and move the cursor to the end of that match
                               {check<> }  Check that this isn't part of any other
                                           table (see below)
                                       S   but don't mark that as part of the result

```

The `left` edge is:

```
\-    Literal hyphen
   |  Followed by a pipe
  ~   which isn't marked as part of the result

```

(Recall that we're moving southwards when we match this.)

Similarly, the `mid` is `\-~`  (same thing but with a space). The `right` edge is the same as the `left`, except it adds a `<L>` to turn left (east). This positions the match cursor just to the east of the table leg, ready to run the `check`.

We need `check` because unlike regex, SnakeEx uses overlapping matches. So input like this

```
----
||||

```

would find not two but three matches for `top`, counting the two hyphens in the middle. To prevent such incorrect matches, we'll assert that the right side of each table must be followed by an even number of table legs.

```
[^|]*(|[^|]*)%{2}*$
                     After a table's right leg, proceeding eastward, match:
[^|]*                0 or more non-leg characters
     (      )        This sequence:
      |               Leg character
       [^|*]          0 or more non-leg characters
             %{2}    Repeated twice
                 *   Repeated 0 or more times
                  $  Edge of input

```

For the golfed version, we basically just combine `left` with `right` and inline `top`, `leg`, and `check` into `main`.

# Answer
> 0 votes
# Python3, 456 bytes:

```
lambda x:' '.join(a for *_,a in{(a,b+1,I,u[a:b+1])for I,u in E(x.split('\n'))for B,U in E(x.split('\n'))for a,b in g(U)if B-I==1 and set(u[a:b+1])=={'-'}})+'\n\n'+'\n'.join(' '.join(m)for m in Z(*sorted(j for k in Z(*x.split('\n'),fillvalue='')for j in findall('\|+',''.join(k))),fillvalue=' '))
from re import*
from itertools import*
E=enumerate
Z=zip_longest
r=lambda x:[(x[i],x[i+1])for i in range(0,len(x),2)]
g=lambda x:r([i for i,a in E(x)if a=='|'])

```

Try it online!

# Answer
> 0 votes
# Vyxal, 32 bytes

```
\|=:∩0v€Þfꜝ$2lƛÞṡƒ<T›;f2ẇvƒṡ"vvL

```

Try it Online!

Port of Jelly.

Port of 05AB1E ended up at same byte count: Try it Online!

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


title: Triangle Tripler

text:
# Question
Title: Triangle Tripler
Simpler version of this

## Task

You must create a program that outputs a triangle of a given size N.

* A triangle is made of 3 identical triangles
* A triangle of size N should be made of N lines
* A triangle's line starts from 1 star, and increases by 2 stars each line

## Test Cases:

```
1 ->

 *
* *

3 ->

     *
    ***
   *****
  *     *
 ***   ***
***** *****

5 ->

         *
        ***
       *****
      *******
     *********
    *         *
   ***       ***
  *****     *****
 *******   *******
********* *********

10 ->

                   *
                  ***
                 *****
                *******
               *********
              ***********
             *************
            ***************
           *****************
          *******************
         *                   *
        ***                 ***
       *****               *****
      *******             *******
     *********           *********
    ***********         ***********
   *************       *************
  ***************     ***************
 *****************   *****************
******************* *******************

```

## Scoring:

This is code-golf so shortest code size wins!

Trailing whitespace is allowed

Credits to Ninsuo for the puzzle

# Answer
> 5 votes
# Canvas, 11 bytes

```
*×［］：｛│］∔／│

```

Try it here!

##### Explanation:

```
*x[]:{|]+/| | Full code (replaced with ASCII)
------------+-----------------------------------------
*           | Push '*'
 x          | Repeat <input> times horizontally
  []        | List of prefixes
    :       | Duplicate
     { ]    | Map over each element
      |     | Palindromize horizontally with 1 overlap
        +   | Add the two lists together
         /  | Anti-diagonalize
          | | Palindromize horizontally with 1 overlap

```

# Answer
> 9 votes
# Python 3, 74 bytes

```
lambda n:[print(i//n*f"{i%n*'**'+'*':^{8*n>>i//n}}")for i in range(n,3*n)]

```

Try it online!

Deera Wijesundara saved 2 bytes by suggesting `print`-based I/O instead of `"\n".join`.

## Explanation

For each `i in range(n,3*n)`, we center `i%n*2+1` asterisks in `8*n>>i//n` spaces and repeat this string `i//n` times.

| `i` | `i%n` | `i%n*'**'+'*'` | `8*n>>i//n` | `i//n` |
| --- | --- | --- | --- | --- |
| n | 0 | `*` | 4n | 1 |
| n+1 | 1 | `***` | 4n | 1 |
| n+2 | 2 | `*****` | 4n | 1 |
|  |  |  |  |  |
| 2n | 0 | `*` | 2n | 2 |
| 2n+1 | 1 | `***` | 2n | 2 |
| 2n+2 | 2 | `*****` | 2n | 2 |
|  |  |  |  |  |

* `i%n*'**'+'*'` is a byte shorter than `(i%n*2+1)*'*'`.
* `f"{s:^{n}}"` is an icky but short way to write `(s).center(n)`.

# Answer
> 5 votes
# Charcoal, 12 bytes

```
ＮθＦ²«Ｇ⌊θ*↖‖Ｏ

```

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

```
Ｎθ

```

Input the size.

```
Ｆ²«

```

Repeat twice.

```
Ｇ⌊θ*

```

Draw half of a triangle. The first time, this draws the left half of the bottom left triangle; the second time, the left half of the top triangle.

Move to the next triangle. (See below as to why this moves left instead of right. This command has no effect on the second iteration.)

```
‖Ｏ

```

Reflect to complete the triangle. On the first iteration, this also reflects the current position to where it needs to be. On the second iteration, this also reflects the bottom left triangle to create the bottom right triangle.

# Answer
> 4 votes
# 05AB1E, ~~20~~ 16 bytes

```
·ÅÉ'*×DāRúí.º«.c

```

Try it online or verify the test cases in the range \\$\[1,10\]\\$.

**Explanation:**

```
           #  e.g. input=3
·          # Double the (implicit) input-integer
           #  STACK: 6
 ÅÉ        # Pop and push a list of all odd numbers below this
           #  STACK: [1,3,5]
   '*×    '# Map each to that many "*" as strings
           #  STACK: ["*","***","*****"]
D          # Duplicate this list
           #  STACK: ["*","***","*****"],["*","***","*****"]
 ā         # Push a list in the range [1,length] (without popping)
           # (which is basically a list in the range [1,input])
           #  STACK: ["*","***","*****"],["*","***","*****"],[1,2,3]
  R        # Reverse it to range [input,1]
           #  STACK: ["*","***","*****"],["*","***","*****"],[3,2,1]
   ú       # Pad the strings of the top copy with that many leading spaces
           #  STACK: ["*","***","*****"],["   *","  ***"," *****"]
    í      # Reverse each string in the list so the spaces are trailing
           #  STACK: ["*","***","*****"],["*   ","***  ","***** "]
     .º    # Overlapping mirror each string
           #  STACK: ["*","***","*****"],["*     *","***   ***","***** *****"]
       «   # Merge the two lists of lines together
           #  STACK: ["*","***","*****","*     *","***   ***","***** *****"]
        .c # Join each line by newlines, and centralize it
           #  STACK: "     *\n    ***\n   *****\n  *     *\n ***   ***\n***** *****"
           # (after which the result is output implicitly)

```

# Answer
> 4 votes
# Excel, 94 bytes

```
=LET(x,SEQUENCE(A1*2),a,REPT(" ",A1*2-x),b,REPT("*",MOD(x-1,A1)*2+1),a&b&REPT(a&" "&a&b,x>A1))

```

Link to Spreasheet

# Answer
> 4 votes
# JavaScript (ES6), 80 bytes

```
f=(n,x=y=h=n*2)=>y?` *
`[--x+h?x>=y-h&x<=h-y^y<=n&x*x<y*y:(x=h,y--,2)]+f(n,x):''

```

Try it online!

### Patterns

Coordinates:

* \\$y\\$ goes from \\$2n\\$ at the top to \\$1\\$ at the bottom
* \\$x\\$ goes from \\$2n-1\\$ on the left to \\$-2n+1\\$ on the right

The examples below are given with \\$n=3\\$.

```
x >= y - h        x <= h - y

XXXXXX-----       -----XXXXXX       -----X-----
XXXXXXX----       ----XXXXXXX       ----XXX----
XXXXXXXX---  AND  ---XXXXXXXX  -->  ---XXXXX---
XXXXXXXXX--       --XXXXXXXXX       --XXXXXXX--
XXXXXXXXXX-       -XXXXXXXXXX       -XXXXXXXXX-
XXXXXXXXXXX       XXXXXXXXXXX       XXXXXXXXXXX

y <= n            x² < y²

-----------       XXXXXXXXXXX       -----------
-----------       -XXXXXXXXX-       -----------
-----------  AND  --XXXXXXX--  -->  -----------
XXXXXXXXXXX       ---XXXXX---       ---XXXXX---
XXXXXXXXXXX       ----XXX----       ----XXX----
XXXXXXXXXXX       -----X-----       -----X-----

-----X-----       -----------       -----X-----
----XXX----       -----------       ----XXX----
---XXXXX---  XOR  -----------  -->  ---XXXXX---
--XXXXXXX--       ---XXXXX---       --X-----X--
-XXXXXXXXX-       ----XXX----       -XXX---XXX-
XXXXXXXXXXX       -----X-----       XXXXX-XXXXX

```

# Answer
> 4 votes
# , 39 37 bytes

```
'* '{~](](=|.)/@,:{.)(>i.@-+/|@i:)@+:

```

Try it online!

-2 thanks to Lynn!

*Includes leading whitespace that can be removed with a few bytes.*

Not super golfy but the concept is fun:

## how

Let's take n=3 as our example:

* `(>i.@-+/|@i:)@+:` Create a single triangle double the requested input size:

```
0 0 0 0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 1 1 1 0 0 0 0 0
0 0 0 0 1 1 1 1 1 0 0 0 0
0 0 0 1 1 1 1 1 1 1 0 0 0
0 0 1 1 1 1 1 1 1 1 1 0 0
0 1 1 1 1 1 1 1 1 1 1 1 0

```
* `](..........{.)` Take the first n lines of that:

```
0 0 0 0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 1 1 1 0 0 0 0 0
0 0 0 0 1 1 1 1 1 0 0 0 0

```
* `].......,:` And append it to the big triangle, auto-filling the extra rows with zeros:

```
0 0 0 0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 1 1 1 0 0 0 0 0
0 0 0 0 1 1 1 1 1 0 0 0 0
0 0 0 1 1 1 1 1 1 1 0 0 0
0 0 1 1 1 1 1 1 1 1 1 0 0
0 1 1 1 1 1 1 1 1 1 1 1 0

0 0 0 0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 1 1 1 0 0 0 0 0
0 0 0 0 1 1 1 1 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0

```
* `(=|.)/@` Reverse rows of the little triangle and check where the planes are still equal:

```
0 0 0 0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 1 1 1 0 0 0 0 0
0 0 0 0 1 1 1 1 1 0 0 0 0
0 0 0 1 1 1 1 1 1 1 0 0 0
0 0 1 1 1 1 1 1 1 1 1 0 0
0 1 1 1 1 1 1 1 1 1 1 1 0

     = elementwise?

0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 1 1 1 1 0 0 0 0
0 0 0 0 0 1 1 1 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0 0 0 0

           v

1 1 1 1 1 1 0 1 1 1 1 1 1
1 1 1 1 1 0 0 0 1 1 1 1 1
1 1 1 1 0 0 0 0 0 1 1 1 1
1 1 1 0 1 1 1 1 1 0 1 1 1
1 1 0 0 0 1 1 1 0 0 0 1 1
1 0 0 0 0 0 1 0 0 0 0 0 1

```
* `'* '{~` Convert to asterisks and spaces:

```
      *
     ***
    *****
   *     *
  ***   ***
 ***** *****

```

# Answer
> 3 votes
# Python 3.8 (pre-release), 114 bytes

```
def f(n,x=1):[print([n*(p:=" "),(t:=(s:=p*(~-n-i))+"*"+"**"*i+s)+p][x]+t)for i in range(0if x and f(n,0)else 0+n)]

```

Try it online!

## Less-golfed version

```
def f(n, drawingTopPart=True):
    for i in range(n):
        space = " "
        spacing = space*(n-i-1)
        stars = spacing + '*' + '**' * i + spacing
        print(n*space + stars) if drawingTopPart else print(stars + space + stars)
    if drawingTopPart:
        f(n, False)

```

# Answer
> 3 votes
# Ruby, 70 bytes

```
->n{a=[]
n.times{|i|puts" "*n+b=(?**i-=~i).center(n*2)
a<<b*2}
puts a}

```

Try it online!

Prints the single triangle as it iterates while building up an array of double triangles.

Then dumps a printout of the array at the end.

# Answer
> 3 votes
# Julia 1.0, 86 bytes

```
n/k=1:n.|>j->((s=" "^(k-j))*" "*"*"^(2j-1)*s)^(1+(n==k))
~n=n./[2n,n].|>l->println.(l)

```

Try it online!

Golfing David Scholz's answer (cannot comment under other people solutions yet!)

Basically got rid of `join` by nesting the `println` call. `println` also gives you trailing `\n` for free. Finally I removed `i` iteration index as it can be expressed in terms of `j`

# Answer
> 2 votes
# Python NumPy, 95 bytes

```
lambda n:where((t:=tril(1>tri(4*n)[::-1])[2*n:])^(t[::-1]&t[:,n:n+1]),*'* ')
from numpy import*
```

Attempt This Online!

#### Old Python NumPy, 99 bytes

```
lambda n:[r:=tri(n),z:=0*r,l:=1-r[::-1]]and where(bmat("z l r z;l r l r"),*'* ')
from numpy import*
```

Attempt This Online!

Returns a numpy array of "\*"s and " "s.

# Answer
> 2 votes
# Julia 1.0, 58 bytes

```
!n=1:2n.|>i->((s=' '^(2n-i))*'*'^2(~-i%n)*"* $s")^-~+(i>n)

```

Try it online!

output is a list of strings

# Answer
> 1 votes
# Pari/GP, 79 bytes

```
n->for(i=1,m=2*n,print(Strchr([32+10*(i<=n||i+abs(j)>m&&i>-j)|j<-[1-m..i-1]])))

```

Try it online!

# Answer
> 1 votes
# Python 3.8 (pre-release), 96 bytes

```
lambda n:'\n'.join(' '*(d:=2*n-1-i)+(c:='*'*(1+i%n*2))+('  '*d+' '+c)*(i>=n)for i in range(n+n))

```

Try it online!

# Answer
> 1 votes
# Retina 0.8.2, 54 bytes

```
.+
$**
.
$._$*_$.'$* $`*$`$.'$* ¶
_+
$&$%'¶$%'
_

O`

```

Try it online! Link includes test cases. Explanation:

```
.+
$**

```

Convert the input to a string of asterisks.

```
.
$._$*_$.'$* $`*$`$.'$* ¶

```

Create a triangle of asterisks indented by underscores. `$._$*_` is the string of asterisks replaced by underscores. `$.'$*`  is the space padding on either side of the triangle. `$`*$`` is the triangle.

```
_+
$&$%'¶$%'

```

Duplicate each line. `$&$%'` ends up keeping the first line the same, while the `$%'`  causes the second copies of the lines to have an extra copy of the triangle, but without the indent.

```
_

```

Convert the underscores back to spaces.

```
O`

```

Sort the lines into order. This puts the lines with the most spaces first, thus grouping the top triangle's lines back together (and also the remaining lines of the bottom double triangle of course).

# Answer
> 1 votes
# APL+WIN, 41 bytes

Prompts for n

```
(⌽0 1↓m),m←⊃(-⍳2×n)↑¨(m,¯1+2×m←⍳n←⎕)⍴¨'*'

```

Try it online! Thanks to Dyalog Classic

# Answer
> 1 votes
# Vyxal `C`, 35 bytes

```
λhd›×*;→ẋė:£ƛ←†;¥ƛ←†:?d‹nhd-ð*JȮJ;J

```

Try it Online!

## Explanation

```
λhd›×*;→  Simple Lambda
λ         Start lambda
 h        Get head
  d›      Double and add 1
    ×*    Repeat it "*" time
      ;→  Close lambda and set it to var.

ẋė:£ƛ←†;  Top triangle
ẋė        Make an empty list with length n and generate tuple (index, item)
  :£      Duplicate tuple and set it to the register
    ƛ     Map through tuple of (index, item)
     ←†;  Get var, call it and close lambda

¥ƛ←†:?d‹nhd-ð*JȮJ;J  Bottom left ans right triangle
¥ƛ                   Get register (index, item) and start a mapping lambda
  ←†:                Get var, call it and duplicate
     ?d‹             Double n and increment by one
        hd-          Get head, double and decrement by one
           ð*        Repeat space that many times
             J       Join the left triangle row with spaces
              ȮJ     Get second to last item (left triangle row) and join
                ;J   Join the top triangle with the bottom triangles

C flag centers everything with spaces.

```

# Answer
> 1 votes
# Julia, 129 bytes

```
l="\n"
△(n,k)=((i,j)->(" "^(k-j+1)*"*"^i*" "^(k-j))^(n==k ? 2 : 1)).(1:2:2n,1:n)
~n=print(join(△(n,2n),l),l,join(△(n,n),l))

```

Try it online!

I had a hard time with this one, any optimizations are highly appreciated!

The function  takes two arguments `n,k` whereby `n` is the size of the triangle. The parameter `k` determines the number of whitespaces for each row of the triangle.

I have not found a way to get rid of the `join` operator, which joins the array of strings with `\n` as a separator. This costs me 8 bytes already.

# Answer
> 0 votes
# Vyxal `C`, 12 bytes

```
d~∷×*øĊDZvṄJ

```

Try it Online!

## How?

```
d~∷×*øĊDZvṄJøĊ⁋
d               # Double the (implicit) input
 ~∷             # Filter-keep for only odd numbers (the number is implicitly converted into a range [1,n])
   ×*           # Repeat an asterisk that many times for each
     øĊ         # Pad each with spaces to center
       D        # Triplicate
        ZvṄ     # Zip the top two copies together, and join by spaces
           J    # Join these two lists together
                # C flag centers and joins by newlines

```

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


title: Are the beams above or below the notes?

text:
# Question
Title: Are the beams above or below the notes?
In musical notation, groups of notes shorter than one beat are joined together by a line at the bottom called a beam. Here are a few bars of music with the beams highlighted:

(Taken from *Second Suite in F* by Gustav Holst; you can hear how these notes sound at 0:13 in this video.)

You may notice that beam #6 is above the ovals that define the notes, and its vertical lines attached to their right sides, while the others are below the notes and attached to their left. What determines this? There are a few simple rules, which are the subject of this challenge.

1. By default, the placement of the beam is determined by its highest or lowest note. If the note farthest from the centermost line of the staff is above it, then the beam goes below the notes. If the note with the highest absolute value is above the centermost line of the staff, then the beam goes below the notes.
2. If the highest and the lowest note are the same distance from the center line, the direction of the beam is determined by which side of the center line the majority of notes in the beam lie on. If a majority of notes lie above the centre line, the beam goes down. If a majority of notes lie below the centre line, the beam goes up. Notes on the center line do not count either way.
3. If the highest and the lowest note are the same distance from the center line, and equally many notes lie above and below the center line, the beam may be placed either above or below the notes.

In the sample notation above, the beams of clusters #1, 2, 3, and 5 are determined to be below the notes because their highest notes (their second, second, first, and third respectively) are above the center line. #6's lowest note is its first/third note, which is below the center line. #4's highest and lowest note are equally distant from the center line and it contains no majority either way. Its beam could be placed either above or below, but my composition program renders it as below.

# Your commission

Write a program that takes in a list of integers, which may be zero or negative, and outputs a truthy/falsey value. These integers represent notes and their distance from the center line; positive values represent notes above the line, zero represents notes on the line, and negative values represent notes below the line. Determine, given a cluster of notes that sit those distances from the center line, which way the cluster's beam should go; output `TRUE` if the beam should go above the notes and `FALSE` if the beam should go below the notes. To restate the rules above and give the algorithm:

1. Find the number in the list with the largest absolute value. If it is greater than zero, output `FALSE`. If it is less than 0, output `TRUE`. If it is 0, output may be `TRUE` or `FALSE` as convenient. If there are positive and negative numbers with the same, maximal absolute value, continue.
2. Determine whether the majority of numbers are positive and negative, ignoring zeroes. If a majority of numbers are positive, output `FALSE`. If a majority of numbers are negative, output `TRUE`.
3. Otherwise, output may be `TRUE` or `FALSE` as convenient.

You might be given only one number. In that case, it has the highest absolute value, so if it is greater than 0 output false; if it is less than zero output true; and if it is 0 you may output true or false.

You may not assume the numbers are sorted.

# Test cases

```
5, 4, 3 -> FALSE                     # #3
1, 0, -1 -> TRUE or FALSE            # #4
0, 1, 2, 0 -> FALSE                  # #5
-2, -1, -2 -> TRUE                   # #6
3, 1, 4, 1, 5, -9 -> TRUE            # Largest absolute value below 0, rule 1
3, 1, 4, 1, 5, -5 -> FALSE           # Largest absolute value tied, determined by majority, rule 2
3, 1, -3, -1, 5, -5 -> TRUE or FALSE # Largest absolute value tied and no majority, unspecified

```

# Answer
# Jelly, ~~13~~ 9 bytes

```
ṠÆm+Ṁ+Ṃ<0

```

Try it online!

A monadic link taking a list of integers and returning a Jelly Boolean indicating the direction of the stems as per the spec.

Modified with inspiration from @RobinRyder’s excellent R answer so be sure to upvote that one too!

## Explanation

```
Ṡ         | Signs
 Æm       | Mean
   +Ṁ     | Add max (of original argument)
     +Ṃ   | Add min (of original argument)
       <0 | Less than 0

```
> 2 votes

# Answer
# , 40 bytes

```
function(x)min(x)+max(x)+mean(sign(x))<0

```

Try it online!

If `min(x)+max(x)` is non-zero, its sign corresponds to the note farthest from the centre and gives the direction of the beam.

Adding `mean(sign(x))` can never change the sign. Indeed, either (a) all notes are of the same sign and `mean(sign(x))` is of the same sign as `min(x)+max(x)` or (b) notes are of both signs and `mean(sign(x))` is strictly in \\$(-1,1)\\$ whereas `min(x)+max(x)` is an integer, so the sign of the sum is unchanged.

If `min(x)+max(x)==0`, the sign of the mean decides the direction.

If undecided, defaults to `FALSE`.
> 10 votes

# Answer
# Python 3, 55 bytes

```
lambda a:(min(a)+max(a)or sum((i>0)-(i<0)for i in a))<0

```

Try it online!
> 4 votes

# Answer
# JavaScript (ES6),  ~~66~~  64 bytes

```
a=>(a.map(m=v=>(k+=v>0||-!!v,a=v>a?a:v,m=v<m?m:v),k=0)|a+m||k)<0

```

Try it online!

### Commented

```
a => (                   // a[] = input array, re-used to store the minimum value
  a.map(m =              // initialize m = maximum to a non-numeric value
    v => (               // for each value v in a[]:
      k +=               //   update k:
        v > 0 ||         //     increment it if v > 0
        -!!v,            //     decrement it if v < 0
      a = v > a ? a : v, //   update a to min(a, v) (always v if a is non-numeric)
      m = v < m ? m : v  //   update m to max(m, v) (always v if m is non-numeric)
    ),                   //
    k = 0                //   start with k = 0
  )                      // end of map()
  | a + m                // use a + m if it's not equal to 0
  || k                   // otherwise, use k
) < 0                    // test if the above value is negative

```
> 3 votes

# Answer
# 05AB1E, ~~15~~ ~~14~~ 13 bytes

```
ÄZQÏ‚¤Ëè.±Od≠

```

Output will be false if either of the two is a possible output.

-1 byte and fixed a bug for `[0,0,1,-1,-1]` thanks to *@Grimmy*.

Try it online or verify all test cases.

**Explanation:**

```
Ä         # Convert each value in the (implicit) input-list to their absolute value
          #  i.e. [3,1,-5,4,1,5,-5] → [3,1,5,4,1,5,5]
          #  i.e. [0,1,-2,0] → [0,1,2,0]
 Z        # Push the maximum of these absolute values (without popping the list itself)
          #  i.e. [3,1,5,4,1,5,5] → 5
          #  i.e. [0,1,2,0] → 2
  Q       # Check for each absolute value whether it's equal to this maximum
          #  i.e. [3,1,5,4,1,5,5] and 5 → [0,0,1,0,0,1,1]
          #  i.e. [0,1,2,0] and 2 → [0,0,1,0]
   Ï      # And only leave the values of the (implicit) input-list at the truthy indices
          #  i.e. [3,1,-5,4,1,5,-5] and [0,0,1,0,0,1,1] → [-5,5,-5]
          #  i.e. [0,1,-2,0] and [0,0,1,0] → [-2]
    ‚     # Pair it with the (implicit) input-list
          #  i.e. [3,1,-5,4,1,5,-5] and [-5,5,-5] → [[3,1,-5,4,1,5,-5],[-5,5,-5]]
          #  i.e. [0,1,-2,0] and [-2] → [[0,1,-2,0],[-2]]
     ¤    # Push the last value of this pair (without popping) again
      Ë   # And check if all values are equal (1 if truthy; 0 if falsey)
          #  i.e. [-5,5,-5] → 0
          #  i.e. [-2] → 1
       è  # Use it to index into the pair
          #  i.e. [[3,1,-5,4,1,5,-5],[-5,5,-5]] and 0 → [3,1,-5,4,1,5,-5]
          #  i.e. [[0,1,-2,0],[-2]] and 1 → [-2]
.±        # Take the signum of each value
          #  i.e. [3,1,-5,4,1,5,-5] → [1,1,-1,1,1,1,-1]
          #  i.e. [-2] → [-1]
  O       # Sum those together
          #  i.e. [1,1,-1,1,1,1,-1] → 4
          #  i.e. [-1] → -1
   d      # Check if it's non-negative (>=0)
    ≠     # And invert the boolean (so basically check if it's negative / <0)
          #  i.e. 4 → 1 → 0
          #  i.e. -1 → 0 → 1
          # (after which this is output implicitly as result)

```
> 2 votes

# Answer
# Retina 0.8.2, 58 bytes

```
O#`\S+
\d+
$*
+` -1+ +1+

^-(1+)($| ((?!.*\1$)|-.* \1$))

```

Try it online! Link includes test cases. Explanation:

```
O#`\S+

```

Sort the numbers numerically.

```
\d+
$*

```

Convert to unary.

```
+` -1+ +1+

```

Match inner pairs of negative and positive numbers and delete them until only one negative and/or positive number remains.

```
^-(1+)($| ((?!.*\1$)|-.* \1$)

```

Output a truthy value if the (largest) negative number is the only number, or if its absolute value is greater than the largest positive number, or if another negative number remains and its absolute value equals the largest positive number.
> 1 votes

# Answer
# PHP, ~~178~~ ~~127~~ ~~111~~ ~~107~~ 105 bytes

```
<?php foreach($argv as$n){$c+=$s=$n<=>0;($a=$n*$s)>$m&&$x=$s;$a-$m||$x=0;$a>=$m&&$m=$a;}echo$x?$x<0:$c<0;

```

Try it online!

## Ungolfed

```
<?php
$notes = explode(',', $argv[1]);

$max_note = 0;
$max_sign = 0;
$counts = 0;
foreach ($notes as $note) {
    $sign = $note <=> 0;
    $counts += $sign;

    if (abs($note) > $max_note) {
        $max_sign = $sign;
    } elseif (abs($note) == $max_note) {
        $max_sign = 0;
    }

    if (abs($note) >= $max_note) {
        $max_note = abs($note);
    }
}

echo ($max_sign == 0) ? ($counts < 0) : ($max_sign == -1);
?>

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 26 bytes

```
Min@#+Max@#+Mean@Sign@#<0&

```

Try it online! Pure function. Takes a list of numbers as input, and returns `True` or `False` as output. Uses the same logic as Robin Ryder's answer. Additionally, here's the 49-byte function I came up with myself:

```
Tr[{}⋃Sign@MaximalBy[#,Abs]/.{-1,1}->Sign@#]<0&

```
> 1 votes

# Answer
# , 17 bytes

```
0>>./+<./+#%~1#.*

```

Try it online!

Based on Robin Ryder's insightful alrogithm - make sure to upvote his.

* `0>` Is 0 greater than...
* `>./` The max...
* `+` Plus...
* `<./` The min...
* `+` Plus...
* `#` The input length...
* `%~` Divided into...
* `1#.` The sum of...
* `*` The signs.
> 1 votes

# Answer
# Burlesque, 23 bytes

```
psJ)snav/^>]j<]CL++@0.<

```

Try it online!

Following the logic of @RobinRyder. Takes input as `A B C ...`

```
psJ  # Parse input to list of ints and dup
)sn  # Map sign
av   # Average (returns double)
/^   # Swap and Dup
>]   # Max
j<]  # Min
CL++ # Collect all and sum
@0.< # <0.0

```
> 1 votes

# Answer
# C (gcc), ~~118~~ ~~115~~ 109 bytes

```
#define A a[p]
p;s;q;r;f(a,t)int*a;{p=t;for(q=r=*a;p--;s+=(A>0)-(A<0))q=q>A?q:A,r=r<A?r:A;a=q+r+(s>0)<(s<0);}

```

Uses Robin Ryder's method.

Try it online!
> 1 votes

# Answer
# ~~Perl 6~~ Raku, 31 bytes

```
{0>.min+.max+sum($_».sign)/$_}

```

Try it online!

Based on Robin Ryder's solution.
> 1 votes

# Answer
# Factor, 44 bytes

```
[ dup minmax + swap [ sgn ] map mean + 0 < ]

```

Try it online!

Port of Robin Ryder's R answer.
> 0 votes

---
Tags: code-golf, music
---


# Question
Title: Draw HyperNeutrino's benzene hegaxon icon in ASCII
In celebration of HyperNeutrino getting back his account and rep, following Mr. Xcoder.

Apologies for rotating the picture for drawability.

---

Print or output this ASCII art exactly. You may have trailing spaces and/or a trailing newline.

```
      _______________
     /               \
    /  /           \  \
   /  /             \  \
  /  /               \  \
 /  /                 \  \
/  /                   \  \
\                         /
 \                       /
  \                     /
   \                   /
    \  _____________  /
     \_______________/

```

This depicts one of the two resonance structures of the molecule benzene

Related: Concentric hexagons, asterisk-filled hexagons

**Leaderboard:**

```
var QUESTION_ID=128104,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/128104/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://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
# Charcoal, 23 bytes

```
×_⁷↙←×_⁸↖⁶→↗⁶Ｐ×_⁸↘↓↙⁵‖Ｂ

```

Try it online! Explanation: Prints the lines in the following order, then reflects everything horizontally:

```
      5_______
     /
    /  6
   /  ↙
  /  /
 ↗  /
4  /
\
 \
  \
   \
    ↖  1→_____
     3______←2

```
> 25 votes

# Answer
## JavaScript (ES6),  ~~144~~  ~~143~~ ~~140~~ ~~138~~ 134 bytes

A recursive function drawing the output character by character with a purely conditional expression.

```
f=(p=363)=>(m=p%28-14,x=m<0?-m:m,y=p/28|0,p--)?`\\/ _
`[m+14?x<8-y&y<2|x<8&y>11?3:x==y+8|x==19-y|x==16-y&y>5&x>5?m<0^y>5:2:4]+f(p):''

```

### How?

For each position **0 \< p ≤ 363**, we define:

* **m = (p MOD 28) - 14**
* **x = | m |**
* **y = ⌊ p / 28 ⌋**

Below is a breakdown of the formula which picks the appropriate character from `[ '\', '/', ' ', '_', '\n' ]`.

```
m + 14 ?                            // if this is not an end of line:
  x < 8 - y & y < 2 |               //   if this is either part D
  x < 8 & y > 11 ?                  //   or part E:
    3                               //     output '_'
  :                                 //   else:
    x == y + 8 |                    //     if this is either part A
    x == 19 - y |                   //     or part B
    x == 16 - y & y > 5 & x > 5 ?   //     or part C:
      m < 0 ^ y > 5                 //       output '/' or '\' depending on the quadrant
    :                               //     else:
      2                             //       output a space
:                                   // else:
  4                                 //   output a Line-Feed

```

And below are the different parts in the coordinate system defined above:

```
   | 13 12 11 10 09 08 07 06 05 04 03 02 01 00 01 02 03 04 05 06 07 08 09 10 11 12 13
---+---------------------------------------------------------------------------------
12 | .  .  .  .  .  .  E  E  E  E  E  E  E  E  E  E  E  E  E  E  E  .  .  .  .  .  .
11 | .  .  .  .  .  B  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  B  .  .  .  .  .
10 | .  .  .  .  B  .  .  C  .  .  .  .  .  .  .  .  .  .  .  C  .  .  B  .  .  .  .
09 | .  .  .  B  .  .  C  .  .  .  .  .  .  .  .  .  .  .  .  .  C  .  .  B  .  .  .
08 | .  .  B  .  .  C  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  C  .  .  B  .  .
07 | .  B  .  .  C  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  C  .  .  B  .
06 | B  .  .  C  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  C  .  .  B
05 | A  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  A
04 | .  A  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  A  .
03 | .  .  A  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  A  .  .
02 | .  .  .  A  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  A  .  .  .
01 | .  .  .  .  A  .  .  D  D  D  D  D  D  D  D  D  D  D  D  D  .  .  A  .  .  .  .
00 | .  .  .  .  .  A  D  D  D  D  D  D  D  D  D  D  D  D  D  D  D  A  .  .  .  .  .

```

### Demo

```
f=(p=363)=>(m=p%28-14,x=m<0?-m:m,y=p/28|0,p--)?`\\/ _
`[m+14?x<8-y&y<2|x<8&y>11?3:x==y+8|x==19-y|x==16-y&y>5&x>5?m<0^y>5:2:4]+f(p):''

o.innerHTML = f()
```

```
<pre id=o></pre>
```
> 8 votes

# Answer
# 05AB1E, 50 bytes

```
•ι¡≠ït]4uƵŽΣ”9g½ùöèri|)á,ćè’∍é•5B3ÝJ"/ _\"‡4¡.B».∞

```

Try it online!

---

***The compression:***

The strategy here was to build half the object, then mirror the image across the halfway mark. To do this, I first built the left half, with front padding:

```
11111122222222
111110
11110110
1110110
110110
10110
0110
3
13
113
1113
1111311222222
11111322222222

```

But no right padding, this is because the `.B` function in 05AB1E can be used to make every element equal in length using spaces. This allows for me to omit the extraneous spaces to the right and just delimit by newlines. I then, took this pattern, and removed all newlines replacing them with `4` to get:

```
1111112222222241111104111101104111011041101104101104011043413411341113411113112222222411111322222222

```

Compressing this with base-255 results in:

```
•ι¡≠ït]4uƵŽΣ”9g½ùöèri|)á,ćè’∍é•5B

```

Where the two  is denoting a base-255 compressed string and 5B is converting it to base-5.

---

***The second part, after the compressing:***

```
3ÝJ                # Push '0123'.
   "/ _\"          # Push '/ _\'.
         ‡         # Replace each in b with a on c.
          4¡       # Split on 4's (the newlines I replaced).
            .B     # Boxify for the mirror (adds padding to longest element).
              »    # Join by newlines.
               .∞  # Mirror image.

```
> 7 votes

# Answer
# , 61 bytes

```
i/  /±¹ \  \
\²µ /6ñGÙlxxhPHÄãxx>ñv$r_jwr w.Gkkl13r_jviwr_jd

```

Try it online!

Hexdump:

```
00000000: 692f 2020 2fb1 b920 5c20 205c 0a5c b2b5  i/  /.. \  \.\..
00000010: 202f 1b36 f147 d96c 7878 6850 48c4 e378   /.6.G.lxxhPH..x
00000020: 783e f176 2472 5f6a 7772 2077 2e47 6b6b  x>.v$r_jwr w.Gkk
00000030: 6c31 3372 5f6a 7669 7772 5f6a 64         l13r_jviwr_jd

```
> 5 votes

# Answer
# Python 2, ~~226~~ ~~213 bytes~~ 179 bytes

My first golf!

```
b,f,s,u='\/ _'
print'\n'.join([s*6+u*15,s*5+f+s*15+b]+[s*(4-n)+'/ /'+s*(13+2*n)+'\ \\'for n in range(5)]+[s*n+b+s*(25-2*n)+f for n in 0,1,2,3]+[s*4+b+s*2+u*13+s*2+f,s*5+b+u*15+f])

```

Try it online!

I tried looping the bits that I could find a pattern on, and hardcoded the rest. Setting the different characters to a variable helped save quite a lot of bytes.

Edit: Decided to append to the same array instead of joining multiple times. Saved 13 bytes.

Edit 2: Thanks to @ValueInk, @jacoblaw, @WheatWizard, @CalculatorFeline, and @Challenger5, saved 34 bytes
> 5 votes

# Answer
# Retina, ~~129~~ ~~114~~ 102 bytes

*Thanks to ovs for -12 bytes!*

```

6eea¶5/15\¶4c1b3c3b2c5b1c7bc9b\25d1\23d2\21d3\19d4\2ee_2d5\eea/
e
aa
d
/¶
c
/2/1
b
\2\¶
a
___
\d+
$*

```

Try it online!
> 4 votes

# Answer
# Charcoal, 47 43 41 bytes

```
↗⁶Ｆ¹⁵_↓↘⁶←↙⁶↷⁴↑Ｆ¹⁵_↖⁶Ｍ⁴→↗⁵Ｍ¹¹→↓↘⁵Ｍ⁵↙↑Ｆ¹³_

```

Try it online!

I did not know a thing about Charcoal until right now, I felt like "I have no idea of what I'm doing" while trying to figure out this answer... I'm quite sure this can be golfed a lot.

Updates:

* I managed to save 4 bytes learning to use cursor directions and movements!
* 2 more bytes saved after realizing the drawing was not exactly as asked. ^\__^U
> 4 votes

# Answer
# , 155 bytes

```
('_ /\',LF){~5#.inv 95x#.32-~3 u:'0_C5NcBe''e2kA/jhk>5y~l<Z:AN<QG)V7m>l"x!@A-jp8E%XEh&"$''j(sP8Z!b#e7})]_,L"LCUu)kqsBQ5_5bt}`bq ":1cv(gU;|{I~n5q@(ISCK `'[<

```

Try it online!

This is a function that expects no input. E.g., `f =: <code>` then `f ''`.

## Explanation

I encoded this using the following steps. Assume that the desired compression string is contained in the variable `h`.

```
   k=:'_ /\',LF                    *NB. the dictionary used to encode the string*
   k i. h                          *NB. numbers corresponding to indices in `k`*
1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 4 1 1 1 1 2 1 1 2 1 1 1 1 1 1 1 1 1 1 1 3 1 1 3 4 1 1 1 2 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 3 4 1 1 2 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 3 4 1 2 1 1 2 1 1 1 ...
   5x#.k i. h                      *NB. base 5 to decimal*
4571656960356964266407389291886526966074643634545109498506871241033015964671946641835339522170115810676380078148856766959449166714046433431522704650346045752930168245684048485736756807881102718244115576453623363843561553955078139
   95#.inv 5x#.k i. h              *NB. decimal to base 95*
16 63 35 21 46 67 34 69 7 69 18 75 33 15 74 72 75 30 21 89 94 76 28 58 26 33 46 28 49 39 9 54 23 77 30 76 2 88 1 32 33 13 74 80 24 37 5 56 37 72 6 2 4 7 74 8 83 48 24 58 1 66 3 69 23 93 9 61 63 12 44 2 44 35 53 85 9 75 81 83 34 49 21 63 21 66 84 93 64 66 8...
   quote u:32+95#.inv 5x#.k i. h   *NB. base 95 to ASCII repr of string*
'0_C5NcBe''e2kA/jhk>5y~ll"x!@A-jp8E%XEh&"$''j(sP8Z!b#e7})]_,L"LCUu)kqsBQ5_5bt}`bq ":1cv(gU;|{I~n5q@(ISCK `'

```

Then, we just need to decode this. `5#.inv 95x#.32-~3 u:` performs the inverse of what I just described, giving us the list of indices. Then, `('_ /\',LF){~` applies the appropriate characters to each index.
> 4 votes

# Answer
# Mathematica, 227 bytes

```
t=Table;T[x_,y_,z_,v_]:=""<>{x,y~t~v,z};Column[Join[b={""<>"_"~t~15},{T["/"," ","\\",15]},t[T["/  /"," ","\\  \\",i],{i,11,19,2}],t[T["\\"," ","/",i],{i,25,19,-2}],{T["\\  ","_","  /",13]},{""<>{"\\",b,"/"}}],Alignment->Center]

```
> 4 votes

# Answer
# Ruby, 117 bytes

```
13.times{|i|s=[?_*(15--i%12*1.3),"/%#{i*2+8}s"%?\\,''][(i%12%11+3)/5].center(27)
i>0&&(s[i-=7]=?\\)&&s[~i]=?/
puts s}

```
> 4 votes

# Answer
# 05AB1E, ~~92~~ ~~86~~ 80 bytes

```
'_15×6ú'/5úð8×«.∞5F'/4N-ú'/2ú«ð6N+×«.∞}4F'\Núð13N-×«.∞}'\4ú'_7×2ú«.∞'\5ú'_8×«.∞»

```

Try it online!

---

## Explanation in parts

The bar at the top

```
'_      # underscore
  15×   # repeated 15 times
     6ú # with 6 spaces in front

```

The line immediately below the bar

```
'/         # forward slash
  5ú       # with 5 spaces in front
    ð      # space
     8×    # repeated 8 times
       «   # concatenated with the earlier string
        .∞ # intersected mirror (i.e middle space not affected)
           # mirroring: "  /  " => "  /    \  "

```

The remainder of the upper portion of the hexagon

```
5F                     # for N in 0..4
  '/                   # forward slash
    4N-                # 4 - N
       ú               # spaces in front of the slash
        '/             # another forward slash
          2ú           # with 2 spaces in front
            «          # concatenated with the other string
             ð         # a space character
              6N+      # N + 6
                 ×     # times
                  «    # concatenated with the other string
                   .∞  # intersected mirror
                     } # end for

```

The remainder except for the last 2 lines

```
4F               # for N in 0 .. 3
  '\             # backslash
    Nú           # with N spaces in front
      ð          # a space
       13N-      # 13 - N
           ×     # repeated
            «    # concatenated with other string
             .∞  # intersected mirror
               } # end for

```

The second to last line

```
'\ # backslash
  4ú # with 4 spaces in front
    '_ # underscore
      7× # repeated 7 times
        2ú # with 2 spaces in front
          « # concatenated with earlier string
           .∞ # intersected mirror

```

The last line

```
'\ # backslash
  5ú # with 5 spaces in front
    '_ # underscore
      8× # repeated 8 times
        « # concatenated with other string
         .∞ # intersected mirror

```

The `»` at the end joins everything on newlines.
> 3 votes

# Answer
# C#, 210 199 bytes

Encodes the length of space runs and underscore runs:

```
var h=@"5KL4/>\L3/1/:\1\L2/1/<\1\L1/1/>\1\L0/1/@\1\L/1/B\1\L\H/L0\F/L1\D/L2\B/L3\1I1/L4\K/L";for(var i='M';--i>'/';)h=h.Replace(""+i,i>75?"\n":"".PadLeft(i>72?i-60:i-47," _"[i/73]));Console.Write(h);

```

Ungolfed:

```
var h = @"5KL4/>\L3/1/:\1\L2/1/<\1\L1/1/>\1\L0/1/@\1\L/1/B\1\L\H/L0\F/L1\D/L2\B/L3\1I1/L4\K/L";
for (var i = 'M'; --i > '/'; )
    h = h.Replace("" + i, i > 75 ? "\n" : "".PadLeft(i > 72 ? i - 60 : i - 47, " _"[i / 73]));
Console.Write(h);

```

Try It Online!
> 3 votes

# Answer
# Retina, 129 bytes

```

5$* ¶
\G (?=( *))
¶$1/  /$`11$* $`\  \
r`(?<=( *)) \G
$1\$'19$* $'/¶
^
6$* 15$*_¶5$* /15$* \
¶$
¶    \  13$*_  /¶5$* \15$*_/

```

Try it online! Completely different approach, yet coincidentally the same length!
> 2 votes

# Answer
# Paintbrush, 43 bytes, non-competing

```
13→'_8×←↓s/5{↙s/3→s/3←}↓'\6×↘↑'_8×→↖'_7×←▕┣

```

### Explanation

```
13→'_8×←↓s/5{↙s/3→s/3←}↓'\6×↘↑'_8×→↖'_7×←▕┣  Program
13→                                          Move the pointer 13 spaces right
   '_                                        Push '_' onto the stack
     8×                                      Multiply it 8 times
       ←                                     Draw out '________' moving to the left
        ↓                                    Move down
         s/                                  Set that cell to a slash
           5{         }                      Execute function 5 times
             ↙                               Move the pointer one spot down and one spot to the left
              s/                             Set that cell to a slash
                3→                           Move 3 spaces right
                  s/                         Set that cell to a slash
                    3←                       Move 3 spaces left
                      ↓                      Move down
                       '\                    Push r'\'
                         6×                  Multiply it 6 times
                           ↘                 Draw out r'\\\\\\' moving down-right
                            ↑                Move up
                             '_              Push '_'
                               8×            Multiply it 8 times
                                 →           Draw out '________' moving to the right
                                   ↖         Move the pointer one spot up and one spot to the right
                                    '_       Push '_'
                                      7×     Multiply it 7 times
                                        ←▕┣  Draw out '_______' moving to the left
                                         ▕   Remove the rightmost column
                                          ┣  Mirror the entire grid to the right, overlapping the inner column, flipping some characters that have backwards variants

```

Beta Testing in the Real World:

```
Charcoal: 1
Paintbrush: 0

```

Gotta make a lot of improvements, huh. :P
> 2 votes

# Answer
# PHP, 122 bytes

```
<?=gzinflate(base64_decode("ddDBDQAgCEPRO1N0AxYicf8tFK2JIPT4HycA34iTHRVxJqwvGLvme8LXrxRAKoVmBZypoMNFjbmUtMEl/OV2WHqYTg"));

```

Try it online!

# PHP, 158 bytes

```
for(;~$c='f000
e/o1d/b/k\b1c/b/m\b1b/b/o\b1a/b/q\b1/b/s\b1\y/
a\w/
b\u/
c\s/
d\b00___b/
e\000/'[$i++];)echo$c>_?str_pad("",ord($c)^96):strtr($c,[_____,"\
"]);

```

Try it online!

# PHP, 165 bytes

```
<?=strtr("5566666
57/3334
5 13552513352713332 13355 213335 2433335 0 433355 0743333054333505 476666_ 057466666/",[" /
","/  /","\  \
","     ","\\","   ",___,"  "]);

```

Try it online!
> 1 votes

# Answer
# ///, 152 bytes

```
/,/  //'/\\!!!//&/\\"\\
//%/\/"\/!!//#/_____//"/,\\//!/,, /! ###
!\/!!!\\
,"% \& "% "&"%!\& \%!"&\%!,"&\'!!\/
 \'! "/
"'! \/
 "',"/
,"\,##___"/
!\\###\/

```

Try it online!
> 1 votes

# Answer
# MATL, ~~58~~ 55 bytes

```
'/__\ '7XyP9BY+3l7:14&(6Xy_3TF_5M&(&v0'Zj'(t2&P_h)[]9Z(

```

**Try it online!**
> 1 votes

# Answer
# Pyth, 111 bytes

```
J\/K\\+*6d*15\_+++*5dJ*15dKV5+++*-5hNd"/  /"*+yN11d+++KddK)V4+++*NdK*-25yNdJ)+++++*4dK*2d*13\_*2dJ+++*5dK*15\_J

```

This code basically prints the lines one after another (in the naive way of doing it). Yeah it sucks, but right now I'm in no state of doing better, and I too still wanted to pay tribute to HyperNeutrino.

Try it online!
> 1 votes

# Answer
# Bubblegum, ~~67~~ 54 bytes

```
00000000: 55c9 310d 0040 0804 c1fe 55e0 0043 24f8  U.1..@....U..C$.
00000010: 77f1 c955 cc96 3b95 d65e 6697 4d76 0b93  w..U..;..^f.Mv..
00000020: cf06 f847 0448 d1e6 0ceb 5722 8421 1010  ...G.H....W".!..
00000030: d95b 7e60 ad3f                           .[~`.?

```

Try it online!
> 1 votes

# Answer
# SOGL V0.12, ~~53~~ 52 bytes

```
/↕Υ¦‛¾}`¼Pσ↕ΗΦ▒∙⌠N►4┼ΥjΠ⌡jOT?»m,┌∆Χ⁶↑┌≠Γ‽‼║%Ν□‘7«n╬⁷

```

Try it Here!
> 1 votes

# Answer
# Python 2, 187 bytes

```
a=`int("7YSUQZDJS0I3J2QJ40G9WNPIRBTBC1KF0F3X5WDMBW8CG5BVDHBJQ71V3UHCSY3TR8LC4IIEE5SZ",36)`[:-1]
for i in"0666666_!6__!5/!3\\!9\n!844!422!211!1 ".split("!"):a=a.replace(i[0],i[1:])
print a

```

Try it online!
> 1 votes

# Answer
# Python 2, ~~154~~ 138 bytes

```
print'eNp10MEJAEEIA8C/VaSDNBTY/rtYlByci+aZER8BMqcnqiR6FG7/IPd87w0c/pQMYBrFJmxhQDstljJSQUrb5euhZzBe6PI3aQ=='.decode('base64').decode('zip')

```

Try it online!
> 1 votes

# Answer
# C# (.NET Core), 169 bytes

```
var d=new char[364];for(int i=10;i-->0;)for(int j="ppnggffggn"[i]-97;j-->0;)d[28*"amlhbccbha"[i]+"ggh{fguva|"[i]-2813+j*("b|~}"[i/3]-97)]="_/\\\n"[i/3];Console.Write(d);

```

Ungolfed:

```
var d = new char[364];
for (int i = 10; i-- > 0; )
    for (int j = "ppnggffggn"[i] - 97; j-- > 0; )
        d[28 * "amlhbccbha"[i] + "ggh{fguva|"[i] - 2813 + j * ("b|~}"[i / 3] - 97)] = "_/\\\n"[i / 3];
Console.Write(d);

```

For each stroke I encoded the start position, length, character used, and direction within various strings. I saved a few bytes by grouping up similar strokes.

Sadly, this prints a little weird in tio. This is because I'm not printing out real spaces. Looks fine in my console, though. So probably this submission doesn't count. Here's the link anyways.

Try it online! (fake spaces 169 bytes)

Try it online! (real spaces 191 bytes)
> 1 votes

# Answer
# C (gcc), 200 bytes

```
char o[28];i,j,k,p;f(){for(k=0;k<39;puts(o))for(memset(o,k&&k<32?32:95,27),i=3;i--;k++)for(j=3;j--;o[24-i*3+j]=" _\\/"[p])o[i*3+2-j]=" _/\\"[p="U@@@B@HH@``@@BB@HH@``@@p@@L@@C@p@EL@UC@"[k]-64>>j*2&3];}

```

Try it online!
> 0 votes

# Answer
# Deadfish~, 872 bytes

```
{iii}iicccccc{iiiiii}iii{c}ccccc{{d}ii}dddddc{ii}iiccccc{i}iiiiic{d}ddddd{c}ccccc{iiiiii}c{{d}ii}ddc{ii}iicccc{i}iiiiic{d}dddddcc{i}iiiiic{d}ddddd{c}c{iiiiii}c{dddddd}cc{iiiiii}c{{d}ii}ddc{ii}iiccc{i}iiiiic{d}dddddcc{i}iiiiic{d}ddddd{c}ccc{iiiiii}c{dddddd}cc{iiiiii}c{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddcc{i}iiiiic{d}ddddd{c}ccccc{iiiiii}c{dddddd}cc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddcc{i}iiiiic{d}ddddd{c}ccccccc{iiiiii}c{dddddd}cc{iiiiii}c{{d}ii}ddc{iiii}dddc{d}dddddcc{i}iiiiic{d}ddddd{c}ccccccccc{iiiiii}c{dddddd}cc{iiiiii}c{{d}ii}ddc{{i}dd}iic{dddddd}{c}{c}ccccc{i}iiiiic{dddd}iiic{ii}iic{iiiiii}c{dddddd}{c}{c}ccc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}{c}{c}c{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddddd}{c}ccccccccc{i}iiiiic{dddd}iiic{ii}iicccc{iiiiii}c{dddddd}cc{iiiiii}iii{c}ccc{dddddd}dddcc{i}iiiiic{dddd}iiic{ii}iiccccc{iiiiii}ciii{c}ccccc{ddddd}iic

```

Try it online!
> 0 votes

# Answer
# Vyxal, 45 bytes

```
»R√UǏ8x⟑9↓ḋSŀ«+Ġ↵‡⊍6-}h≥kẇ⊍ḣW£»`/ _\,`τ⌐øŀ⁋øM

```

Try it Online!
> 0 votes

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