title: Ellipsoid surface area

text:
# Question
Title: Ellipsoid surface area
Related: Ellipse circumference

## Introduction

An **ellipsoid** (Wikipedia / MathWorld) is a 3D object analogous to an ellipse on 2D. Its shape is defined by three principal semi-axes \\$a,b,c\\$:

$$ \frac{x^2}{a^2} + \frac{y^2}{b^2} + \frac{z^2}{c^2} = 1 $$

Just like an ellipse, the volume of an ellipsoid is easy, but its surface area does not have an elementary formula. Even Ramanujan won't save you here.

The basic formula is given as the following:

$$ S = 2\pi c^2 + \frac{2\pi ab}{\sin\varphi} \left( E(\varphi,k) \sin^2\varphi + F(\varphi,k) \cos^2\varphi \right) \\ \text{where }\cos\varphi = \frac{c}{a},\quad k^2 = \frac{a^2(b^2-c^2)}{b^2(a^2-c^2)},\quad a \ge b \ge c $$

\\$F\\$ and \\$E\\$ are incomplete elliptic integral of the first kind and second kind respectively. Note that the formula does not work for a sphere.

A good approximation can be found on this archived page, where Knud Thomsen developed a symmetrical formula of

$$ S \approx 4\pi \left(\frac{a^p b^p + b^p c^p + c^p a^p} {3 - k\left(1-27abc/\left(a+b+c\right)^3\right)}\right)^{\frac{1}{p}} $$

with empirical values of \\$p=\frac{\ln 2}{\ln (\pi/2)}\\$ and \\$k=3/32\\$.

## Challenge

Given the three principal semi-axes \\$a,b,c\\$ of an ellipsoid, compute its surface area.

All three input values are guaranteed to be positive, and you can use any reasonable representation of a real number for input. Also, you may assume the three values are given in a certain order (increasing or decreasing).

The result must be within 0.1% (=10-3) relative error for the given test cases. You can go for the exact formula (if your language has the necessary built-ins) or Thomsen's approximation, or you can go for numerical integration (extra brownie points if you succeed in this way).

## Test cases

The true answer was calculated by feeding the corresponding ellipsoid equation into WolframAlpha.

```
a  b  c  => answer
------------------
1  1  1  => 12.5664
1  1  2  => 21.4784
1  2  2  => 34.6875
1  1  10 => 99.151
1  2  3  => 48.8821
1  10 10 => 647.22
1  3  10 => 212.00

```

# Answer
> 7 votes
# JavaScript (ES7),  ~~86 83~~  82 bytes

*Saved 3 bytes thanks to @xnor*
*Saved 1 byte thanks to @VarunVejalla*

An approximation of Thomsen's approximation.

```
(a,b,c)=>(519*((a*b)**(p=1.535)+c**p*(b**p+a**p))/(31+27*a*b*c/(a+b+c)**3))**(1/p)

```

Try it online!

# Answer
> 6 votes
# Wolfram Language (Mathematica), 27 bytes

Shamelessly copying from the 2D solution by @J42161217:

```
SurfaceArea[#~Ellipsoid~#]&

```

Try it online!

# Answer
> 3 votes
# Ruby 2.7, 86 83 bytes

*Saved three bytes, thanks to Dingus!*

```
->a{(519*a.zip(a.rotate).sum{(_1*_2)**1.535}/(31+27*eval(a*?*)/a.sum**3))**0.65147}

```

Try it online!

Expects an array of \\$a,b,c\\$. TIO uses an older version of Ruby, whereas in Ruby 2.7, we've numbered parameters, which saves three bytes.

# Answer
> 2 votes
# PowerShell, 325 bytes

Takes input as a descending list of semi-axis lengths; +5 bytes if this is not allowed, or +0 bytes if this is not allowed but we need only handle ascending-sorted lists as in the test cases. Spheroid handling takes up 26 bytes of this solution. This solution uses the formula for the surface area of an ellipsoid in the question, which does not hold for spheroids (a=b=c) and requires that a\>=b\>=c.

The integral calculated by this program is *very* rough to avoid taking too long to output; can easily improve the accuracy of results by reducing $d, and especially by calculating the area of the trapezoid between $x and $x+$d, rather than the rectangle of width $d at $x

```
$a,$b,$c=$args;$u,$p,$z={param($t,$g)for($d=1e-4;$x-lt$t){$i+=(&$g ($x+=$d))*$d}$i},($m=[Math])::PI,$c*$c;if($a-eq$c){4*$p*$z}else{$e=$c/$a;$h=$m::Acos($e);$s=$m::Sin($h);$j={$m::Sqrt(1-($a*$a*($b*$b-$z))/($b*$b*($a*$a-$z))*($v=$m::Sin($args[0]))*$v)};2*$p*$z+2*$p*$a*$b/$s*((&$u $h $j)*$s*$s+(&$u $h {1/(&$j @args)})*$e*$e)}

```

Try it online!

Ungolfed and Explanation

```
#Set a, b, and c to the elements in the input array
$a,$b,$c=$args;
#Declare a function for finding integrals of a provided function, for 0 to $to
$integralFunction={
    #take parameters $to (the value to calculate the integral to, from 0)
    #and $function (the function to calculate the integral of)
    param($to,$function)
    #set $dx to .0001 and loop until $x >= $to
    for($dx=1e-4;$x-lt$to){
        #increase x by dx
        $x+=$dx
        #calculate the area of the right-side rectangular sliver for this step (f(x)dx)
        $integral+=(&$function $x)*$dx
    }
    #return the integral of the function
    $integral
}
#pi!
$pi=[Math]::PI
#if this is a spheroid (due to the assumption a>=b>=c, a=c follows that a=b=c)
if($a-eq$c){
    #return the surface area of the sphere
    4*$pi*$c*$c
#if this is an ellipsoid
}else{
    #cosine of Phi equals the shortest side over the longest side
    $cosPhi=$c/$a;
    #we need Phi for the integral, so calculate the arccos of cosPhi
    $Phi=[Math]::Acos($cosPhi);
    #we need the sin of Phi for the final calculation
    $sinPhi=[Math]::Sin($Phi);
    #set k^2 to this value, because the formula says so
    #we don't need k, as the elliptical integrals use k^2
    $kSquared= ($a*$a*($b*$b-$c*$c))/($b*$b*($a*$a-$c*$c))
    #since both incomplete elliptical integrals have the term
    #sqrt(1-k^2*sin^2(theta)), we assign this calculation it's own function
    $ellipticalIntegralFunctionBase={
        param($theta)
        [Math]::Sqrt(1-$kSquared*($sinTheta=[Math]::Sin($theta))*$sinTheta)
    };
    #the first elliptical integral (F) is the integral from 0 to Phi of
    #(1/sqrt(1-k^2*sin^2(theta))) with respect to theta
    $FirstEllipticalIntegral = (&$integralFunction -to $Phi -function {param($theta) 1/(&$ellipticalIntegralFunctionBase -theta $theta)})
    #the second elliptical integral (E) is the integral from 0 to Phi of
    #sqrt(1-k^2*sin^2(theta) with respect to theta
    $SecondEllipticalIntegral = (&$integralFunction -to $Phi -function $ellipticalIntegralFunctionBase)
    #we have all of our intermediate calculations done, so now we plug those numbers into
    #(2*pi*c^2)+((2*pi*a*b)/sin(Phi))*(E*sin^2(Phi)+F*cos^2(Phi))
    #we return the result of this calculation implicitly
    (2*$pi*$c*$c)+((2*$pi*$a*$b)/$sinPhi)*($SecondEllipticalIntegral*$sinPhi*$sinPhi+$FirstEllipticalIntegral*$cosPhi*$cosPhi)
}

```

# Answer
> 2 votes
# BQN, 50 bytes

```
{(519×(+´(⊢×1⊸⌽)⋆p)÷31+(27××´)÷3⋆˜+´)⋆÷p←1.535}

```

Try it!

An anonymous function which uses Arnauld's formula.

Input given as a single array.

# Answer
> 1 votes
# Python/mpmath, 70 bytes

```
lambda a,b,c:4*pi*a*b*c*elliprg(1/a/a,1/b/b,1/c/c)
from mpmath import*

```

Attempt This Online!

DLMF 19.33.1 relates one of Carlson's symmetric elliptic integrals to the ellipsoid surface area as $$S=4\pi abcR\_G(a^{-2},b^{-2},c^{-2})$$ This is one of the examples Carlson (who wrote section 19 of the DLMF) uses to propound the superiority of his elliptic integrals over Legendre's \\$F/E/\Pi\\$ set. Indeed, internally mpmath uses the symmetric integrals to calculate Legendre's integrals.

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


title: Generalized FizzBuzz

text:
# Question
Title: Generalized FizzBuzz
#### Task

FizzBuzz, but instead of 3 and 5, you'll take the numbers and corresponding strings as input.

You can assume all inputted numbers are coprime (and \\$\ge 2\\$). You'll receive one or more numbers, and a string to print with each of them. The normal FizzBuzz would be something like `[[3, "Fizz"], [5, "Buzz"]]`, but you could also receive something like `[[2, "Quux"]]` or `[[2, "a"], [5, "b"], [7, "c"], [33, "d"], [529, "e"]]`.

For output, you'll have two options:

* Print this modified FizzBuzz infinitely
* Take a number as input, and return the first \\$n\\$ lines

You *must* return output with newline separators. An array of lines is not acceptable.

#### Details

To clarify exactly what this should look like, this is the process to determine what the \\$n\\$th line should look like (first line is always \\$1\\$):

1. For each of the inputted numbers \\$n\\$ is divisble by, append the corresponding string to the output (for example, \\$15\\$ would result in `"Fizz" + "Buzz" = "FizzBuzz"` for normal FizzBuzz)
2. If \\$n\\$ is not divisble by any of the numbers (i.e., the line is still empty), default to \\$n\\$

For example, the first 100 lines of the sample input `[[4, "Foo"], [7, "Bar"], [9, "Baz"]]` are:

```
1
2
3
Foo
5
6
Bar
Foo
Baz
10
11
Foo
13
Bar
15
Foo
17
Baz
19
Foo
Bar
22
23
Foo
25
26
Baz
FooBar
29
30
31
Foo
33
34
Bar
FooBaz
37
38
39
Foo
41
Bar
43
Foo
Baz
46
47
Foo
Bar
50
51
Foo
53
Baz
55
FooBar
57
58
59
Foo
61
62
BarBaz
Foo
65
66
67
Foo
69
Bar
71
FooBaz
73
74
75
Foo
Bar
78
79
Foo
Baz
82
83
FooBar
85
86
87
Foo
89
Baz
Bar
Foo
93
94
95
Foo
97
Bar
Baz
Foo

```

#### I/O

You can take input in any reasonable format. This includes dicts of numbers and their strings, a single list of pairs (like in the examples), two lists (one with numbers and ones with pairs), or similar.

For instances where there's two strings being appended, such as `FooBar` in the example above, any order is acceptable (`BarFoo` is also fine).

#### Other

This is , so shortest answer in bytes (per language) wins!

# Answer
> 10 votes
# Jelly, 8 bytes

```
⁴ḍTị⁵ȯ)Y

```

Try it online!

Full program that takes \\$n\\$, the list of numbers \\$L\\$ and the list of strings \\$S\\$ as command line argument, and returns a newline separated string

## How it works

```
⁴ḍTị⁵ȯ)Y - Main link. Takes n on the left, L as ⁴ and S as ⁵
      )  - Over each integer 1 ≤ i ≤ n:
⁴ḍ       -   Map each element in L to 1 if i is divisible by it, else 0
  T      -   Indices of 1s
   ị⁵    -   Select the elements of S at those indices
     ȯ   -   If this is the empty list, replace it with i
       Y - Join on newlines

```

# Answer
> 6 votes
# K (ngn/k), 29 bytes

```
{{$[a:&~x!'y;,/a;y]}[x]'1+!y}

```

Try it online!

Takes a dict with (string, number) pairs.

## Explanation

```
{{$[a:&~x!'y;,/a;y]}[x]'1+!y}
                        1+!y  range 1..y
                       '      for each number
                    [x]       with x as constant first argument:
 {$[              ]}           if:
        x!'y                    the values of x mod y
       ~                        logical NOTed
      &                         filter out keys which have truthy values
    a:                          store in a
            ;,/a                return a if non-empty
                ;y              otherwise return number y

```

# Answer
> 6 votes
# Haskell, 69 bytes

```
[]%n=show n
x%_=x>>=id
f a=unlines[[y|(x,y)<-a,mod i x<1]%i|i<-[1..]]

```

Try it online!

`f [(3, "Fizz"), (5, "Buzz"), (10, "Boom")]` is an infinite string with newlines in it.

# Answer
> 5 votes
# JavaScript (V8), 59 bytes

Prints the sequence forever.

```
a=>{for(k=0;++k;)print(a.map(([m,s])=>k%m?'':s).join``||k)}

```

Try it online!

# Answer
> 4 votes
# Vyxal, 8 bytes

```
ƛ¹Ḋ⁰*∑∴,

```

Try it Online!

Since y'all complaining about flags, I'll give you a tie with jelly.

Expects `L`imit, `D`ivisors, `S`trings

## Explained

```
ƛ¹Ḋ⁰*∑∴,
ƛ        # for each n in the range [1, L]:
 ¹Ḋ      #     Push n % D == 0 (epicly vectorised)
   ⁰*    #     Push ^ * S (which is vectorised python string multiplication)
     ∑∴  #     Push max(sum(^), n)
       , #     and print ^ with a newline

```

This would be 7 with the `j` flag

# Answer
> 4 votes
# Python 2, 63 bytes

```
def f(k,i=1):
 print''.join(y*(i%x<1)for x,y in k)or i;f(k,i+1)
```

Attempt This Online!

-1 bytes thanks to @dingledooper

-3 bytes thanks to @pxeger

# Answer
> 4 votes
# Japt `-R`, 14 bytes

```
õ@VËÌpXvDÎÃ¬ªX

```

Try it

```
õ@VËÌpXvDÎÃ¬ªX     :Implicit input of integer U & array V
õ                  :Range [1,U]
 @                 :Map each X
  VË               :  Map each D in V
    Ì              :    Last element
     p             :    Repeat
      Xv           :      Is X divisible by
        DÎ         :      First element of D
          Ã        :  End map
           ¬       :  Join
            ªX     :  Logical OR with X
                   :Implicit output joined with newlines

```

# Answer
> 4 votes
# Perl 5, 56 bytes

```
sub{say join('',map$.%$$_[0]?'':$$_[1],@_)||$.while++$.}

```

Try it online!

# Answer
> 4 votes
# Charcoal, 19 bytes

```
Ｅθ∨⭆η⎇﹪⊕ι§λ⁰ω§λ¹Ｉ⊕ι

```

Try it online! Link is to verbose version of code. Prints the first `n` terms. Explanation:

```
 θ                  Input `n`
Ｅ                   Map over implicit range
    η               Input list of pairs
   ⭆                Map over pairs and join
        ι           Outer index
       ⊕            Incremented
      ﹪             Modulo
         §λ⁰        First element of pair
     ⎇              If non-zero then
            ω       Empty string
             §λ¹    Else second element of pair
  ∨                 Logical Or
                  ι Current index
                 ⊕  Incremented
                Ｉ   Cast to string
                    Implicitly print on separate lines

```

Note: Using trunk Charcoal (not available on TIO) this would be only 15 bytes:

```
Ｅθ∨⭆η⎇﹪⊕ιμωλＩ⊕ι

```

Explanation: Takes the input as a dict, which means that iterating over it populates the loop variables directly without having to index into the pairs.

# Answer
> 4 votes
# , ~~76~~ 64 bytes

*-12 bytes thanks to @Dominic*

```
function(N,S)repeat{F=F+1;cat(F[all(k<-F%%N)],S[!k],"
",sep="")}

```

Try it online!

Takes vectors of `N`umbers and corresponding `S`trings.

Outputs infinitely.

# Answer
> 4 votes
# Java (JDK), 109 bytes

```
l->{for(int i=1;;i++){var s="";for(var e:l)if(i%e.getKey()<1)s+=e.getValue();System.out.println(s==""?i:s);}}

```

Try it online!

## Notes

The `s==""` works here because of the constants pool: the two references to the empty string are actually one reference and have the same address in memory. `s==new String("")` wouldn't have worked for instance.

## Credits

# Answer
> 3 votes
# Python 3, 65 bytes

```
f=lambda a,n=1:print(''.join(j*(n%i<1)for i,j in a)or n)+f(a,n+1)

```

Try it online!

-1 byte thanks to MarcMush

# Answer
> 3 votes
# Julia 0.7, 59 bytes

```
N\d=1:N.|>n->println((a=prod(p->p[2]^(n%p[1]<1),d))>""?a:n)

```

Try it online!

# Answer
> 3 votes
# , 48 bytes

```
1 :'(|:@([:(,0=+/)0=u|/]);@#"1(,"#:<@":"+))1+i.'

```

Try it online!

This was bizarrely difficult to golf in J.

# Answer
> 3 votes
# Bash, ~~100~~ ~~80~~ 75 bytes

*-20 bytes thanks to @Dude coinheringaahing*

*-5 bytes and extra readability thanks to @Jonah*

```
for((i=1;;i++));{
o=
for a;{((0==i%${a% *}))&&o=$o${a#* };}
echo ${o:-$i}
}

```

Try it online!

Takes arguments as strings in the form '$num $str' and uses variable expansion to split them out into their component parts. Outputs infinitely.

I'm pretty sure this one has lots of potential for further golfing, but I'll take an even 100 for my first submission.

# Answer
> 3 votes
# Scala, 94 bytes

```
b=>1 to _ map(x=>println(Seq(b.collect{case(k,s)if x%k<1=>s},Seq(x))maxBy(_.size)mkString ""))

```

Try it online!

Outputs the first n lines of the sequence.

```
b => //A Map with the keys being divisors (4, 7, 9) and the values being strings ("Foo", "Fizz", etc.)
1 to _ //Make a range to n
 map(x=> //For each x in the range, output either "x" or a string made from its divisors
  println( //Print with newline
   Seq(   //Make a Seq with the two alternatives ^
    b.collect{ //The Fizz, Buzz, FizzBuzz alternative
     case(k,s) //For every divisor k and its accompanying string s,
      if x%k<1 //If k divides x
      =>s},    //Add s to this alternative
    Seq(x)  //The second alternative is just the number itself
   ) maxBy(_.size) //Find the alternative with more elements (if both have 1, the first is chosen)
    mkString ""  //Join into a single string
  )
 )

```

# Answer
> 3 votes
# 05AB1E, 12 bytes

```
∞ε¹ÖÏJy‚õKн,

```

Integers and strings as two separated input-lists.
Outputs the infinite sequence.

Try it online.

**Explanation:**

```
∞            # Push an infinite positive list: [1,2,3,...]
 ε           # Foreach `y` over these integers:
  ¹Ö         #  Check for each integer in the first input-list whether it divides the
             #  current integer
    Ï        #  Get the strings of the second (implicit) input-list at the truthy indices
     J       #  Join this list of strings (it's now "" if none were divisible)
      y‚     #  Pair it with the current integer `y`
        õK   #  Remove empty strings from this pair
          н  #  Pop and leave the first item
           , #  And print it with trailing newline

```

# Answer
> 2 votes
# CSASM v2.5.1, 317 bytes

```
func a:
.local a : i32
push 1
add
pop $3
pop $2
dup
len
pop $4
pop $1
lda 1
.lbl a
push 0
pop a
push -1
pop $5
push $a
push 1
sub
brfalse c
.lbl b
inc $5
push $5
push $4
sub
brfalse c
push $a
push $1
ldelem $5
rem
brtrue b
push 1
pop a
push $2
ldelem $5
print
br b
.lbl c
push a
brtrue d
push $a
print
.lbl d
push '\n'
print
inc $a
push $a
push $3
sub
brtrue a
ret
end

```

A function named `a` which expects an `~arr:i32` for the values, an `~arr:str` for the names and an `i32` representing \\$n\\$ on the stack, pushed in that order specifically.

**Explanation:**

```
func a:
    ; Used as the flag for if a string was printed
    .local a : i32

    ; stack: [ values array, strings array, amount to print ]
    push 1
    add
    pop $3
    pop $2
    ; Duplicate "values array", get its length and store it into $4
    dup
    len
    pop $4
    pop $1

    ; $1 = values, $2 = strings, $3 = final number

    ; Initialize $a to 1
    lda 1

    .lbl a
        ; Reset the "string printed" flag
        push 0
        pop a

        ; Reset the "numbers array" iteration
        push -1
        pop $5

        ; If $a == 1, skip to the end
        push $a
        push 1
        sub
        brfalse c

        .lbl b
            inc $5
            push $5
            push $4
            sub
            brfalse c

            ; Loop through each value in the numbers array and check if a$ % them is zero
            ; If they are, print that string
            push $a
            push $1
            ldelem $5
            rem
            brtrue b

            ; Modulo was zero
            push 1
            pop a

            push $2
            ldelem $5
            print
            br b
    .lbl c
        push a
        brtrue d
        ; Print the current number
        push $a
        print
    .lbl d
        ; Print the newline
        push '\n'
        print

        ; Loop while $a != $3
        inc $a
        push $a
        push $3
        sub
        brtrue a
    ret
end

```

---

**Sample Program:**

```
func main:
    push $i32:[3,5]

    push 2
    newarr str
    pop $a

    push $a
    push "Fizz"
    stelem 0
    push $a
    push "Buzz"
    stelem 1

    push $a
    push 30

    call a

    ret
end

; "func a" would be defined here

```

# Answer
> 2 votes
# Python 3, 122 bytes

```
exec("g="+input())
n=1
while 1:
 b=1
 for k,v in g:
  if n%k<1:
   print(v,end='')
   b=0
 print(n)if b else print()
 n+=1

```

Input:

```
((4, "Foo"), (7, "Bar"), (9, "Baz"))

```

Try it online!

Fairly obvious way of going about the challenge. Using a tuple of tuples saves 1 byte over a dict. Looking at the other python submissions, I realize I missed a lot of optimizations. Lessons to bring to the next code golf, I hope.

# Answer
> 2 votes
# CJam, ~~36~~ 35 bytes

```
q~{)1${\_@~;%!},_@aa?{1=}%:+oNo}%];

```

Try it online!

**Explanation**

```
q~                                       read the factor array and upper bound in one go
  {)                            }%       for each i from 1 to n
    1${       },                          get all the input factors i contains
       \_@~;%!                              by checking i mod f = 0 for each input factor f
                _@aa?                     if there *are* factors in i,
                                            keep the relevant factors [[f, "Foo"], ...]
                                            otherwise keep the number in the form [[i]]
                     {1=}%                keep the 2nd element in each subarray
                                            this is the texts ["Foo","Bar","Baz",...]
                                            or just [i] if there were no input factors
                          :+              sum them all (concatenating texts together)
                            oNo           print in the required format
                                 ];       clean up

```

**(-1 byte)** *dropping `,`: CJam automatically turns a number `n` into `[0, n)` when you map using `%`*

---

**Possible Changes**

**(-2 bytes)** *using `p` instead of `oNo` but this prints `"Foo"`/`"BarBaz"` instead of `Foo`/`BarBaz`*
**(-2 bytes)** *using `n` instead of `oNo` but this feature isn't in any releases (and most likely will never be)*

---
Tags: code-golf, fizzbuzz
---


# Question
Title: Convert a Forsyth-Edwards Notation string to ASCII art
In chess, Forsyth-Edwards Notation, more commonly called "FEN", is a textual way of transcribing boards. It describes each of the board's eight rows (called "ranks" in chess) from top to bottom from White's perspective. The pieces are written as K (king), Q (queen), R (rook), B (bishop), N (knight), and P (pawn). Black pieces use these letters in lowercase, and white pieces use these letters in uppercase. Empty spaces are indicated by a number from 1 to 8 indicating how many consecutive empty spaces there are. A completely empty rank would be `8`, a single black rook in the rightmost column (called "files" in chess) would be `7r`, and two white pawns on each end of a row would be `PP4PP`. Ranks are separated by a `/`. There is normally other information added, indicating which side is to move, castling and *en passant* rights, move number, and halfmove clock, but we will ignore them for the purposes of this challenge.

# Input

A FEN string, from the command line or STDIN, as you please. You may assume that this string is always valid.

# Output

Write to STDOUT a simple ASCII art representation of the board as it would actually appear:

* Pieces are represented by their character in FEN
* Empty squares are represented by spaces
* Pieces and squares are separated by a pipe `|` and there are pipes on each side of the board

So an empty board, written as `8/8/8/8/8/8/8/8` in FEN, would appear as

```
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |

```

The starting position of a chess game is written as `rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR`, and would appear as

```
|r|n|b|q|k|b|n|r|
|p|p|p|p|p|p|p|p|
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
|P|P|P|P|P|P|P|P|
|R|N|B|Q|K|B|N|R|

```

The final position of Anderssen-Kieseritzky 1851, called "The Immortal Game" in the chess community, is written as `r1bk3r/p2pBpNp/n4n2/1p1NP2P/6P1/3P4/P1P1K3/q5b1`, and your program when fed that input would output:

```
|r| |b|k| | | |r|
|p| | |p|B|p|N|p|
|n| | | | |n| | |
| |p| |N|P| | |P|
| | | | | | |P| |
| | | |P| | | | |
|P| |P| |K| | | |
|q| | | | | |b| |

```

# Answer
> 11 votes
# Perl, 28 bytes

Includes +2 for `-lp`

Give input on STDIN

```
fen.pl <<< "r1bk3r/p2pBpNp/n4n2/1p1NP2P/6P1/3P4/P1P1K3/q5b1"

```

`fen.pl`:

```
#!/usr/bin/perl -lp
s/\d/$"x$&/eg;s/|/|/g;y;/;

```

Actually in the league of some golfing languages...

Notice that the file based version needs the final newline in the file so that one is really 29 bytes. But the commandline version doesn't need that extra newline and therefore the code counts as 28 bytes:

```
perl -lpe 's/\d/$"x$&/eg;s/|/|/g;y;/;' <<< "r1bk3r/p2pBpNp/n4n2/1p1NP2P/6P1/3P4/P1P1K3/q5b1"

```

# Answer
> 16 votes
# Retina, 13 bytes

```
\d
$*
/
¶

|

```

Try it online!

## Explanation

The first part (note the trailing space):

```
\d
$*

```

is to convert a to the specific number of spaces. Retina has a `$*` feature to repeat. The way it works is: `<num>$*<char>` if there is no `<num>`, Retina will assume `$&` or the matched string, in this case the matched number.

The next part:

```
/
¶

```

is pretty simple, it replaces all `/` with  which is a newline.

The last part works the same:

```

|
```

This will replace everything (hence why there is nothing on the first line) with `|`. Putting a `|` everywhere.

# Answer
> 12 votes
## Ruby - ~~75~~ ~~82~~ ~~78~~ ~~76~~ ~~75~~ ~~62~~ ~~59~~ ~~58~~ ~~57~~ 56 bytes

```
->n{"|#{n.gsub(/\d|
/){' '*$&.hex}.chars*?|}|".tr'/',$/}

```

*Saved a few bytes thanks to Ventero*

Let me explain (with `\n` replacing the literal newline):

```
->n{"...".tr'/',$/}

```

This implicitly returns the value of the string, with each `/` replaced with a newline (by default, `$/` contains a newline)

```
"|#{...}|"

```

This is super simple; it's just a string containing a pipe, string interpolation, and another pipe. The string interpolation is evaluated

```
n.gsub(/\d|\n/){' '*$&.hex}...

```

This replaces every number with that many spaces. I can save a few bytes by also finding newlines here; because `hex` returns 0 if the string isn't a valid number, when it finds a newline –- i.e. the one at the end of the result of `gets` –- it replaces it with a 0-length string, effectively deleting it. Without this, there would be a trailing pipe.

`$&` is a magic variable which represents the complete text of the latest variable match, which lets me save a byte by eliminating `|d|`. I can save another byte by using `.hex` instead of `.to_i`, which works because every number is less than 9, which means that hex and decimal have the same values.

```
.chars*?|

```

This puts a pipe between every character. Note that this is what puts the pipes on either side of the lines (except the first and last) because the slashes, which eventually turn into newlines through `tr`, count as characters, and are therefore surrounded by pipes. The `?|` just means "the one-character string `"|"`".

And... that's it. It's a frankly scandalously simple program. It just uses a lot of sneaky syntax tricks.

# Answer
> 5 votes
# Pyth - ~~24~~ ~~22~~ 21 bytes

```
.i*\|72jcu:G`H*Hd9z\/

```

Test Suite.

```
+                     Concatenate
 K\|                  Store "|" in K and use value
+         K           Concatenate to end
 jK                   Join string by K, this puts "|" between each char
  :                   String substitution
        \/            Replace "/"
         b            With newline
   u                  Reduce
        9             Over [0, 9)
         z            With input as base case
    :G                String substitution current val
     `H               Replace stringifyed int from list we're looping through
     *Hd              With " "*that int

```

# Answer
> 4 votes
# JavaScript ES7, ~~80~~ 70 bytes

Is an anonymous function that accepts a string as input.

```
a=>[,...[+t?" ".repeat(t):t<"0"?`
`:t for(t of a)].join``,`
`].join`|`

```

80-byte ES6-only appraoch.

```
a=>a.split`/`.map(x=>[,...x.replace(/\d/g,t=>" ".repeat(t)),`
`].join`|`).join``

```

## Explanation

We use an array comprehension to loop over the list:

```
[+t?" ".repeat(t):t<"0"?`
`:t for(t of a)]

```

This is equivalent to:

```
[!isNaN(parseInt(t, 10)) ? " ".repeat(parseInt(t, 10)) : t === "/" ? "\n" : t for(t of a)]

```

If it's a number, we have that number of spaces. If it's a `/`, we have a newline. Otherwise, we have the character. Then, we join the comprehension with nothing to make a string.

Then, we create an array of length 3 `[,...that,"\n"]`. `...` splats the joined comprehension into chars. Joining this yields the result.

# Answer
> 4 votes
# Pyth, 23 bytes

```
VT=:Q`N*dN;jc.i*\|72Q\/

```

Try it online!

How it works:

```
VT=:Q`N*dN;jc.i*\|72Q\/
VT        ;                for N in range(10):
  =:Q`N*dN                     Q = Q.replace(`N`,repeat(' ',N))
             .i*\|72Q      temp = interweave(repeat('|',72), Q)
            c        \/    temp = chop(temp,'/')
           j               temp = join(temp,'\n')
                           print temp

```

# Answer
> 3 votes
# Julia, 62 bytes

```
s->split("|"join(replace(s,r"\d",d->" "^parse(d)),"|")"|","/")

```

This is an anonymous function that accepts a string and returns an array of strings. To call it, assign it to a variable.

The approach is the same as in QPaysTaxes' clever Ruby answer. We replace each digit in the input with that many spaces, place `|` between each character, tack `|` onto the front and back, and split into an array on `/`.

Try it online!

# Answer
> 2 votes
# Retina, ~~50~~ 45 bytes

This was fun haha. Not only am I a noob in Retina, but also in regex in general... This can probably be golfed a *lot*, so I'll do some more research.

Code:

```
8
44
7
34
6
42
5
 4
4
22
3
 2
2

1

/
¶

|

```

Try it online!

# Answer
> 2 votes
# 05AB1E, 21 bytes

Code:

```
9GNNð×:}S'|ý"|ÿ|"'/¶:

```

Also 21 bytes: `'|¹9GNNð×:}S'|«JJ'/¶:`.

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

# Answer
> 2 votes
# Python 3.5, 112 bytes:

```
def r(o):print(''.join(['| '*8if h=='8'else'| '*int(h)if h.isdigit()else'|\n'if h=='/'else'|'+h for h in o])+'|')

```

Try it online! (Ideone)

# Answer
> 2 votes
## JavaScript (ES6), ~~69~~ ~~67~~ 62 bytes

```
s=>[,...s.replace(/[/-8]/g,c=>+c?' '.repeat(c):`
`),,].join`|`

```

The extra commas create empty values in the outer split which creates the beginning and ending `|` characters. You need two trailing commas because trailing commas are optional at the end of lists, so the first one is still part of the previous item.

Edit: Saved 5 bytes thanks to @user81655.

# Answer
> 2 votes
## R (out of competition)

Sorry if it's not appropriate to post this, but I thought it was cool that I just happened to have a function lying around that actually works for this question without editing! It prints unicode output rather than ascii, though. I can't remember quite why I wrote it, but it wasn't to answer a challenge.

```
function(x){
# x = FEN position, a string
# can be split with / or ,
# example: forsythe("rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R")

allowed <- c(paste(1:64),
c("k", "q", "r", "b", "n", "p", "K", "Q", "R", "B", "N", "P"))
chars <- strsplit(x, "")[[1]]
chars <- chars[-which(!(chars %in% allowed))]
out <- c()
for (i in 1:length(chars)){
  if (chars[i] %in% paste(1:64)){
    out <- c(out, rep(" ", as.numeric(chars[i])))
  }
  else{
    out <- c(out, chars[i])
  }
}
if (length(out) < 64) out <- c(out, rep(" ", 64-length(out)))

pieces <- strsplit("KQRBNPkqrbnp", "")[[1]]
unicode <- c("\u2654", "\u2655", "\u2656",
"\u2657", "\u2658", "\u2659", "\u265A", "\u265B",
"\u265C", "\u265D", "\u265E", "\u265F")

for (i in 1:64){
  if (out[i] %in% pieces){
    out[i] <- unicode[which(pieces==out[i])]
  }
  else{
  }
}
out <- matrix(out, nc=8, byrow=T)
#print(out)

plot(0, xlim=c(0, 8), ylim=c(0, 8), type="n", xaxt="n", yaxt="n",
xlab="", ylab="")
for (i in 0:7){ for (j in 0:7){ rect(i, j, i+1, j+1,
col=ifelse(((i+j) %% 2) == 0, grey(0.95), "white"), border=F) }}

for (i in 0:7){ for (j in 0:7){
  text(i+0.5, j+0.5, out[8-j, i+1], cex=2)
}}

axis(1, labels=letters[1:8], at=1:8 - 0.5, tick=F)
axis(2, labels=paste(1:8), at=1:8-0.5, las=2, tick=F)

}

```

# Answer
> 1 votes
# Jolf, 28 bytes

```
RΜGi'/dΆγ'|RGρH«\d»d*♣PHEγγS

```

Replace  with the character `\x05`, or try it here!

# Answer
> 1 votes
# C, 252 bytes

```
i=-1,j,s=1,x;C(char*n){while(n[++i])s+=isdigit(n[i])?n[i]*2+1:2;char*m=(char*)malloc(s);for(i=j=-1;n[++i]&(m[++j]='|');)if(n[i]=='/')m[++j]='\n';else if(isdigit(n[i]))for(x=n[i]-'0';x;--x&&(m[++j]='|'))m[++j]=' ';else m[++j]=n[i];m[++j]='\0';return m;}

```

**Detailed** *try online*

```
// input-string, input-string-size
char* C(char*n)
{
    int i=-1,j,s=1,x;

    // figure out required grid size
    while(n[++i])s+=isdigit(n[i])?n[i]*2+1:2;
    char*m=(char*)malloc(s);

    i=j=-1;
    while(n[++i]) // while not end of string
    {
        m[++j]='|'; // seperator

        if (n[i]=='/') // end of row
            m[++j]='\n';
        else if (isdigit(n[i])) // fill spaces
            for(x=n[i]-'0';x;--x&&(m[++j]='|')) m[++j]=' ';
        else
            m[++j]=n[i]; // single literals
    }

    m[++j]='|';
    m[++j]='\0';
    return m;
}

```

# Answer
> 1 votes
# Haskell, 110 Bytes

```
p '/'="\n"
p c|'1'<=c&&c<='8'=replicate(read[c])' '
p c=[c]
main=getLine>>=putStrLn.('|':).(>>=(:"|")).(>>=p)

```

## Ungolfed:

```
p c | c=='/'           = "\n"
    | '1'<=c && c<='8' = replicate (read [c]) ' '
    | otherwise        = [c]
addPipes string = "|" ++ concatMap (\c -> [c] ++ "|") string
main = getLine >>= putStrLn . addPipes . concatMap p

```

# Answer
> 1 votes
# JavaScript (FireFox 30+), 61

Using array comprehension that is not standard EcmaScript anymore

```
f=>'|'+[for(c of f)+c?' |'.repeat(c):c<'A'?`
|`:c+'|'].join``

```

**Test**

```
F=f=>'|'+[for(c of f)+c?' |'.repeat(c):c<'A'?`\n|`:c+'|'].join``

console.log=x=>O.textContent+=x+'\n'

;['8/8/8/8/8/8/8/8','rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR',
'r1bk3r/p2pBpNp/n4n2/1p1NP2P/6P1/3P4/P1P1K3/q5b1']
.forEach(t=>console.log(F(t)+'\n'))
```

```
<pre id=O></pre>
```

# Answer
> 1 votes
## Python, 84 bytes

```
lambda a:"".join(c*c.isalpha()or"\n"*(c=="/")or" "*int(c)for c in a).replace("","|")

```

Explanation:

```
        c*c.isalpha()                                                       - if c is alphabetical, use c
                       "\n"*(c=="/")                                        - if it's "|", replace it with a newline
                                      " "*int(c)                            - else its an int.
"".join(                                                  ).replace("","|") - interweave "|" between the chars

```

# Answer
> 1 votes
## Lua, 106 Bytes

```
print("|"..(...):gsub(".",function(c)return c:find("%d")and(" |"):rep(c)or c=="/"and"\n|"or c.."|"end),'')

```

### Ungolfed

```
print("|"..                   -- prepend | to the following string
  (...):gsub(".",function(c)  -- iterate over each character in the argument
    return                    -- replaces in the argument
           c:find("%d")       -- if c is a number
             and(" |"):rep(c) --   replace by " |"*c
           or c=="/"          -- elseif c is a slash
             and"\n|"         -- replace by "\n|"
           or c.."|"          -- else (case letter)replace by c
  end)                        -- return the modified string
,'')                          -- add an empty parameter to print
                              -- it suppresses the second output of gsub

```

# Answer
> 1 votes
# \>\<\>, 64 bytes

```
<v?(0:i
r\
"<o-*=@"%/":   v?*(@)@":/"::;?(0:o"|
 ^~?="0":-1o" "<

```

4 wasted bytes due to alignment issues, not sure how to golf them out though. ¯\\\_(ツ)\_/¯

# Answer
> 0 votes
# Java 7, ~~190~~ 184 bytes

```
String Z(int c){String m="";if(c==47)m+="|\n";else if(c>57)m+="|"+c;else while(c-->48)m+="| ";return m;}String C(String n){String m="";for(char x:n.toCharArray())m+=Z(x);return m+"|";}

```

**Detailed** *try online*

```
public static String Z(char c)
{
    String m="";
    if(c=='/')m+="|\n";
    else if(c>'9')m+="|"+c;
    else while(c-->'0')m+="| ";
    return m;
}

public static String C(String n)
{
    String m="";
    for(char x:n.toCharArray())m+=Z(x);
    return m+"|";
}

```

# Answer
> 0 votes
## Pyke, ~~25~~ 20 bytes

```
FD~u{RIbd*(s\/n:k\|:

```

Explanation:

```
F         (          -    for char in input:
 D~u{RI              -     if char in '0123456789':
       bd*           -      char = " "*int(char)
           s         -   sum(^)
            \/n:     -  ^.replace("/","\n")
                k\|: - ^.replace("", "|")

```

Try it here!

# Answer
> 0 votes
# brev, 89 bytes

```
(fn(print(strse x'num(->(m 0)string->number(make-string #\ ))"."(c conc "|")"/""\n")"|"))

```

# Answer
> 0 votes
# Japt v2.0a0 `-R`, 15 bytes

```
r\dÈ°çÃrP'| q'/

```

Try it

```
r\dÈ°çÃrP'| q'/     :Implicit input of string U
r                   :Replace
 \d                 :  Regex /[0-9]/g
   È                :  Pass each match through a function
    °               :    Postfix increment (to convert from string to integer)
     ç              :    Repeat a space that many time
      Ã             :End replace
       r            :Replace
        P           :  Empty string
         '|         :  With "|"
            q'/     :Split on "/"
                    :Implicit output, joined with newlines

```

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


title: Mr. Binary Counterman

text:
# Question
Title: Mr. Binary Counterman
Mr. Binary Counterman, son of Mr. Boolean Masker & Mrs. Even Oddify, follows in his parents’ footsteps and has a peculiar way of keeping track of the digits.

When given a list of booleans, he counts the 1s and 0s separately, numbering the 1s with the odds & the 0s with the evens.

For example, when he looks at `1 1 0 0 1 0` he counts: `1st odd, 2nd odd, 1st even, 2nd even, 3rd odd, 3rd even` and copies it down as `1 3 2 4 5 6`

Mr. Binary Counterman thinks it looks prettier to start counting odds at 1 and evens at 2. However the pattern is more symmetric if you start counting evens at 0. You may do either. So either `1 3 2 4 5 6` or `1 3 0 2 5 4` are good given the list above.

As input you may take any representation of a boolean list or binary number, the output should be the list of resulting numbers with any delimiter. (But the list elements should be separate & identifiable.)

This is , so least bytes wins.

## Test Cases

```
1 0 1 0 1 0
1 2 3 4 5 6

1 1 1 1
1 3 5 7

0 0 0 0
2 4 6 8

0 1 1 0 0
2 1 3 4 6

0 1 1 0 0 1 0 1 1
2 1 3 4 6 5 8 7 9

0 0 1 0 0 1 1 1
2 4 1 6 8 3 5 7

0
2

1
1

1 1 1 0 0 0
1 3 5 2 4 6

```

# Answer
# JavaScript (ES6), 29 bytes

```
a=>a.map(v=>b[v]+=2,b=[0,-1])

```

Try it online!
> 15 votes

# Answer
# , 12 bytes

```
+2*/:<.&/:\:

```

Try it online!

Explanation: Self plus twice the minimum of ascending and descending ranks.

Given a boolean array `1 1 0 0 1 1 1`, ascending rank `/:@/:` and descending rank `/:@\:` are computed as follows:

```
array:       1 1 0 0 1 1 1
asc. rank:   2 3 0 1 4 5 6
desc. rank:  0 1 5 6 2 3 4
minimum:     0 1 0 1 2 3 4

```

# APL(Dyalog Unicode), 9 bytes SBCS

```
⊢+2×⍋⌊⍥⍋⍒

```

Try it on APLgolf!
> 12 votes

# Answer
# Risky, 44 bytes

```
__0+0+_0+0+__0+0+_0+0+__0+0+_0+0+__0+0+_0+?1__0+0+_0+0+__0+0+_0!-_0!_{1+_0+0_[2_{0+__{1

```

Try it online!

**How it works:**

This is a really low level explanation:

```
... + __0+0+_0+?                                                  ;  the input array
                 1                                                ;  map with the following pairs:
                   ... + __0+0+_0!-                               ;  [0, -1]
                                    _                             ;  map to
                                      0!_{1+_0+0                  ;  range with same length
                                                 _                ;  map to
                                                   [              ;  absolute value
                                                          +       ;    of the sum of
                                                     2_{0         ;      twice the index in the range and
                                                            __{1  ;      the offset (0 or -1)

```

That's useless, though. Here's a better description of how this works:

Risky has an operator called "map pairs" which takes an array, and maps the items according to a set of rules. The rules are arrays, starting with the item to be replaced, and with (typically) one item to map to. However, if multiple are specified, they'll be used in order.

This answer generates those mappings, which look like `[[0, 2, 4, 6, ...], [1, 1, 3, 5, 7, ...]]`. It does this by mapping `[0, -1]` to `[2_{0+__{1` over a range `[0, x)`, which is essentially `(x, n) => abs(2 * x + n)`, where `x` is the number in the range and `n` is either `0` or `-1`.
> 11 votes

# Answer
# Jelly, 8 bytes

```
,CÄḤ×ƊS_

```

Try it online!

-2 bytes thanks to Bubbler

## How it works

```
,CÄḤ×ƊS_ - Main link. Takes a binary list B on the left
 C       - Complement. Flip the bits of B
,        - Pair with B: [B, B']
     Ɗ   - Last 3 links as a monad f([B, B']):
  Ä      -   Cumulative sum of each
   Ḥ     -   Unhalve
    ×    -   Multiply modified B by B and modified B' by B'
      S  - Columnwise sum
       _ - Subtract B, elementwise

```
> 9 votes

# Answer
# Japt `-m`, 8 bytes

```
?J±2:T±2

```

Try it

* `J` is initially `-1`,
* `T` is initially `0`, and,
* `±` is the shortcut for `+=`.
> 7 votes

# Answer
# Jelly, 9 bytes

```
,CỤ€⁺«/Ḥ_

```

Try it online!

My convoluted port of my own APL/J answer.

# Jelly, 9 bytes

```
CỤỤ«ỤỤ$Ḥ_

```

Try it online!

Small modification of caird's 10-byter port.
> 5 votes

# Answer
# 8086 machine code, ~~21~~ 18 bytes

```
00000000: b0 01 b2 02 d1 eb 72 01 92 aa 40 40 72 01 92 e2  ......r...@@r...
00000010: f3 c3                                            ..

```

Function.

```
        [bits 16]
        [cpu 8086]
        section .text
        ; nasm syntax
        ; INPUT:
        ;    DI: destination byte array
        ;    BX: bit pattern (little endian)
        ;    CX: count of bits
        ; OUTPUT:
        ;    stored to DI
        global  mrbitctr
mrbitctr:
        ; Count odd bits in AL
        mov     al, 1
        ; Count evens in DL
        mov     dl, 2
.loop:
        ; Shift right BX one bit. This will put
        ; the lowest bit in CF.
        shr     bx, 1
        ; Was the bit set? If so, jump.
        jc      .no_swap
        ; Even: swap
.swap:
        ; Pull the old switcheroo to select evens
        xchg    ax, dx
        ; Odd: don't swap
.no_swap:
        ; Store to DI and increment
        stosb
        ; Add 2 to AL by incrementing AX twice
        ; Note: INC does not affect the carry flag
        inc     ax
        inc     ax
        ; swap back if even
        jc      .no_swap_back
.swap_back:
        xchg    ax, dx
.no_swap_back:
        ; Loop CX times.
        loop    .loop
.end:
        ret

```
* 3 bytes: swap twice
> 5 votes

# Answer
# PowerShell Core, 28 bytes

```
$b=0,-1;$args|%{($b[$_]+=2)}

```

Try it online!

Port of Arnauld's solution, thanks !

### Initial implementation, 35 bytes

```
switch($args){0{++$e*2}1{$o++*2+1}}

```

Try it online!
Or starting with 0 (35 bytes)

Takes the input as a list of `0/1`'s
Returns a list of integers

## Explanation

```
switch($args){ # For each argument passed as an integer
0{++$e*2}      # if it is 0, output an even number, starting from 2
1{$o++*2+1}}   # if it is 1, output an odd number, starting from 1

```
> 5 votes

# Answer
# 05AB1E, ~~8~~ 6 bytes

```
η^_O·α

```

Try it online!

```
η       # prefixes of the input
 ^      # XOR the first value of the input with the first prefix, second value of input with second prefix, ...
  _     # boolean negate
   O    # sum each modified prefix
    ·   # double all integers
     α  # absolute difference to the input

```

`η^_` can be replaced with `δQÅl` (equality table; lower-triangular matrix), which is a byte longer but might be shorter in some other language.

```
δQÅlO·α

```

Try it online!
> 5 votes

# Answer
# Jelly, ~~7~~ 6 bytes

```
ċṪ$ƤḤ+

```

Try it online!

Basically a translation of an old version of ovs' 05AB1E answer.

## Explanation

```
ċṪ$ƤḤ+ Main monadic link
   Ƥ   Map over prefixes
  $    (
ċ        Count the occurences of
 Ṫ         the last item after removing it
  $    )
    Ḥ  Unhalve
     + Add the original list

```
> 5 votes

# Answer
# Dyalog APL, ~~24~~ 23 bytes

```
(⍵×¯1+2×+\⍵)+N×2×+\N←~⍵

```

The list of evens and the list of odds are generated separately and added elementwise with the `+` in the middle. Here's what it looks like with the problem's example input:

```
Evens:
    ⍵            The input                      → 1 1 0 0 1 0
    ~            Negate it                      → 0 0 1 1 0 1
    N←           Let N be the negated list      → 0 0 1 1 0 1
    +\           Take the running sum           → 0 0 1 2 2 3
    2×           Multiply by two                → 0 0 2 4 4 6
    N×           Multiply by the negated list   → 0 0 2 4 0 6

Odds:
    ⍵            The input                      → 1 1 0 0 1 0
    +\           Take the running sum           → 1 2 2 2 3 3
    2×           Multiply by two                → 2 4 4 4 6 6
    ¯1+          Subtract 1                     → 1 3 3 3 5 5
    ⍵×           Multiply by the list           → 1 3 0 0 5 0

Together:
  (~⍵)×2×+\~⍵    Evens                          → 0 0 2 4 0 6
  (⍵×¯1+2×+\⍵)   Odds                           → 1 3 0 0 5 0
  +              Add elementwise                → 1 3 2 4 5 6

```

Try it online!
> 4 votes

# Answer
# , 27 26 25 bytes

```
<@({.-~2*#\)/.~@/:~/:&;/:

```

Try it online!

* `/.~@/:~` Sort and group by value
* `({.-~2*#\)` Create `2 4 6 ...` to the length of each group, and subtract the first element of each group from that (vectorized), so that the the 1 group becomes `1 3 5 ...`
* The grouping screws up the order though, so we have to...
* `/:&;/:` Resort it according to the grade up of the original input, which makes it correct again.

## , bonus: translation of AviFS's APL answer into J (28 bytes)

```
([:+/**-&1 0)@,:&(2*]*+/\)-.

```

Try it online!

Just because I liked it and wanted to see how they'd compare.
> 4 votes

# Answer
# Vyxal, ~~15~~ 9 bytes

```
₌⇧⇩⇧$⇧∵d+

```

Try it Online!

Me when APL port

## Explained

```
₌⇧⇩⇧$⇧∵d+
₌⇧⇩       # grade up input, grade down input
   ⇧$⇧    # grade each of those up
      ∵d  # 2 * the minimum of those two lists
        + # added to the input

```
> 4 votes

# Answer
# Python 2, 43 bytes

```
b=[2,1]
for e in input():print b[e];b[e]+=2

```

Try it online!

-5 bytes and fix thanks to @xnor

The program is now reusable
> 4 votes

# Answer
# Ruby `-p`, 29 bytes

Takes input as space separated digits (or any other non-digit separator).

```
gsub(/\d/){($`*2+?1).count$&}

```

Try it online!
> 4 votes

# Answer
# Haskell, 38 bytes

```
f(h:t)=h:f[x+mod(x-h-1)2*2|x<-t]
f e=e

```

Try it online!

The recursion happens on “the `t`ail of the list, but with all elements `x` that have the same parity as the `h`ead incremented by 2.” Like so:

```
  f [1,1,0,0,1,0]
= 1 : f [3,0,0,3,0]
= 1 : 3 : f [0,0,5,0]
= 1 : 3 : 0 : f [2,5,2]
= 1 : 3 : 0 : 2 : f [5,4]
= 1 : 3 : 0 : 2 : 5 : f [4]
= 1 : 3 : 0 : 2 : 5 : 4 : f []
= [1,3,0,2,5,4]

```
> 4 votes

# Answer
# Jelly, 15 bytes

```
ṢŒg2ḷ$\€ÄFị@ỤỤ$

```

Try it online!

```
ṢŒg2ḷ$\€ÄFị@ỤỤ$  Main Link; take a list of 0s and 1s
Ṣ                Sort the list
 Œg              Group runs of equal elements
       €         For each group
     $\          Cumulatively reduce by
   2ḷ            x => 2 (that is, all but the first element become 2)
        Ä        Cumulative sum, vectorizing to depth 1
         F       Flatten
          ị@     Index into (reverse order)
            ỤỤ$  The input graded up twice

```

Grading up twice returns the permutation to index into another list to get the same ordering or something like that. I think that's how it works.
> 3 votes

# Answer
# K (ngn/k), 15 bytes

```
{x+2*(<<x)&<>x}

```

Try it online!

A K port of @Bubbler's J and APL solutions \- don't forget to upvote it!
> 3 votes

# Answer
# Stax, ~~9~~ 8 bytes

```
╜♪N·{☼►◄

```

Run and debug it

Inspired by Arnauld's idea.

0-indexed, takes the bits flipped.

## Explanation

```
AEsF{Q2+}&
AEs        swap the input with  [1,0]
   F       foreach i:
    {   }&  modify the element at i in 2,1
     Q      print without popping
      2+    add 2

```
> 2 votes

# Answer
# C (clang), 52 bytes

-1 thanks to @AZTECCO, by using clang instead of gcc.

```
f(a,l)int*a;{for(int b[]={0,-1};l--;)*a++=b[*a]+=2;}

```

Try it online!

---

# C (gcc), 53 bytes

```
f(a,l)int*a;{for(int b[]={0,-1};l--;a++)*a=b[*a]+=2;}

```

Try it online!
> 2 votes

# Answer
# Wolfram Language (Mathematica), 29 bytes

```
(a=0@-1;a[[#~Mod~2]]+=2&/@#)&

```

Try it online!

Boring answer. Mathematica's `+=` etc. operators have different precedence than assignment `=` etc. operators. This gives them higher precedence than `&`, so unlike `=` expressions they don't need to be parenthesized on the left side of `&`. (`//=`, introduced in 12.2, is slightly different from both aforementioned groups).
> 2 votes

# Answer
# Raku, 21 bytes

```
*>>.&{(%.{$_}+=2)-$_}

```

Try it online!

Maps each element to the index into an anonymous hash, incrementing that value by two (initially zero), and finally subtracting the element itself to distinguish between odd and even.This could also be extended to values beyond 0 and 1 simply by changing the `2` to another number.
> 2 votes

# Answer
# Julia, ~~33~~ 30 bytes

```
f(x,y=[0,-1])=x.|>i->y[i+1]+=2

```

Try it online!
> 2 votes

# Answer
# AWK, 42 bytes

```
d[1]=1{for(;a++<NF;d[b]+=2)$a=+d[b=$a%2]}1

```

Try it online!

So this one is one test with a codeblock, and a naked `1` to print all the commandline arguments. It replaces each commandline argument with the appropriate even/odd counter in the codeblock.

The "test" for the codeblock is always truthy and it just used to initialize the "odd" counter to `1`.

```
d[1]=1{                                  }

```

The code block runs through each commandline argument,

```
       for(;a++<NF;       )

```

Then sets that argument to the current value of the even/odd counter with:

```
                           $a=+d[b=$a%2]

```

And at the end of the loop, increments the current counter by 2 in preparation for the next match.

```
                   d[b]+=2

```

Once that's done, it just need to print out all the arguments.

```
                                         1

```
> 1 votes

# Answer
# Zsh, 23 bytes

```
for x
echo $[x+a$x++*2]

```

Attempt This Online!

Starts even numbers at 0.

Explanation:

* `for x`: for each `$x` in the input,
* `$[]`: arithmetic expansion
* `++`: increment and return original value
* `a$x`: the variable named `a0` or `a1` (which correspond to the number of 0s and 1s seen so far)
* `x+*2`: double and add `x` to get the correct value
* `echo` : print (can't use `<<<` because the mutation wouldn't work in the subshell it creates)
> 1 votes

# Answer
# Desmos, 64 bytes

```
a(l)=\sum_{n=1}^{[1...length(l)]}l[n]
b=1-l
f(l)=2ba(b)+2la(l)-l

```

Just implements the strategy shown in AviFS's Dyalog APL answer.

Try It On Desmos!

Try It On Desmos! - Prettified

## Explanation:

`a(l)=\sum_{n=1}^{[1...length(l)]}l[n]`: Function that takes in a list \\$l\\$ and returns the running total of \\$l\\$.

`b=1-l`: Variable that stores the inputted list, but with each bit flipped.

`f(l)=2ba(b)+2la(l)-l`: Function that takes in a list of bits \\$l\\$ and outputs the correct answer, based on the strategy mentioned above.
> 1 votes

# Answer
# , 42 bytes

```
function(x,y=seq(x)*2){x[x]=y-1;x[!x]=y;x}

```

Try it online!

*-8 bytes thanks to @Dominic*

Takes input as booleans: `TRUE`(`1`) and `FALSE`(`0`).

Straightforward approach, but takes advantage of truncating the replacement to the length of items being replaced.

---

Different approach:

### , 47 bytes

```
function(x,n=0:-1)for(i in x)show(n[i]<-n[i]+2)

```

Try it online!

Takes input incremented by 1: `2` (for `1`) and `1` (for `0`).
> 1 votes

# Answer
# Retina 0.8.2, 43 bytes

```
(.)(?<=((\1)|.)*(1)?)
$#3$*2$4¶
2
11
1+
$.&

```

Try it online! Link includes test cases. Takes input as a string of bits. 1-indexed. Explanation:

```
(.)(?<=((\1)|.)*(1)?)

```

For each bit, count the number of preceding identical bits. If the current bit is `1` then count it separately otherwise include the current bit in the count.

```
$#3$*2$4¶

```

Record a `2` for each duplicate plus one extra for a `1` bit.

```
2
11

```

Convert to unary.

```
1+
$.&

```

Convert the sum back to decimal.
> 1 votes

# Answer
# Charcoal, 12 bytes

```
ＩＥθ⁺Ｉι⊗№…θκι

```

Try it online! Link is to verbose version of code. Takes input as a string of bits. 0-indexed. Explanation:

```
  θ             Input string
 Ｅ              Map over characters
     ι          Current character
    Ｉ           Cast to integer
   ⁺            Plus
      ⊗         Doubled
       №        Count of
           ι    Current character in
         θ      Input string
        …       Truncated to length
          κ     Current index
Ｉ               Cast to string
                Implicitly print on separate lines

```
> 1 votes

# Answer
# Perl 5 (`-ap`), 27 bytes

```
$_+=$x[$_]++*2for@F;$_="@F"

```

Try it online!
> 1 votes

# Answer
# Pip `-p`, 11 bytes

```
{a?vi+:2}Ma

```

Takes input as a single string of 1's and 0's on the command-line. Try it online!

### Explanation

```
             i is preinitialized to 0, v to -1 (implicit)
{       }Ma  Map the following function to the characters of the input:
     +:2       Add 2 to...
 a?vi          ... v, if the character is 1 (truthy), or i, if it is 0 (falsey)
               ... and return the resulting value
             Autoprint in list format (implicit, -p flag)

```

In other words, for each character in the input:

* If it is 0, increment `i` by 2 and return it (giving values 2, 4, 6, ...)
* If it is 1, increment `v` by 2 and return it (giving values 1, 3, 5, ...)
> 1 votes

# Answer
# Python 3, ~~57~~ 55 bytes

```
v = [2,1]
for i in map(int,input()):print(v[i]);v[i]+=2

```

Try it online!

2 bytes less thanks to AviFS
> 1 votes

# Answer
# Java (OpenJDK 8), 74 bytes

```
a->{for(int c=0,i=-1,j=0;c<a.length;)a[c]=a[c++]==1?i+=2:(j+=2);return a;}

```

Try it online!
> 1 votes

# Answer
# Nibbles, 10 bytes

```
/$^0_:$.@+*-~%-$@~~

```

Attempt This Online!

Disgusting.

General idea: Process the list right to left. Prepend each bit to the result, then increase all numbers in the result that have the same parity by 2.

```
/  Right fold
$    the input
    with initial value
^0   repeat 0 times
_     the input
:   join
$    the bit
.    map
@     the accumulator
+     add
*      multiply
-       subtract
~        1
%        modulo
-         subtract
$          the number in the accumulator
@          the bit being prepended
~         2
~       2
       the number in the accumulator

```
> 1 votes

# Answer
# Arturo, 37 bytes

```
$=>[p:[2,1]map&'x[n:p\[x]p\[x]:n+2n]]

```

Try it
> 1 votes

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


# Question
Title: Find the largest sum of any contiguous subarray of the array
Let's say you are given an integer array. Create a function to determine the largest sum of any array's adjacent subarrays. For instance, the contiguous subarray with the largest sum is `[4, -1, 2, 1]` in the array `[-2, 1, -3, 4, -1, 2, 1, -5, 4]`.

You can employ a variant of Kadane's algorithm to resolve this issue. The steps are as follows:

1. Set `max_so_far` and `max_ending_here`, two variables, to the first array element.
2. From the second element all the way to the end, traverse the array.
3. Update the `max_ending_here` variable for each element by either adding the current element to it or setting it to the current element if it is larger than the sum of the previous elements.
4. If the `max_ending_here` variable is larger than the `max_so_far` variable, update it.
5. The `max_so_far` variable holds the largest sum of any contiguous subarray after traversing the entire array.

The steps are optional to perform if you may like. The best one which wins is the shortest in length!

# Leaderboard

```
var QUESTION_ID=257808,OVERRIDE_USER=116868;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"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} /* font fix */ body {font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;} /* #language-list x-pos fix */ #answer-list {margin-right: 200px;}
```

```
<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
> 5 votes
# Vyxal `G`, 3 bytes

```
ÞSṠ

```

This is my first Vyxal answer but I'm already outgolfing TheThonnu lol

Try it Online!

```
ÞSṠ
ÞS  : Sublists
  Ṡ : Vectorized sum (sum each)
    : -G: Max

```

# Answer
> 4 votes
# Python, 69 bytes

```
lambda x:max(sum(x[a:b])for a in range(len(x))for b in range(len(x)))

```

Attempt This Online!

# Python, 74 bytes

Outputs the list

```
lambda x:max((x[a:b]for a in range(len(x))for b in range(len(x))),key=sum)

```

Attempt This Online!

# Answer
> 3 votes
# APL (Dyalog Unicode), 9 bytes

Anonymous tacit prefix function.

```
⌈/∘∊⍋+/¨⊂

```

Try it online!

on the entire input:

`+/¨` sum sub-sequences of each of the following lengths:

the grade (permutation that would sort, but the order doesn't matter; we just need all the indices as lengths)

`∘∊`**e**nlist (flatten), and then:

`⌈/` find the maximum (lit. maximum reduction)

---

For reference, Kadane's algorithm can be found on APLcart, but is much longer:

```
{s←0 ⋄ ⌈/{s⊢←0⌈s+⍵}¨⍵}

```

This sets the maximum sum with `s←0` then, for each element `{``}¨⍵` we update the sum `s⊢←` with the maximum of zero and `0⌈` the sum plus that element `s+⍵`. Finally, we find the maximum `⌈/`.

# Answer
> 3 votes
# Husk, 3 bytes

```
►ΣQ

```

Try it online!

```
►       # maximum by
 Σ      # sum
        # of
  Q     # all contiguous subarrays

```

# Answer
> 2 votes
# Vyxal `G`, 9 bytes

```
Lʀ:Ẋƛ?$i∑

```

Try it Online!

#### Explanation

```
Lʀ:Ẋƛ?$i∑  # Implicit input
Lʀ         # Length range
  :Ẋ       # Cartesian product with itself
    ƛ      # Map:
     ?$i   #  Slice input
        ∑  #  Sum
           # G flag gets maximum

```

# Answer
> 2 votes
# Brachylog, 5 bytes

```
sᶠ+ᵐ⌉

```

Try it online!

Please note that the negative symbol for negative numbers is the underscore `_` in Brachylog, not the standard dash `-`.

### Explanation

```
sᶠ        Find all sublists of consecutive elements
  +ᵐ      Map sum
    ⌉     Get the max

```

# Answer
> 2 votes
# Japt `-h`, 4 bytes

Because the required ouput is not clear from the spec, the first solution below outputs the sub-array, while the second outputs its sum.

```
ã ñx

```

Try it

```
ãx Í

```

Try it

```
ã ñx     :Implicit input of array
ã        :Sub-arrays
  ñ      :Sort by
   x     :  Sum
         :Implicit output of last element

```

```
ãx Í     :Implicit input of array
ã        :Sub-arrays
 x       :Reduced by addition
   Í     :Sort
         :Implicit output of last element

```

# Answer
> 2 votes
# Excel, ~~70~~ 74 bytes

```
=LET(b,SEQUENCE(ROWS(A1#)),MAX(SUBTOTAL(9,OFFSET(A1#,b-1,,TRANSPOSE(b)))))

```

where `A1#` is a *vertical* spill range comprising the values from the array.

# Answer
> 1 votes
# JavaScript, 42 bytes

```
a=>a.map(s=m=n=>m=m>(s=0<s?n+s:n)?m:s)|m

```

Try it:

```
f=a=>a.map(s=m=n=>m=m>(s=0<s?n+s:n)?m:s)|m

;[
  [-2, 1, -3, 4, -1, 2, 1, -5, 4], // 6
  [1], // 1
  [1, 2, 3, 4, 5, 6, 7], // 28
  [-1, -2, -3, -4, -5, -6, -7], // -1
  [-3, -2, -1, 0, 1, 2, 3], // 6
].map(a=>console.log(f(a)))
```

## UPD 45 -\> 42

Thanks to Arnauld for the tip to reduce bytes count

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

```
f=lambda a,x=0,y=0:max(x-y,len(a)and f(a[1:],x:=x+a[0],min(x,y)))

```

Try it online!

# Answer
> 1 votes
# Wolfram Language (Mathematica), 24 bytes

```
Max[Tr/@Subsequences@#]&

```

Try it online!

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

Like several other answers, this assumes that the empty array is a valid subarray.

```
a=>Math.max(...a.map(v=>s=v>-s&&s+v,s=0))

```

Try it online!

# Answer
> 1 votes
# Python, 41 bytes

```
lambda a,x=0:max(x:=max(c+x,0)for c in a)

```

Attempt This Online!

Version that can handle empty input:

# Python, 43 bytes

```
lambda a,x=0:max(x:=c+x*(x>0)for c in[0]+a)

```

Attempt This Online!

# Answer
> 1 votes
# 05AB1E, 3 bytes

```
ŒOZ

```

Try it online!

TIL that there's a "sublists" command in both 05AB1E and Vyxal!

```
Œ   # Sublists
 O  # Sum each
  Z # Maximum

```

# Answer
> 1 votes
# , ~~46~~ 45 bytes

*Edit: -1 byte thanks to pajonk*

```
\(s){b=0;for(x in s)b=max(F<-max(x,F+x),b);b}

```

Attempt This Online!

Outputs the sum of the subarray with the largest sum (as requested in the second sentence of the question)

---

# , 59 bytes

```
\(s,`+`=sum,b={}){for(x in s)if(+(F=c(F[+F>0],x))>+b)b=F;b}

```

Attempt This Online!

Outputs the subarray with the largest sum (as in the example in the third sentence of the question).

# Answer
> 0 votes
# Pyth, 6 bytes

```
eSsM.:

```

Try it online!

### Explanation

```
eSsM.:Q    # implicitly add Q
           # implicitly assign Q = eval(input())
    .:Q    # list all subarrays of Q
  sM       # map to their sums
eS         # sort and take the last value (the largest sum)

```

# Answer
> 0 votes
# \>\<\> (Fish), 48 bytes

```
00i:?v/::0$0)?$~-{20.
+i}-1/\&~$?(@:$@:&:
 ;n~~/

```

Try it

I thought Kadane's algorithm would always be longer but for \>\<\>, which lacks normal array manipulation, it's actually shorter.

Takes input as a length-prefixed array.

# Answer
> 0 votes
# Charcoal, 14 bytes

```
Ｉ⌈Ｅθ⌈Ｅθ↨¹✂θκ⊕μ

```

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

```
   θ            Input array
  Ｅ             Map over elements
      θ         Input array
     Ｅ          Map over elements
         ✂θκ⊕μ  Inclusive slice of elements
       ↨¹       Take the sum
    ⌈           Take the maximum
 ⌈              Take the maximum
Ｉ               Cast to string
                Implicitly print

```

(Using "base 1" to take the sum as that returns `0` for empty lists.)

---
Tags: code-golf, array, subsequence
---


# Question
Title: Create a triangle whose colors are determined by the bitsums of coordinates
Write a program that, for any \\$n\\$, generates a triangle made of hexagons as shown, \\$2^n\\$ to a side. The colors are to be determined as follows.

We may give the triangle barycentric coordinates so that every hexagon is described by a triple \\$(x,y,z)\\$ with \\$x+y+z=2^n-1\\$. (The three corners will be \\$(2^n-1,0,0)\\$, \\$(0,2^n-1,0)\\$, and \\$(0,0,2^n-1)\\$.)

Let \\$s\_2(n)\\$ refer to the number of 1s in the binary expansion of \\$n\\$. (This is sometimes called the *bitsum* or the *popcount* function.) If $$s\_2(x)+s\_2(y)+s\_3(z)\equiv n\pmod 2$$ then color the hexagon \\$(x,y,z)\\$ in a light color; otherwise, color it in a dark color. (These must be *colors*, not simply black and white.)

In your answer, I would appreciate seeing several example outputs, ideally including \\$n=10\\$.

This is my first post here, so I apologize if I misunderstand the rules somehow.

This is a code golf challenge, so shortest code (in bytes) wins.

# Answer
# Wolfram Language (Mathematica), 119 bytes

-1 byte thanks to @att.

```
Graphics@Table[{Hue[Tr[ThueMorse@{x,y,s-x-y}+#+1]/2],RegularPolygon[{2x+y,√3y},{1,Pi/2},6]},{x,0,s=2^#-1},{y,0,s-x}]&

```
> 7 votes

# Answer
## JavaScript (ES~~7~~6), ~~191~~ ~~187~~ ~~180~~ ~~174~~ ~~172~~ ~~168~~ 152 bytes

```
f=
n=>eval('s="<center style=line-height:.7>";for(i=-1;++i<1<<n;s+="<br>")for(j=i+1;j--;)s+=`<font color=#f${(g=n=>n?9-g(n&n-1):9)(i^j^i-j)}0>⬢</font>`')
```

```
<input type=number min=0 max=10 onchange=o.innerHTML=f(+this.value)><div id=o style=font-size:5px>
```

Output format is HTML. Snippet limited to `n=10` because it triggers my browser's slow script warning if you go any higher. (But the output is too big for my screen anyway.) Edit: Saved ~~4~~* 11 bytes by simplifying the parity calculation. Saved ~~6~~ ~~8~~ 23 bytes thanks to @Ausername. Saved ~~4~~* 5 bytes thanks to @EzioMercer.

\*crossed out 4 is still regular 4
> 6 votes

# Answer
# C++ using SFML : ~~722~~ ~~703~~ ~~683~~ ~~527~~ ~~411~~ 399 bytes

-19 bytes thanks to NoLongerBreathedIn, using \__builtin\_popcount removes needing a bitsum function. Might work only for GCC.

-20 bytes, I used the using keyword for namespaces and components, and stopped using `.f` for magic numbers

-156 bytes thanks to pan

-116 bytes again thanks to pan

-12 bytes thanks to ceilingcat and pan

pan's proposed version approximates the value of cos(210) to around -.86, which will produce a slightly different graphic output, but very close to what's required by the challenge. This makes the cmath include useless. He also put the whole code into one function, and used a number of golfy techniques to reduce more the byte count, which makes the result very nice. His second optimization renders the use of vector useless, making an include and object usage useless

pan's code :

```
#include<SFML/Graphics.hpp>
#define B+__builtin_popcount(
void v(int n){sf::CircleShape h(4,6);for(sf::RenderWindow w({1200,1000},"");w.isOpen();w.display()){for(sf::Event e;w.pollEvent(e);)e.type?h.setOrigin(-600,-650):w.close();w.clear();for(int x=0,y,z=1<<n;x<z;)for(y=x++-z;y++;)h.setPosition(4.3*(2*y+z-x),2.5*(2+z-3*x)),h.setFillColor(sf::Color(B-x)B-y)B z+y-x)-n&1?65535:-65281)),w.draw(h);}}

```

SFML is a library that helps with the development of graphical / audio / network applications.

Previous 683 bytes answer (with the "exact" value or cos(210°)) :

```
#include <cmath>
#include <vector>
#include <SFML/Graphics.hpp>
#define B(c) __builtin_popcount(c)
using namespace sf;struct t{double x,y;bool b;};using V=std::vector<t>;V d(int n){double r=5;int x,y,z,w=pow(2,n);V o;for(x=0;x<w;++x)for(y=0;y<w-x;++y){z=w-1-x-y;o.push_back({-cos(7*M_PI/6)*(r*y-r*z),r*x-(r*y+r*z)/2,(B(x)+B(y)+B(z))%2==n%2});}return o;}int v(int n){RenderWindow w(VideoMode(1200,1000),"");CircleShape h(4,6);;auto v=d(n);while(w.isOpen()){Event event;while(w.pollEvent(event))if(event.type==Event::Closed)w.close();w.clear();for(auto&a:v){h.setPosition(a.x,-a.y);h.setOrigin(-600,-650);h.setFillColor(a.b?Color::Yellow:Color::Blue);w.draw(h);}w.display();}return 0;}

```

Function to call in the main is `v(int)` with the parameter being n, the number `n`

```
int main() {
    return v(6);
}

```

Compile with : `g++ source.cpp -lsfml-graphics -lsfml-window -lsfml-system`

Run with : `./a.out`

Due to the screen size and the fact that hexagons have to be visible, the size of a n=10 triangle can't be seen fully in a 'normal' sized screen, triangle is fully visible in the screen at n\<=7. Size of hexagon and space between them can be configured in the `d(int)` function with variable `r` and `v(int)` function by modifying the first parameter of the constructor of the `h` variable (the CircleShape object), that value being the radius of the circle. Be free to modify those parameters to draw bigger hexagons on the screens, `r` should be slightly bigger that the circle's radius

Here is an image of the result for `n=6`
> 5 votes

# Answer
# Wolfram Language (Mathematica), 222 bytes

```
n=6;c=Graphics[{#,Rotate[Polygon@CirclePoints@6,30Degree]},ImageSize->9]&;Column[Row/@TakeList[(Tr@DigitCount[#,2,1]~Mod~2&/@Reverse@Select[Range[0,h=2^n-1]~Tuples~3,Tr@#==h&])/.{1->c@Red,0->c@Blue},Range[2^n]],Center,.01]

```
> 3 votes

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


title: How spherical is my ellipsoid?

text:
# Question
Title: How spherical is my ellipsoid?
Define the (unnormalised) Willmore energy of a surface as the integral of squared mean curvature over it: $$W=\int\_SH^2\\,dA$$ For surfaces topologically equivalent to a sphere \\$W\ge4\pi\\$, and \\$W=4\pi\\$ iff it is actually a sphere. Thus the energy quantifies how spherical a surface is.

In September 2020 I asked on MathsSE how to simplify the Willmore energy of an ellipsoid with semi-major axes \\$a\ge b\ge c\ge0\\$. Two days later I had done it myself:

> Define $$A=a^2,B=b^2,C=c^2,\varphi=\cos^{-1}\frac ca$$ $$g=\sqrt{(A-C)B},m=\frac{(B-C)A}{(A-C)B}$$ Then $$\color{red}{\begin{align}W=\frac\pi{3ABC}&\Big(C(5AB+2AC+2BC)\\ &+2(AB+AC+BC)E(\varphi,m)g\\ &+BC(AB+AC+2BC-A^2)F(\varphi,m)/g\Big)\end{align}}$$

Here \\$F\\$ and \\$E\\$ are the elliptic integrals of the first and second kinds respectively. (Note that as with all my elliptic integral/function answers on MathsSE the argument convention is as in Mathematica and mpmath, where \\$m\\$ is the *parameter*.) Later on I derived a much cleaner and order-agnostic formula in terms of Carlson's symmetric integrals\\$A,B,C\\$ keep their meanings: $$W=\frac\pi3\left(3+4\left(\frac1A+\frac1B+\frac1C\right)R\_G(AB,CA,BC)-(A+B+C)R\_F(AB,CA,BC)\right)$$ I was inspired to write this question after writing answers to the ellipse perimeter and ellipsoid surface area questions that use the symmetric integrals. In the former case it actually saves one byte over an answer using the classic formula.

## Task

Given an ellipsoid's semi-axes \\$a,b,c\\$, which you may assume are sorted and positive, output the ellipsoid's Willmore energy with a relative error of at most \\$10^{-3}\\$. You may use either formula above or something else entirely like explicitly integrating the squared mean curvature.

This is ; fewest bytes wins.

## Test cases

```
(1, 1, 1) 12.5663706143592
(2, 1, 1) 15.4516066443266
(2, 2, 1) 16.9023119660317
(3, 2, 1) 21.2244261324396
(2, 2, 2) 12.5663706143592
(6, 1, 1) 34.2162831541838
(6, 5, 1) 70.4793621781325
(13, 9, 6) 15.9643343585267

```

# Answer
> 9 votes
# JavaScript (ES6), 195 bytes

Quite obviously not the right tool for the job, at least without any specialized library. The only math builtins used here are \\$\sin\\$, \\$\cos\\$ and \\$\operatorname{hypot}\\$.

The precision can be improved by using a smaller increment (the \\$i\\$ in the code). The version below uses \\$i=10^{-2}\\$ so that it doesn't time-out on TIO. But as a result, the relative error is \\$\approx10^{-1}\\$.

```
with(Math)f=(a,b,c)=>{i=1e-2;for(F=G=p=0;S=sin(p+=i),P=S*i*i/12,p<PI;)for(q=0;q<2*PI;G+=P*Q)F+=P/(Q=hypot(a*b*S*cos(q+=i),c*a*S*sin(q),b*c*cos(p)));return(4/a/a+4/b/b+4/c/c)*G-(a*a+b*b+c*c)*F+PI}

```

Try it online!

### Formulas

This is derived from the second formula given in the challenge and the following formulas from this page for Carlson's symmetric integrals:

$$R\_F(x,y,z)=\frac{1}{4\pi}\int\_{0}^{2\pi}\int\_{0}^{\pi}\frac{\sin\theta\\:d\theta\\:d\phi}{(x\sin^2\theta\cos^2\phi+y\sin^2\theta\sin^2\phi+z\cos^2\theta)^{1/2}}$$ $$R\_G(x,y,z)=\frac{1}{4\pi}\int\_{0}^{2\pi}\int\_{0}^{\pi}(x\sin^2\theta\cos^2\phi+y\sin^2\theta\sin^2\phi+z\cos^2\theta)^{1/2}\sin\theta\\:d\theta\\:d\phi$$

# Answer
> 5 votes
# Wolfram Language (Mathematica), 63 bytes

-1 byte and fixed a bug thanks to @att.

```
Pi/3(3.-Tr[s=#^2]CarlsonRF@@(t=##&@@s/s)+4Tr[1/s]CarlsonRG@@t)&

```

`CarlsonRG` and `CarlsonRF` are new functions in Mathematica 12.3, so this does not work on TIO.

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


# Question
Title: Distance to the average of the next two prime numbers
Suppose we have a sequence \\$P\\$. Every element \\$P\_n\\$ represents the distance between the \\$n^{th}\\$ prime number and the average of the next two prime numbers.

For example, \\$P\_1\\$ would be the distance between the first prime number (2) and the average of the next two prime numbers (3 and 5), so \\$P\_1 = \frac{3+5}{2} - 2 = 2\\$. Similarly, \\$P\_2 = \frac{5+7}{2} - 3 = 3\\$.

## Input

Your input is an integer \\$n\\$. You may assume \\$n\>0\\$.

## Output

Your task is to print out the sequence \\$P\\$ up to \\$n\\$, starting from \\$P\_1\\$. You can format your output however you like as long as every element is clearly separated.

## Rules

* This is , so shortest number of bytes wins.
* You can assume that every computed number will be within the limits of the language you choose, so no need to worry about how big \\$n\\$ or \\$P\_n\\$ can get.

## Test cases

```
Input            Output
n = 1            2
n = 2            2, 3
n = 5            2, 3, 4, 5, 4
n = 10           2, 3, 4, 5, 4, 5, 4, 7, 7, 5

```

(If you're curious, this sequence is A305748!)

# Answer
> 5 votes
# Vyxal, 8 bytes

*-1 byte thanks to AndrovT*

```
ƛ⇧ṡ‹ǎḣṁε

```

Try it Online! | 7 bytes to output the nth number | 9 bytes as an infinite list by emanresu A

**Explantion:**

```
ƛ⇧ṡ‹ǎḣṁε
ƛ           Implicitly take input, convert it to a range and open mapping lambda :P
 ⇧ṡ         Range between n and n+2
   ‹ǎ       Decrement and get the respective prime (1-indexed)
     ḣṁε    Head extract; push mean and get the abs difference

```

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

Returns a space-separated string.

```
f=(n,q=p=3,r=2,x=p++)=>n?--x?f(n,q,r,p%~x?x:p++):(p+q)/2-r+' '+f(n-1,p,q):''

```

Try it online!

### Commented

```
f = (               // f is a recursive function taking:
  n,                //   n = number of terms to generate
  q =               //   q = previous confirmed prime
  p = 3,            //   p = current prime candidate
  r = 2,            //   r = penultimate confirmed prime
  x = p++           //   x = divisor (post-increment p here)
) =>                //
n ?                 // if we still have some terms to generate:
  --x ?             //   decrement x; it it's not zero:
    f(              //     do a recursive call:
      n, q, r,      //       pass n, q and r unchanged
      p % ~x ?      //       if x + 1 does not divide p:
        x           //         keep using x as the divisor
      :             //       else (p is composite):
        p++         //         reset the divisor to p and increment p
    )               //     end of recursive call
  :                 //   else (p is prime):
    (p + q) / 2 - r //     append (p + q) / 2 - r, which is the next
    +               //     term of the sequence by definition
    ' ' +           //     followed by a space
    f(              //     followed by the result of a recursive call:
      n - 1,        //       decrement n
      p, q          //       set (q, r) = (p, q)
    )               //     end of recursive call
:                   // else:
  ''                //   stop

```

# Answer
> 4 votes
# 05AB1E, 10 bytes

```
ÌÅpü3ε`+;α

```

Try it online or verify all test cases.

Or alternatively:

```
>ÝØDü2ÅA¦α

```

Try it online or verify all test cases.

**Explanation:**

```
Ì           # Increase the (implicit) input-integer by 2
 Åp         # Pop and push the first input+2 amount of prime numbers
   ü3       # Get all overlapping triplets of this list
     ε      # Map each triplet to:
      `     #  Pop and push the three values in the triplet separated to the stack
       +    #  Add the top two together
        ;   #  Halve this sum
         α  #  Get the absolute difference with the third one
            # (after which the list is output implicitly as result)

>           # Increase the (implicit) input-integer by 1
 Ý          # Pop and push a list in the range [0,input+1]
  Ø         # Get the 0-based index for each of these values
   D        # Duplicate this list
    ü2      # Get all overlapping pairs of the copy
      ÅA    # Get the arithmetic mean of each inner pair
        ¦   # Remove the first one
         α  # Get the absolute difference between the values in the two lists
            # (the trailing additional item of the prime-list is discarded)
            # (after which the list is output implicitly as result)

```

# Answer
> 3 votes
# Husk, 10 bytes

```
↑Ẋ₁İp
≠⁰½+

```

Try it online!

```
≠⁰½+    # helper function with 3 args:
≠       # absolute difference between
 ⁰      #   first arg and
  ½     #   half
   +    #   the sum of
        #   the (implicit) other 2 args

↑Ẋ₁İp   # main program:
↑       # get the first input elements of
 Ẋ₁     #   applying helper function ₁ to groups of 3
   İp   #   from the infinite list of primes

```

Same byte-count to output the `n`-th element (by swapping the initial  for `!` \[index\]), or one byte less to output the infinite sequence (9 bytes, by omitting the initial ).

# Answer
> 3 votes
# Factor \+ `grouping.extras math.primes`, 46 bytes

```
[ 2 + nprimes [ + 2/ - abs ] 3 clump-map ... ]

```

Could be 42 bytes without the restrictive IO.

```
2 + nprimes       ! get the first input+2 primes
[                 ! begin clump-map
    + 2/          ! the average of the next two primes
    - abs         ! subtracted by the current prime
] 3 clump-map     ! map over every three elements with overlapping
...               ! prettyprint a sequence of any length to stdout

```

# Answer
> 2 votes
# Java 8, ~~111~~ 106 bytes

```
n->{for(int a=2,b=3,c,k=5;n>0;){for(c=1;k%++c>0;);if(k++==c){System.out.println((b+c)/2-a);a=b;b=c;n--;}}}

```

Prints the results on separated newlines to STDOUT.

Try it online.

**Explanation:**

```
n->{              // Method with integer parameter and no return-type
  int a=2,b=3,    //  Previous two primes, starting at hard-coded 2 and 3
      c,          //  Current prime, uninitialized
      k=5;        //  Prime-loop integer, starting at the third prime 5
  for(;n>0;){     //  Loop as long as the input `n` is not 0 yet:
    for(c=1;      //   Reset `c` to 1
        k%++c>0;);//   Keep increasing `c` as long as `c` is NOT divisible by `k`
    if(k++==c){   //   If `k` and `c` are now equal (which means `c` is a prime number):
                  //   (and increase `k` by 1 afterwards for the next iteration with `k++`)
      System.out.println((b+c)/2-a);
                  //    Print (b+c)//2-a with trailing newline
      a=b;b=c;    //    Then set a=b and b=c for the next iteration
      n--;}}}     //    And decrease `n` by 1

```

# Answer
> 2 votes
# , ~~21~~ 20 bytes

```
3(-~-:)`+/\p:@i.@+&2

```

Try it online!

* `+` `&` `2`: Add 2 to *n*.
* And then (`@`, composition), `i.`: Make a list of the first *n*+2 nonnegative integers.
* And then (`@`, composition), `p:`: Get the prime numbers of those indices.
* `3` ...`\`: Apply the inside verb to each three consecutive prime numbers.
    + `(-~-:)` ``` `+` `/`: Insert the two subverbs between the prime numbers, turning `p q r` into `p (-~-:) (q + r)`.
        - `q + r` adds (`+`) `q` and `r`.
        - `(-~-:)` is a hook; it halves (`-:`) the sum of `q` and `r`, and then subtracts (`-`) `p` from the result; `~` swaps the operands from their usual order.

# Answer
> 2 votes
# Retina 0.8.2, 95 bytes

```
\d+
__¶$&$*#___
#(#*(_+))
$2¶$1_
}+`\b(__+)\1+$
$&_
M!&`\b_+¶_+¶_+
(_+)¶\1(_+)¶\1(\2(_+))\4
$.3

```

Try it online! Explanation:

```
\d+
__¶$&$*#___

```

On the first pass, convert the input to `2,n,3` where `n` is a unary run of `#`s while the primes are unary using `_`s.

```
#(#*(_+))
$2¶$1_

```

Replace `n,p` with `p,n-1,p+1`.

```
+`\b(__+)\1+$
$&_

```

Increment the last value until it becomes prime.

```
}`

```

Repeat the above until `n=0`.

```
M!&`\b_+¶_+¶_+

```

Extract overlapping windows of three primes.

```
(_+)¶\1(_+)¶\1(\2(_+))\4
$.3

```

Match each set of three primes as `\1, \1+\2, \1+\2+\4+\4` and calculate `\2+\4` in decimal; `\1+\2+\4` is the average of the second and third primes so `\2+\4` is the difference between that and the first prime.

# Answer
> 2 votes
# Haskell, 92 bytes

```
(`take`((zipWith3(\x y z->div(x+y)2-z)=<<tail)=<<tail)[x|x<-[2..],all((0/=).mod x)[2..x-1]])

```

# Answer
> 1 votes
# Python 3, 98 bytes

```
f=lambda n:n and f(n-1)+[(g(n+1)+g(n+2))//2-g(n)]or[]
g=lambda n,i=1,p=1:n and-~g(n-p%i,i+1,p*i*i)

```

Try it online!

I couldn't find a better way than using a helper function, `g`, (stolen from Lynn's amazing answer on the tips question) to get the n<sup>th</sup> prime.

However, with default rules, it would be 77 bytes.

# Answer
> 1 votes
# Wolfram Language (Mathematica), 40 bytes

```
(#2+#3)/2-#&@@Prime[#+{0,1,2}]&~Array~#&

```

Try it online!

# Answer
> 1 votes
# Charcoal, 41 bytes

```
Ｎθ≔¹ηＷ‹ⅉθ«≦⊕η¿⬤υ﹪ηκ«Ｆ‹⁴η⟦Ｉ⁻⊘⁺η↨υ⁰§υ±²⟧⊞υη

```

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

```
Ｎθ

```

Input `n`.

```
≔¹η

```

Start looking for primes after `1`.

```
Ｗ‹ⅉθ«

```

Repeat until `n` results have been obtained.

```
≦⊕η

```

Increment the candidate prime.

```
¿⬤υ﹪ηκ«

```

If it is indeed prime, then:

```
Ｆ‹⁴η

```

If it is at least the third prime, then...

```
⟦Ｉ⁻⊘⁺η↨υ⁰§υ±²⟧

```

... output the difference of the average with the previous prime with the prime before.

```
⊞υη

```

Add the prime to the list.

# Answer
> 1 votes
# \[Wolfram Language (Mathematica)\], 42 bytes

```
ListConvolve[{1,1,-2}/2,Prime@Range[#+2]]&

```

Try it online!

# Answer
> 1 votes
# Jelly, 12 bytes

```
3Ḷ+)ÆNḋ-,.,.

```

Try it online!

This *has* to be possible in 11 bytes if a hardcoded dot product ties everything else I've come up with...

```
3Ḷ              [0, 1, 2]
  +             plus
   )            each [1 .. n], individually.
    ÆN          Get the x'th prime for each x in that matrix,
      ḋ         then return each row's dot product with
       -,.,.    [-1, 0.5, 0.5].

```

# Answer
> 1 votes
# Raku, 49 bytes

```
{(-*+(*+*)/2)(|grep(&is-prime,2..*)[^3+$++])xx$_}

```

Try it online!

Without the requirement for preceding elements, this could output the nth element for 42 bytes:

```
-*+(*+*)/2 o{grep(&is-prime,2..*)[^3+$_]}

```

Try it online!

# Answer
> 0 votes
# Wolfram Language (Mathematica), ~~53~~ 47 bytes

```
(#3+#2)/2-#&@@@Partition[Prime@Range[#+2],3,1]&

```

Thanks to @ZaMoC

Try it online!

# Answer
> 0 votes
## BSD/Linux command line, 52 bytes

Requirements:

* any Bourne-style shell;
* awk;
* the `primes` program from the classic BSD games collection (`bsdgames` package on Debian, Ubuntu and derivatives, `bsd-games` on Fedora, …).

```
primes 2|awk '{a=b;b=c;c=$0;$0=(c+b)/2-a}a'|head -$1

```

Try it online: there seems to be a bug in the version of awk on TIO which causes it to print blanks when printing `$0` (implicitly or explicitly) and `$0` is numeric. The version in my answer does work on my machines. Here's modified code with a workaround — obviously the workaround for the bug on TIO increases the length (by two bytes: an extra `""`).

# Answer
> 0 votes
## F#, 188 bytes

```
let x=Seq.initInfinite
let p n=n=2||Seq.forall(fun c->n%c<>0)[2..n-1]
let f n=x(fun i->n+i+1)|>Seq.find p
let s n=x(fun i->i+2)|>Seq.where p|>Seq.map(fun p->(f p+(f p|>f))/2-p)|>Seq.take n

```

Try it online!

Didn't think it would end up so big, to be honest. I wonder if my approach is maybe wrong... but it's all functional, stateless, and inefficent.

Anyway, a brief explanation:

`x` is a shorthand for `Seq.initInfinite`, which creates endless, lazy-evaluated sequences. `p n` determines if a number `n` is prime. `f n` gets the next prime number after `n`. `s n` is the main sequence function. First it creates a sequence of primes, then for each of them, gets the next prime and next-next prime, and calculates the average. Finally, it takes the first `n` elements in the sequence.

---
Tags: code-golf, sequence, primes
---