title: No parentheses shall be omitted

text:
# Question
Title: No parentheses shall be omitted
This expression actually has an omitted pair of parentheses.

```
1 + 2 * 3

```

To make things clear, it should be,

```
1 + (2 * 3)

```

Even this has its parentheses missing.

```
1 + 2 + 3

```

It actually means,

```
(1 + 2) + 3

```

People often assume left-to-right evaluation to such an arithmetic expression, but I want to make everything very clear.

**Given an arithmetic expression, add parentheses until the order of evaluation is clear without any assumption, and don't remove any pre-existing parentheses.**

Here are some examples of possible inputs and their expected output.

```
IN
OUT

IN  1
OUT 1

IN  (((1)))
OUT (((1)))

IN  1+2+3+4+5
OUT (((1+2)+3)+4)+5

IN  1/2/3/4/5
OUT (((1/2)/3)/4)/5

IN  1/2/((3/4))/5
OUT ((1/2)/((3/4)))/5

IN  1+2-3*4/5+6-7*8/9
OUT (((1+2)-((3*4)/5))+6)-((7*8)/9)

IN  1+(2-3*4/5+6-7)*8/9
OUT 1+(((((2-((3*4)/5))+6)-7)*8)/9)

```

The expression will be composed of single-digit numbers, operators `(+, -, *, /)`, and parentheses. The typical rules of evaluation apply; left-to-right, parentheses first, multiplication first.

The input may have whitespaces, which has no effect, but your program should be able to handle them. The output must have no whitespace and have the same format as given in the examples. The input should be read either as a command line argument or from `stdin`, and the code should be runnable with no additional code.

This is a `code-golf` challenge.

Here's a rather formal definition of an arithmetic expression.

```
primary-expression
  [0-9]
  (arithmetic-expression)

multiplicative-expression
  primary-expression
  multiplicative-expression (* | /) primary-expression

additive-expression
  multiplicative-expression
  additive-expression (+ | -) multiplicative-expression

arithmetic-expression
  additive-expression

```

This is a python script that you can use to validate your output (in a very manual way..).

I had fun writing Lisp in Python.

```
def addop(op):
    return op == '+' or op == '-'

def match(l):
    if l[1:] == []:
        return [1, l]
    elif addop(l[1]):
        if l[3:] == [] or addop(l[3]):
            return [3, l[0:3]]
        else:
            m = match(l[2:])
            return [m[0] + 2, l[0:2] + [m[1]]]
    else:
        if l[3:] == [] or addop(l[3]):
            return [3, l[0:3]]
        else:
            m = match([l[0:3]] + l[3:])
            return [m[0] + 2, m[1]]

def tree__(l):
    m = match(l)
    if l[m[0]:] == []:
        return m[1]
    else:
        return tree__([m[1]] + l[m[0]:])

def tree_(l):
    if l == []:
        return []
    elif isinstance(l[0], list):
        return [tree_(tree__(l[0]))] + tree_(l[1:])
    else:
        return [l[0]] + tree_(l[1:])

def tree(l):
    return tree_(tree__(l))

def afterParen(s, n):
    if s == '':
        return '';
    if s[0] == '(':
        return afterParen(s[1:], n + 1)
    if s[0] == ')':
        if n == 0:
            return s[1:]
        else:
            return afterParen(s[1:], n - 1)
    else:
        return afterParen(s[1:], n)

def toList(s):
    if s == '' or s[0] == ')':
        return []
    elif s[0] == '(':
        return [toList(s[1:])] + toList(afterParen(s[1:], 0))
    elif s[0].isspace():
        return toList(s[1:])
    elif s[0].isdigit():
        return [int(s[0])] + toList(s[1:])
    else:
        return [s[0]] + toList(s[1:])

def toString(l):
    if l == []:
        return ''
    elif isinstance(l[0], list):
        return '(' + toString(l[0]) + ')' + toString(l[1:])
    elif isinstance(l[0], int):
        return str(l[0]) + toString(l[1:])
    else:
        return l[0] + toString(l[1:])

def addParen(s):
    return toString(tree(toList(s)))

exp = "1+2*3+4+2+2-3*4/2*4/2"
print(exp)
print(addParen(exp))
exp = "((1+2*(3+4)+(((((2))+(2-3*4/2)*4)))/2))"
print(exp)
print(addParen(exp))

```

# Answer
> 5 votes
# Pip 1.0, ~~20~~ 19 bytes

```
a&TM(ST V"{}"Ja)DCs

```

Try It Online!

Verify all test cases

### Explanation

Episode 2 in the "Hey, my language happens to do exactly that!" saga...

In Pip 1.0, the string representation of a function is derived by "unparsing" the function's parse tree. Because I was lazy, I decided to just put parentheses around every subexpression, rather than trying to eliminate the parentheses that weren't necessary. Also, because I was lazy, redundant layers of parenthesization are kept in the parse tree, so they also remain in the string representation.

Thus, all this program does is convert the input to a function, get that function's string representation, and delete a few extra characters. The empty string is a corner case that costs +2 bytes.

```
a&TM(ST V"{}"Ja)DCs
a                    First command-line argument
 &                   If it is truthy (not empty or 0), then:
         "{}"          This string
             Ja        Joined on the argument (essentially, wrap the arg in {})
        V              Eval the resulting string as a Pip expression
                       The string will always be a valid function literal, so
                       the result is a Pip function
     ST                Stringify
  TM(          )       Trim off the curly braces
                DCs    Delete all spaces
                     If the arg is falsey, use the arg itself ("" or "0")

```

# Answer
> 1 votes
# Retina 0.8.2, 237 bytes

```
\s

+1`(?<=(^|\()?)(\d|\(((\()|(?<-4>\))|[^()])+(?(4)$)\))[*/](\d|\(((\()|(?<-7>\))|[^()])+(?(7)$)\))(?(1)(?!$|\)))
($&)
+1`(?<=(^|\()?)(\d|\(((\()|(?<-4>\))|[^()])+(?(4)$)\))[-+](\d|\(((\()|(?<-7>\))|[^()])+(?(7)$)\))(?(1)(?!$|\)))
($&)

```

Try it online! Link includes test cases. Explanation:

```
\s

```

Delete white space.

```
+`

```

Repeat until no more replacements can be made.

```
1`

```

Make only one replacement at a time.

```
(?<=(^|\()?)

```

See whether this subexpression begins at the beginning of the string or after a `(`.

```
(\d|\(((\()|(?<-4>\))|[^()])+(?(4)$)\))

```

Match either a digit or a balanced subexpression (using a .NET balancing group).

```
[*/]

```

Match either a `*` or a `/` sign.

```
(\d|\(((\()|(?<-7>\))|[^()])+(?(7)$)\))

```

Match another digit or balanced subexpression.

```
(?(1)(?!$|\)))

```

If the match started at the beginning of the string or after a `(`, it must not match at the end of the string or after a `)`, because this subexpression is already parenthesised (or is the whole expression, which does not need to be parenthesised).

```
($&)

```

Parenthesise this match.

```
+1`(?<=(^|\()?)(\d|\(((\()|(?<-4>\))|[^()])+(?(4)$)\))[-+](\d|\(((\()|(?<-7>\))|[^()])+(?(7)$)\))(?(1)(?!$|\)))
($&)

```

Do the `-` and `+` signs in the same way.

---
Tags: code-golf, math, arithmetic
---


title: ASCII-Plot the equation

text:
# Question
Title: ASCII-Plot the equation
You are given a polynomial function, in the following format:

\\$x = (c\_0 * y^0) + (c\_1 * y^1) + (c\_2 * y^2) + ... + (c\_n * y^n)\\$

where \\$c\_n\\$ stands for the coefficient of the \\$n^{th}\\$ power of \\$y\\$

You have to plot the equation on a \\$10 * 10\\$ ASCII matrix. The value must be **floored** to an integer before plotting. If \\$y \< 0\\$ or \\$y \> 9\\$, then do not plot. For simplicity, we are assuming the top left corner to be \\$(0,0)\\$.

A `.` represents an empty space, and `*` represents a point on the graph. You can choose any characters to represent both of the things as per your convenience but do mention what you use in your answer.

You may take the input as a list/array of coefficients, or, as a string in the above specified format.

Examples:

```
Input -> x = (1 * y^1)
Output ->
*.........
.*........
..*.......
...*......
....*.....
.....*....
......*...
.......*..
........*.
.........*

Input -> x = (9 * y^0) + (-1 * y^1)
Output ->
.........*
........*.
.......*..
......*...
.....*....
....*.....
...*......
..*.......
.*........
*.........

Input -> x = (0.10 * y^2)
Output ->
*.........
*.........
*.........
*.........
.*........
..*.......
...*......
....*.....
......*...
........*.

Input -> x = (3 * y^1)
*.........
...*......
......*...
.........*
..........
..........
..........
..........
..........
..........

```

*Hint: eval can be helpful here.*

Inspired by a clash of code problem from https://www.codingame.com/

# Answer
# APL (Dyalog Unicode), 15 bytes

Full program. Takes list of coefficients in descending order. Returns Binary matrix. Requires 0-based indexing (`⎕IO←0`).

```
a∘.=⍨⌊⎕⊥⍨⍪a←⍳10

```

Try it online!

`⍳10`**i**ndices 0…9

`a←` store as `a`

make into column vector

`⎕⊥⍨` prompt for coefficients and evaluate the them as digits in base each-element-of-`a`

floor

`a∘.=⍨` equality table with `a` horizontally
> 5 votes

# Answer
# Factor \+ `math.polynomials`, 73 bytes

```
[ 10 iota dup -rot '[ _ polyval 1 /i _ [ = pprint ] with each nl ] each ]

```

Try it online!

Takes a sequence of coefficients from low to high. `polyval` handles the actual evaluation of the polynomial; the rest is just data plumbing and output.

`1 /i` is to convert from a float to integer, as it is shorter than `>integer` (and `floor` doesn't produce an integer in Factor \[AND `1 /i =` is shorter than `number=` by 1 byte\]). I found a locals solution that was the same length, but couldn't save any bytes. You can save 2 bytes by using a modern version of Factor with `tuck`, but meh.

Prints `t` for a point on the graph and `f` for empty space.
> 4 votes

# Answer
# , 15 bytes

*-2 thanks to Jonah!*

```
(<.@p.=/])i.@10

```

Try it online!

Execute the left function with `i.@10` (`0 1 2 … 9`) as the right argument. `<.@p.` apply polynomial (thanks J for the built-in!) to each `i.@10`, floor and compare each result to `i.@10` with `=/`.
> 4 votes

# Answer
# Charcoal, 10 bytes

```
Ｅχ⭆χ⁼λ⌊↨ιθ

```

Try it online! Takes input as a list of coefficients (in order of highest power of y down to 1) and outputs a binary matrix. Explanation:

```
 χ          Predefined variable 10
Ｅ           Map over implicit range
   χ        Predefined variable 10
  ⭆         Map over implicit range and join
         θ  Input coefficients
        ι   Outer index
       ↨    Evaluate polynomial
      ⌊     Floor
     λ      Inner index
    ⁼       Do they equal?
            Implicitly print

```
> 4 votes

# Answer
# JavaScript (ES7),  ~~87 85 83~~  81 bytes

Expects an array of coefficients, from lowest to highest.

```
a=>(g=x=>y>9?'':`
*.`[x>9?x=++y-y:a.reduce((p,c,i)=>p+c*y**i)^x++?2:1]+g(x))(y=0)

```

Try it online!

### Commented

```
a => (                   // a[] = input array of coefficients
  g = x =>               // g is a recursive function taking x
  y > 9 ?                // if this is the end of the graph:
    ''                   //   stop the recursion
  :                      // else:
    `\n*.`[              //   lookup string: 0 = '\n', 1 = '*', 2 = '.'
      x > 9 ?            //   if this is the end of the row:
        x = ++y - y      //     increment y, set x to 0, yield 0
      :                  //   else:
        a.reduce(        //     compute P(y)
          (p, c, i) =>   //       which is the sum of all
          p + c * y ** i //       a[i] * y ** i
        ) ^ x++          //     test whether floor(P(y)) = x
        ? 2              //     and yield 2 if it's not
        : 1              //     or 1 if it is
    ] +                  //
    g(x)                 //   do a recursive call
)(y = 0)                 // initial call with x = y = 0

```
> 3 votes

# Answer
# Stax, 20 bytes

```
éR▒Å╗←û%╞.A◄→⌐‼²GÑd,

```

Run and debug it

Very long, partly due to `floor` not working on integers.

uses 1 and 0 as the display chars.
> 2 votes

# Answer
# Python 3, 112 bytes

```
def f(l,*m):
 for x in range(10):
  try:m=[*m,[0]*10];m[x][int(sum(y*x**z for y,z in l))]=1
  except:1
 return m

```

Try it online!

-15 bytes thanks to @UnrelatedString

-3 bytes thanks to @ophact
> 2 votes

# Answer
# C (gcc), <sup>~~164~~ \\$\cdots\\$ ~~123~~</sup> 111 bytes

Saved 2 bytes thanks to att!!!

```
y;i;f(l,n,x)float*l,x;{for(y=-1;x=y++<9;i=x>=1&x<11?x:0,puts("         *"+10-i))for(i=n;i--;)x+=l[i]*pow(y,i);}

```

Try it online!

Uses the space () character for background and an asterisk (`*`) for plot points.
> 2 votes

# Answer
# Python 3, 86 bytes

```
lambda l,r=range(10):[[i==sum(c*x**n for n,c in enumerate(l))//1for i in r]for x in r]

```

Try it online!

Takes a list of coefficients in ascending power. Outputs a list of lists of booleans.
> 2 votes

# Answer
# Haskell, 200 bytes

```
p[]x=0;p(s:r)x=x*p r x+s
q f=[[b$map(subtract y.p f)[x,x+1/4..x+3/4]|y<-n]|x<-n]
b=(['⠀'..]!!).a.map c
n=[0..9]
c x|x<0=[0,0]|x<0.5=[1,0]|x<1=[0,1]|x>0=[0,0]
a[[l,r]]=l*8+r*16
a([l,r]:s)=2*a s+l+r*8

```

Try it online!

The function `q` takes a list of polynomial-coefficients and generates braille dot-matrix characters. Example:

```
x = + (0.0 * y^0) + (0.0 * y^1) + (0.1 * y^2)
⡇
⡇
⢱
⠈⡆
⠀⠘⡄
⠀⠀⠘⡄
⠀⠀⠀⠘⢄
⠀⠀⠀⠀⠈⠢⡀
⠀⠀⠀⠀⠀⠀⠑⢄
⠀⠀⠀⠀⠀⠀⠀⠀⠑⢄

```
> 2 votes

# Answer
# Jelly, ~~10~~ ~~8~~ 7 bytes

```
⁵ḶɓḅḞ=€

```

Try it online!

*-2 bytes because the output format was loosened, then I noticed another golf in the course of writing the explanation*

*-1 byte because why the hell didn't I already try that?*

Input as coefficients in descending order of power, output as binary matrix.

```
⁵Ḷɓ        Let [0 .. 9] be the right argument to the following dyadic link:
   ḅ       evaluate the polynomial at each y in [0 .. 9],
    Ḟ      and floor each result.
      €    For each result,
     =     is it equal to each x in [0 .. 9]?

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), ~~46~~ 43 bytes

```
0<=#<1&/@(#-r)&/@FromDigits[#,r=0~Range~9]&

```

Try it online!

Input coefficients in descending order. Returns a 10x10 boolean matrix.
> 1 votes

# Answer
# Ruby, 78 bytes

```
->c{(a=0..9).map{|y|a.map{|x|z=1;x==c.reduce{|s,x|s+x*z*=y}.to_i ? ?*:?.}*''}}

```

Try it online!

Returns an array of 10 strings

# Ruby, 67 bytes

```
->c{(a=0..9).map{|y|a.map{|x|z=1;x==c.reduce{|s,x|s+x*z*=y}.to_i}}}

```

Try it online!

Return a matrix of booleans
> 1 votes

# Answer
# Pari/GP, 42 bytes

```
p->matrix(10,,y,x,y--;floor(eval(p))==x--)

```

Try it online!
> 0 votes

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


title: Oreoorererereoo

text:
# Question
Title: Oreoorererereoo
# Oreoorererereoo

Given an input string that is similar to the word "oreo", give an ASCII representation of the cookie that is as wide as the input string (to ensure cookie stability).

## Rules

* The input is lowercase, a non-empty string with no whitespace containing any combination of the strings "o" and "re", and containing only those strings.
* The string "o" represents the solid cookie, while the string "re" represents the filling.
* The output must be a stacked cookie that is as wide as the input string.
* The output may not be an array of strings
* The cookie must overlap the filling by one character on each side
* The characters used for the output don't have to match the output below (█ and ░), they just have to be different non-whitespace characters for the two parts of the cookie
* The whitespace padding on the left side of the filling is required, and any trailing whitespace is optional

## Examples

```
Input: oreo
Output:
████
 ░░
████

Input: o
Output:
█

Input: re
Output: (two spaces)

Input: rere
Output:
 ░░
 ░░

Input: oreoorererereoo
Output:
███████████████
 ░░░░░░░░░░░░░
███████████████
███████████████
 ░░░░░░░░░░░░░
 ░░░░░░░░░░░░░
 ░░░░░░░░░░░░░
 ░░░░░░░░░░░░░
███████████████
███████████████

```

Since this is code golf the shortest answer wins, good luck :)

# Answer
> 17 votes
# Jelly,  ~~16 14~~  13 bytes

-1 Thanks to Erik the Outgolfer

```
OḂƇẒṁ€aØ.¦€⁶Y

```

Uses `1` for the cream and `0` for the cookie.

**Try it online!**

### How?

```
OḂƇẒṁ€aØ.¦€⁶Y - Main Link: list of characters, V    e.g. 'orereo'
O             - ordinal (vectorises)                     [111,114,101,114,101,111]
  Ƈ           - filter keep those for which:
 Ḃ            -   modulo 2                               [111,    101,    101,111]
   Ẓ          - is prime? (vectorises)                   [  0,      1,      1,  0]
    ṁ€        - mould each like V                        [[0,0,0,0,0,0],[1,1,1,1,1,1],[1,1,1,1,1,1],[0,0,0,0,0,0]]
          €   - for each:
         ¦    -   sparse application...
       Ø.     -   ...to indices: literal [0,1] (0 is the rightmost index, 1 is the leftmost)
      a       -   ...apply: logical AND with:
           ⁶  -               space character           [[0,0,0,0,0,0],[' ',1,1,1,1,' '],[' ',1,1,1,1,' '],[0,0,0,0,0,0]]
            Y - join with newline characters            [0,0,0,0,0,0,'\n',' ',1,1,1,1,' ','\n',' ',1,1,1,1,' ','\n',0,0,0,0,0,0]
              - implicit print                       ...smashes everything together:
              -                                         000000
              -                                          1111
              -                                          1111
              -                                         000000

```

---

Previous 16 byter:

```
ḟ”eẋ€Ly@Ø.¦€⁾r Y

```

Uses `r` for the c`r`eam and `o` for the c`o`okie.

Try it online!

# Answer
> 19 votes
# Pepe, 364 bytes

Unfortunately the online interpreter does not take care of compressing comments, hence all `o` characters will be replaced by a space.. Neither the spaces nor the `o` are necessary, so this could be 295 bytes, but I like it more this way:

```
rEeEEeeEeEororEEoreoreeeEeeeeeorEEEEeoREeoreorEeEEeEEEEororEEoreorEEEEEoREeoreorEeEEEeeEeororEEoreoReoREoREEEeoREEEEEoreorEorEEEeorEEEEEoreEoREeoreoREEeoREEEEeEeeoREEEeoREeeEoREEEeoREEEEEEEorEEEeEorEEEeoREoREEEeoREEEEEoREEoReoreorEEEeEoREEEEEEeorEEEeoReEoREoREEEeoREEoReoroReEeoREoREEEeorEEEEeoReeoREEEeoREeeEoREEEeoREEEEEEEoreoReoReoREoREEEeoREEEEEoreeeeeEeEeoRee

```

Try it online!

## Ungolfed

There might be some golfing oppurtunities with *flags* which I missed, but I'm done for now:

```
# "function" for 'e'
rEeEEeeEeE rrEE
  re          # remove duplicated argument
  reeeEeeeee  # print space
  rEEEEe      # decrement counter twice
REe re

# "function" for 'o'
rEeEEeEEEE rrEE
  re      # remove duplicated argument
  rEEEEE  # increment counter
REe re

# "function for 'r'
rEeEEEeeEe rrEE
  re Re              # remove duplicated argument & char
  RE REEEe REEEEE    # push 1
  re rE rEEEe rEEEEE # replace 1
  reE                # goto 1
REe re

# Main

REEe REEEEeEee                # read input & reverse
REEEe REeeE REEEe REEEEEEE    # push length-1 & move to r

rEEEeE rEEEe # dummy loop-var (fucking do-whiles...)
RE REEEe REEEEE REE  # while [label-1]

  # Call the right procedure depending on current character,
  # sets stacks up as follows:
  #   R [ .... *currentChar ]
  #   r [ (N-1) *count ]
  Re re          # pop 1 & loop-counter
  rEEEeE         # duplicate counter
  REEEEEEe rEEEe # copy current char to other stack
  ReE            # jeq to 'o'-label or 'e'-label

  # Output currentChar count times:
  RE REEEe REE # while [label-0]:
    Re         #   pop 0
    rReEe      #   print character
    RE REEEe   #   push 0
    rEEEEe     #   decrement counter
  Ree

  REEEe REeeE REEEe REEEEEEE  # push length-1 & move to r
  re Re Re                    # pop 0, counter and 9((((currentChar
  RE REEEe REEEEE             # push 1
  reeeeeEeEe                  # print new-line

Ree

```

# Answer
> 10 votes
# Canvas, ~~19~~ ~~18~~ 17 bytes

```
e ∙╋
：r≠＊┤］；Ｌ×⁸↔⁸

```

Try it here!

Uses the annoyingly long code of `：r≠＊┤］` to remove `r`s from the input..

# Answer
> 8 votes
# Japt `-R`, ~~16~~ 15 bytes

```
re ¬£çX sX²èrÃû

```

Try it

```
                    :Implicit input of string U
re                  :Remove all "e"s
   ¬                :Split to array of characters
    £               :Map each X
     çX             :  Repeat X to the length of U
        s           :  Slice from index
         X²         :   Duplicate X
           èr       :   Count the occurrences of "r"
             Ã      :End map
              û     :Centre pad each element with spaces to the length of the longest
                    :Implicitly join with newlines and output

```

---

## Alternatives

```
re ¬ËpUÊaD²èrÃû
re ¬£îX rr²i^Ãû

```

# Answer
> 7 votes
# 05AB1E, ~~18~~ ~~17~~ 16 bytes

```
'eKεD'rQ2*Igα×}.c

```

-1 byte thanks to *@Emigna*

Uses `o` for the cookie and `r` for the filling.

Try it online or verify all test cases.

**Explanation:**

```
'eK                 '# Remove all "e" from the (implicit) input
                     #  i.e. "orereo" → "orro"
   ε         }       # Map all characters to:
    D                #  Duplicate the current character
     'rQ            '#  Check if it's an "r" (1 if truthy; 0 if falsey)
                     #   i.e. "r" → 1
                     #   i.e. "o" → 0
        ·            #  Double that
                     #   i.e. 1 → 2
                     #   i.e. 0 → 0
         Ig          #  Take the length of the input
                     #   i.e. "orereo" → 6
           α         #  Take the absolute difference between the two
                     #   i.e. 2 and 6 → 4
                     #   i.e. 0 and 6 → 6
            ×        #  Repeat the duplicated character that many times
                     #   i.e. "r" and 4 → "rrrr"
                     #   i.e. "o" and 6 → "oooooo"
              .c     # Then centralize it, which also imlicitly joins by newlines
                     # (and the result is output implicitly)
                     #  i.e. ["oooooo","rrrr","rrrr","oooooo"]
                     #   → "oooooo\n rrrr\n rrrr\noooooo"

```

# Answer
> 6 votes
# C# (Visual C# Interactive Compiler), 95 bytes

```
n=>n.Replace("o",new String('-',n.Length)+"\n").Replace("re"," ".PadRight(n.Length-1,'|')+"\n")

```

Try it online!

# Alternative using Aggregate, 108 bytes

```
n=>n.Aggregate("",(d,c)=>d+(c<102?"":c<112?new String('-',n.Length)+"\n":" ".PadRight(n.Length-1,'|')+"\n"))

```

Try it online!

# Answer
> 6 votes
# , 106 bytes

```
function(s,N=nchar(s)){m=rep(el(strsplit(gsub('re',0,s),'')),e=N)
m[m<1&seq(m)%%N<2]=' '
write(m,1,N,,"")}

```

Try it online!

* -12 bytes thanks to @Giuseppe

---

Previous version with explanation :

# , 118 bytes

```
function(s,N=nchar(s)){m=t(replicate(N,el(strsplit(gsub('re',0,s),''))))
m[m<1&row(m)%in%c(1,N)]=' '
write(m,1,N,,'')}

```

Try it online!

* -1 byte thanks to @Giuseppe

Unrolled code and explanation :

```
function(s){                       # s is the input string, e.g. 'oreo'

  N = nchar(s)                     # store the length of s into N, e.g. 4

  s1 = gsub('re',0,s)              # replace 're' with '0' and store in s1, e.g. 'o0o'

  v = el(strsplit(s1,''))          # split s1 into a vector v of single characters
                                   # e.g. 'o','0','o'

  m = replicate(N,v)               # evaluate N times the vector v and arrange
                                   # the result into a matrix m (nchar(s1) x N)
                                   # e.g.
                                   # 'o' 'o' 'o' 'o'
                                   # '0' '0' '0' '0'
                                   # 'o' 'o' 'o' 'o'

  m = t(m)                         # transpose the matrix

  m[m<1 & row(m)%in%c(1,N)] = ' '  # substitute the zeros (i.e. where < 1)
                                   # on the 1st and last row of the matrix with ' ' (space)
                                   # e.g.
                                   # 'o' ' ' 'o'
                                   # 'o' '0' 'o'
                                   # 'o' '0' 'o'
                                   # 'o' ' ' 'o'

  write(m,1,N,,'')                 # write the matrix to stdout (write function transposes it)
                                   # e.g.
                                   # oooo
                                   #  00
                                   # oooo
}

```

# Answer
> 6 votes
# Retina, ~~21~~ 19 bytes

```
L$`.
$.=*$&
r+¶ee

```

Try it online! Link includes test cases. Explanation:

```
L$`.
$.=*$&

```

List each letter on its own line repeated to the length of the original input.

```
r+¶ee

```

Remove the lines of `r`s and replace the first two `ee`s on the next line with a space.

Edit: Saved 2 bytes thanks to @DomHastings.

# Answer
> 5 votes
# Retina, ~~74~~ 73 bytes

I feel like I haven't posted an answer in a very long time. Well, here I am. Also, Retina has changed a lot, and I feel like I suck at it now.

```
.+
$0$.0
(\d+)
*
e

o|r
$&¶
_$

+(/_/&`o¶
oo¶
_$

)/_/&`r¶
rr¶
¶$

m`^r

```

**Try it online!**

# Answer
> 5 votes
# C (gcc), ~~135~~ ~~113~~ ~~109~~ 104 bytes

```
#define $ putchar(33
O(char*r){for(char*e,*o=r,x;*r;$-23))for(x=*r++>111,e=x?$-1),r++,o+2:o;*e++;$+x));}

```

Try it online!

# Answer
> 5 votes
# JavaScript, ~~72~~ ~~65~~ 64 bytes

```
s=>s.replace(/.e?/g,([x,y])=>(y?`
 `:`
`).padEnd(s.length+!y,x))

```

Try it online

# Answer
> 5 votes
# Perl 5 `-p`, 47 bytes

```
s|o|X x($i=y///c).$/|ge;s|re|$".O x($i-2).$/|ge

```

Try it online!

# Answer
> 4 votes
# JavaScript ES6, 103 bytes

### Using replace 103 bytes:

```
x=>x.replace(/o/g,"-".repeat(s=x.length)+`
`).replace(/re/g," "+"|".repeat(s>1?s-2:0)+`
`).slice(0,-1)

```

Try it online!

### Using split and map 116 bytes:

```
x=>x.split("re").map(y=>("-"[h='repeat'](r=x.length)+`
`)[h](y.length)).join(" "+"|"[h](r>1?r-2:0)+`
`).slice(0,-1)

```

Try it online!

# Answer
> 4 votes
# Python 3, 77 bytes

```
lambda x:x.replace("o","-"*len(x)+"\n").replace("re"," "+'.'*(len(x)-2)+"\n")

```

Try it online!

# Answer
> 4 votes
# Pyth, 28 bytes

```
FNzIqN"o"*lzN)IqN"r"+d*-lz2N
FNz                              For each value, N, in input
   IqN"o"                        if the character is "o"
         *lzN                    return the character times the length of the input
             )                   end if
              IqN"r"             if the character is "r"
FNzIqN"o"*lzN)IqN"r"+d*-lz2N
                        *-lz2N   return the character times length - 2
                    +d           padded on the left with " "

```

Try it here! This one uses a loop.

# Pyth, 30 bytes

(As string replace)

```
::z"o"+*lz"="b"re"++d*-lz2"~"b
 :z"o"                           With the input, replace "o" with
       *lz"="                    "=" times the length of the input
      +      b                   and a newline added to the end
:             "re"               With the input, replace "re" with
                     *    "~"    "~" times
                      -lz2       the length of the input minus 2
                   +d            padded on the left with " "
                  +          b   and a newline added to the end

```

Try it here! This one uses string replacement.

I really like python (it's what I wrote my original test scripts in), so I thought I'd do a pyth entry for fun :)

# Answer
> 4 votes
# Java 11, ~~110~~ 106 bytes

```
s->{int l=s.length();return s.replace("re"," "+"~".repeat(l-2+1/l)+"\n").replace("o","=".repeat(l)+"\n");}

```

-4 bytes thanks to *@ceilingcat*.

Uses `=` for the cookie and `~` for the filling.

Try it online.

**Explanation:**

```
s->{                       // Method with String as both parameter and return-type
  int l=s.length();        //  Get the length of the input
  return s                 //  Return the input
          .replace("re",   //  After we've replaced all "re" with:
            " "            //   A space
            +"~".repeat(l-2+1/l)
                           //   Appended with length-2 amount of "~"
                           //   (or length-1 if the input-length was 1)
            +"\n")         //   Appended with a newline
          .replace("o",    //  And we've also replaced all "o" with:
            "=".repeat(l)  //   Length amount of "="
            +"\n");}       //   Appended with a newline

```

---

The above solution uses a replace. The following maps over the characters of the input instead:

# Java 11, ~~113~~ 112 bytes

```
s->s.chars().forEach(c->{if(c>101)System.out.println((c>111?" ":"")+(""+(char)c).repeat(s.length()-2*(~c&1)));})

```

-1 byte thanks to *@Neil*.

Try it online.

**Explanation:**

```
s->                           // Method with String parameter and no return-type
  s.chars().forEach(c->{      //  Loop over the characters as codepoint-integers
    if(c>101)                 //   If it's not an 'e':
      System.out.println(     //    Print with trailing newline:
       (c>111?                //     If it's an 'r'
         " "                  //      Start with a space
        :                     //     Else (it's an 'o' instead)
         "")                  //      Start with an empty string
       +(""+(char)c).repeat(  //     And append the character itself
          .repeat(            //     Repeated the following amount of times:
           s.length()         //      The input-length
           -2*(~c&1)));})     //      Minus 2 if it's an "r", or 0 if it's an "o"

```

# Answer
> 4 votes
# Powershell, ~~71~~ ~~69~~ 66 bytes

*-2 bytes thanks @Veskah*

*-3 bytes thanks @AdmBorkBork*

```
$l=$args|% le*
switch($args|% t*y){'o'{'#'*$l}'r'{" "+'%'*($l-2)}}

```

Less golfed test script:

```
$f = {

$l=$args|% length
switch($args|% t*y){
    'o'{'#'*$l}
    'r'{" "+'%'*($l-2)}
}

}

@(

,(
'oreo',
'####',
' %%',
'####'
)
,(
'o',
'#'
)
,(
're',
' '
)
,(
'rere',
' %%',
' %%'
)
,(
'oreoorererereoo',
'###############',
' %%%%%%%%%%%%%',
'###############',
'###############',
' %%%%%%%%%%%%%',
' %%%%%%%%%%%%%',
' %%%%%%%%%%%%%',
' %%%%%%%%%%%%%',
'###############',
'###############'
)

) | % {
    $s,$expected = $_
    $result = &$f $s
    "$result"-eq"$expected"
    # $result # uncomment this line to display a result
}

```

Output:

```
True
True
True
True
True

```

# Answer
> 4 votes
# PHP, ~~100~~ ~~99~~ 93 bytes

```
$l=strlen($i=$argv[1]);$r=str_repeat;echo strtr($i,[o=>$r(X,$l)."
",re=>' '.$r(o,$l-2)."
"]);

```

Try it online!

OUCH. PHP's waaaay\_too\_long function names strike again!

Output:

```
$php oreo.php oreo
XXXX
 oo
XXXX

$php oreo.php o
X

$php oreo.php rere
 oo
 oo

$ php oreo.php oreoorererereoo
XXXXXXXXXXXXXXX
 ooooooooooooo
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX
 ooooooooooooo
 ooooooooooooo
 ooooooooooooo
 ooooooooooooo
XXXXXXXXXXXXXXX
XXXXXXXXXXXXXXX

```

# Answer
> 4 votes
# Mathematica, ~~111~~ 91 bytes

```
#~StringReplace~{"o"->"O"~Table~(n=StringLength@#)<>"\n","re"->" "<>Table["R",n-2]<>" \n"}&

```

Try It Online!

This was majorly shortened thanks to Misha's edits.

---

My original code:

```
(z=StringRepeat;n=StringLength@#;#~StringReplace~{"o"->"O"~z~n<>"\n","re"->" "<>If[n>2,z["R",n-2],""]<>" \n"})&

```

This code is not very fancy but it seems too expensive to convert away from strings and then back or to do anything else clever.

In particular, with only 3-4 commands that have the name String, my original approach couldn't save bytes at all by trying to abstract that away. For example, the following is 129 bytes:

```
(w=Symbol["String"<>#]&;z=w@"Repeat";n=w["Length"]@#;#~w@"Replace"~{"o"->"O"~z~n<>"\n","re"->" "<>If[n>2,z["R",n-2],""]<>" \n"})&

```

# Answer
> 4 votes
# Bash, 87 bytes

Without `sed`:

```
f(){ printf %$1s|tr \  $2;}
c=${1//o/`f ${#1} B`
}
echo "${c//re/ `f $[${#1}-2] F`
}"

```

Thanks to @manatwork.

With `sed` (90 bytes):

```
f(){ printf %$1s|tr \  $2;}
echo $1|sed "s/o/`f ${#1} B`\n/g;s/re/ `f $[${#1}-2] F` \n/g"

```

# Answer
> 4 votes
# Ruby, ~~62~~ 60 bytes

```
->s{s.gsub /./,?r=>" #{(?**z=s.size)[0..-3]}
",?o=>?O*z+?\n}

```

Try it online!

Uses `O` for the cookie, `*` for the filling.

-1 thanks to @manatwork pointing out a silly mistake and another -1 due to relaxation of the rules about whitespaces.

# Answer
> 4 votes
# PHP, 96 87 85 bytes

Thanks to @gwaugh -9 Bytes
Thanks to @manatwork -2 Bytes

```
<?=strtr($i=$argv[1],[o=>($r=str_repeat)(X,$l=strlen($i))."
",re=>" {$r(o,$l-2)}
"]);

```

Try it online!

Try it online! (87 Bytes)

Try it online (original 97 bytes submition)!

---

**And a recursive function**

# PHP, 135 bytes

```
function f($w,$x=0){$f=str_repeat;echo($x<($l=strlen($w)))?($w[$x]=='o')?$f(█,$l)."
".f($w,$x+1):" ".$f(░,$l-2)."
".f($w,$x+2):"";}

```

Try it online! (recursive)

# Answer
> 4 votes
# Perl 6, 37 bytes

```
{m:g/o|r/>>.&({S/rr/ /.say}o*x.comb)}

```

Try it online!

Anonymous code block that takes a string and prints the oreo, with `o` as the cookie and `r` as the cream.

### Explanation:

```
{                                   }   # Anonymous code block
 m:g/o|r/                               # Select all o s and r s
         >>.&(                     )    # Map each letter to
                            *x.comb     # The letter padded to the width
               S/rr/ /                  # Substitute a leading rr with a space
                      .say              # And print with a newline

```

# Answer
> 4 votes
# Brainfuck, ~~276~~ ~~268~~ 206 bytes

Technically as the brainfuck only has 8 instructions, that means it needs only 3 bits per character instead of 8 (that also means we could encode brainfuck in base64 with exactly 2 instructions per character), but I'll play fair and say it's 268 bytes long.

It was a fun challenge, thanks!

**Edit**: now featuring the 3rd rule!

**Edit**: moving the line feed from the data pool to the display part of the code allowed me to get down to 268 bytes:

```
>>+<,[<++++++++++[>-----------<-]>-[>-<,>>+<<[-]>>>>[>]>++++[<++++++++>-]+>>++++++++++[<+++++++++++>-]<+>>++++[<++++++++>-]<[<]<<<]>[[-]>>>[>]>+++++++[<+++++>-]+>>+++++++[<+++++>-]>+++++++[<+++++>-]<[<]<<]+<,>>+<<]>>--[>>>+<<<-]>>[.>-[>>>>+<<<<->.<]>>.[-]++++++++++.>]

```

Here's a more readable version:

The data pool is made like so: \[first character, placeholder value used to move the input character count, repeated character, last character\]

```
>>+<,[//start of the loop
<++++++++++[>-----------<-]>-//"o"
[>-<,>>+<<[-]//if it's not a "o", skip one character and:

>>>>[>]//go to the data pool and search for the end
>++++[<++++++++>-]//put " " in memory
+>//put 1 in memory
>++++++++++[<+++++++++++>-]<+>//put a "o" in memory
>++++[<++++++++>-]<//put another " " in memory
[<]<<<//get back to the beginning of the data pool and get back to the program

]>[[-]//else (so if it's a "o"):

>>>[>]//go to the data pool and search for the end
>+++++++[<+++++>-]//put a "#" in memory
+>//put 1 in memory
>+++++++[<+++++>-]//put a "#" in memory
>+++++++[<+++++>-]<//put a "#" in memory
[<]<<//get back to the beginning of the data pool and get back to the program

]+<,>>+<<]//loop until the end of the input line and count the number of characters

>>//go to the number of characters variable
--//substract 2 to it because the first and last characters take one space each
[>>>+<<<-]//copy the value to the next place
>>[.>//start of the loop and display of the first character
-[>>>>+<<<<->.<]//display of the repeated character while copying the character count to the next line
>>.//display of the last character
[-]++++++++++.//display a line feed
>]//loop until the end of the data pool

```

It works on copy.sh/brainfuck with default settings (link)

**Edit**: now down to only 206 Bytes thanks to @RezNesX

```
>>+<,[<-[>++<-------]>-[,[-]>->+>>[>]>+>+>-[<-->-------]>++++[<<<<++++++++>>>++++++++>-]<[<]<<<]>[[-]>>>[>]->+>->->--[<<<<-->>-->-->+++++++]<[<]<<]+>+<<,]>>--[>>>+<<<-]>>[.>-[>>>>+<<<.<-]>>.[-]++++++++++.>]

```

The code is quite similar but a lot of optimisation has been done in the creation of the data pool, very interesting.

# Answer
> 4 votes
# Zsh, 67 bytes

```
a=$#1
o()<<<${(l/a//=/)}
r()<<<\ ${(l/a>1?a-2:0//+/)}
eval ${1///;}

```

Try it online!

Explanation:

* `$1`: input
* `#`: length
* `a=`: assign to global variable `$a`
* `o()`: define a function called `o`:
    + `${(l/a//=/)}`: left pad {nothing} with `=` signs to the width `$a` (i.e., print this many equals signs)
    + `<<<`: print
* `r()`: define a function called `r`:
    + `${(l///+/)}` left pad {nothing} with `+` signs,
    + `a>1?a-2:0`: to the width of `$a - 2` if `$a > 1` else `0` (because otherwise, if `$a - 2` was negative, zsh would use its absolute value)
    + `<<<\` : print with a space before
* `${1}`: input
* `///;`: replace all {empty string}s with `;` (effectively intersperses; `oreo` -\> `;o;r;e;o`)
* `eval`: evaluate that as zsh code
    + `o` and `r` call the functions defined above
    + `e` is a non-existent command, so does nothing
    + `;` separates the commands

# Answer
> 3 votes
# Charcoal, 19 bytes

```
Ｆθ≡ιo⟦⭆θ#⟧e«→Ｐ⁻Ｌθ²↙

```

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

```
Ｆθ

```

Loop through the characters of the input string.

```
≡ι

```

Switch on each character.

```
o⟦⭆θ#⟧

```

If it's an `o` then print the input string replaced with `#`s on its own line.

```
e«→Ｐ⁻Ｌθ²↙

```

If it's an `e` then move right, print a line of `-`s that's two less than the length of the input string, then move down and left.

# Answer
> 3 votes
# C# (Visual C# Interactive Compiler), 71 bytes

```
s=>s.Aggregate("",(a,c)=>a+(c>111?" ":"\n".PadLeft(s.Length+c/5-21,c)))

```

Try it online!

Borrowed some ideas from on Embodiment of Ignorance's answer for sure.

-6 bytes thanks to @ASCIIOnly!

The overall concept is to compute a string aggregate over the input characters following these rules:

* If an `r` is encountered, append a single space  character for indentation. We know the next character will be an `e`.
* If an `o` or an `e` is encountered, generate a string by repeating the current character a specific number of times and prepending it to a newline or some padding and a newline.
* The number of times to repeat is determined by length of input string and whether the current line is indented.
* The `PadLeft` function is used to generate the repeating character string.

The result is the concatenation of all of these strings.

# Answer
> 2 votes
# Dart, ~~120~~ ~~106~~ 107 bytes

```
f(s)=>s.replaceAll('o',''.padRight(s.length,'#')+'\n').replaceAll('re',' '.padRight(s.length-1,'-')+' \n');

```

Try it online!

* +1 byte : Added trailing whitespace

# Answer
> 2 votes
# Python 2, ~~77~~ ~~76~~ 72 bytes

```
lambda i:'\n'.join((x*len(i),' '+x*(len(i)-2))[x>'o']for x in i if'e'<x)

```

Try it online!

The outer part of the cookie is 'o' and the filling is 'r'.

# Answer
> 2 votes
# C# (.NET Core), 143 bytes

Without LINQ.

```
p=>{var q="";foreach(char c in p){if(c!='e'){for(var j=0;j<p.Length;j++)q+=(j<1|j>p.Length-2)&c>'q'?" ":c<'p'?"█":"░";q+="\n";}}return q;};

```

Try it online!

# Answer
> 2 votes
# Clojure, 137 bytes

```
(fn[f](let[w(count f)r #(apply str(repeat % %2))](clojure.string/join"\n"(replace{\o(r w \#)\e(str \ (r(- w 2)\-) \ )}(remove #{\r}f)))))

```

I'm not using the nice characters in the printout in the golfed version since those are expensive. Returns a string to be printed.

Try it online!

See below for explanation.

Pre-golfed:

```
; Backslashes indicate a character literal
(defn oreo [format-str]
  (let [width (count format-str)

        ; A helper function since Clojure doesn't have built-in string multiplication
        str-repeat #(apply str (repeat % %2))

        ; Define the layers
        cookie (str-repeat width \█)
        cream (str \ (str-repeat (- width 2) \░) \ )]

    (->> format-str ; Take the input string,
         (remove #{\r}) ; remove r for simplcity,
         (replace {\o cookie, \e cream}) ; replace the remaining letters with the layers,
         (clojure.string/join "\n")))) ; and join the layers together with newlines

```

# Answer
> 2 votes
# Sed, 89 characters

(86 characters code + 3 characters command line option)

```
h;s/./E/g;H;g;s/\n//;:b;s/(o|re)([ore]+)(E*)/\1\3\n\2\3/;tb;s/o//g;s/reE(E*)E/ \L\1 /g

```

Commented with example for input “oreo”:

```
h        # copy to hold space
s/./E/g  # change into cookie: EEEE
H        # append to hold space
g        # copy back to pattern space: oreo␤EEEE
s/\n//   # remove the newline: oreoEEEE

:b                                 # split the os and res in separate lines
  s/(o|re)([ore]+)(E*)/\1\3\n\2\3/ # repeating the EEEE for each:
tb                                 # oEEEE␤reEEEE␤oEEEE

s/o//g                # remove the os: EEEE␤reEEEE␤EEEE
s/reE(E*)E/ \L\1 /g   # remove the res, cut edge, change fill: EEEE␤ ee ␤EEEE

```

Sample run:

```
bash-4.4$ sed -r 'h;s/./E/g;H;g;s/\n//;:b;s/(o|re)([ore]+)(E*)/\1\3\n\2\3/;tb;s/o//g;s/reE(E*)E/ \L\1 /g' <<< oreoorererereoo
EEEEEEEEEEEEEEE
 eeeeeeeeeeeee
EEEEEEEEEEEEEEE
EEEEEEEEEEEEEEE
 eeeeeeeeeeeee
 eeeeeeeeeeeee
 eeeeeeeeeeeee
 eeeeeeeeeeeee
EEEEEEEEEEEEEEE
EEEEEEEEEEEEEEE

```

Try it online!

# Answer
> 2 votes
# C (gcc), `-D$=putchar(33` \+ 88 = 102 bytes

```
O(char*r){for(char*e,*o=r,x;*r;$-x),$-23))for(x=*r++>111,e=x?$-1),r++,o+1:o;*++e;$+x));}

```

Try it online!

# Answer
> 2 votes
# APL (Dyalog Extended), 22 bytes<sup>SBCS</sup>

Anonymous tacit prefix function. C**o**okies are `o`, c**r**eam is `r`.

```
'^rr'⎕R' '⍤1≢⊢⍤/⍪~'e'⍨

```

Try it online!

swap the input for:

`'e'` this letter

`~` remove all the "e"s from:

the columnised argument

`⊢⍤/` replicate that single column to be as many columns as:

the tally of characters in the input

`⍤1` on each row (lit. on each 1D sub-array):

`'^rr'⎕R' '` PCRE **R**eplace leading "rr" with a single space

# Answer
> 2 votes
# Stax, 13 bytes

```
äNëY┬2-]‼Cv6╤

```

Run and debug it

Uses "o" and "r" characters for the layers.

# Answer
> 2 votes
# Excel, 93 bytes

```
=SUBSTITUTE(SUBSTITUTE(A4,"o",REPT("O",LEN(A4))&"
"),"re"," "&REPT("r",MAX(0,LEN(A4)-2))&"
")

```

`MAX(0,` is needed to handle `o`. Uses `O` and `r`.

# Answer
> 2 votes
# Nibbles 10 bytes

```
&" ",@~.|@%$~
^-,_%$3 # $

```

explanation

```
&           # Justify
  " "       # (value to pad in justify)
  ,         # length (size to justify to)
    @       # first input string
  ~         # centered
  .         # map
    |       # filter
      @     # first input string
      %$~   # mod char element 2
    ^       # replicate (begin map body)
     -      # minus
      ,_    # length of first input string
        %$3 # mod char element 3
            # implicit $ (the char element to be replicated)

```

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), 136 bytes

```
	S =INPUT
	N =SIZE(S)
S	S ('o' | 're') . X REM . S	:F(END)
	OUTPUT =IDENT('o',X) DUPL(X,N)	:S(S)
	OUTPUT =' ' DUPL(0,N - 2) ' '	:(S)
END

```

Try it online!

# Answer
> 1 votes
## Batch, 133 bytes

```
@set/ps=
@set o=%s:r=o%
@set o=%o:e=o%
@set r=%o:o=-%
@set r= %r:~2%
@set s=%s:e= %
@for %%c in (%s:o=o %)do @call echo %%%%c%%

```

Takes input on STDIN. Explanation:

```
@set/ps=

```

Input the string.

```
@set o=%s:r=o%
@set o=%o:e=o%

```

Make a copy of the string with all of the `r`s and `e`s replaced with `o`s.

```
@set r=%o:o=-%
@set r= %r:~2%

```

Make a copy of the string of `o`s, change them to `-`s and replace the first two with a space.

```
@set s=%s:e= %
@for %%c in (%s:o=o %)do @call echo %%%%c%%

```

Change the `e`s into spaces and also add a space after each `o`, allowing the `o`s and `r`s to be iterated over, printing the appropriate string each time.

# Answer
> 1 votes
# CJam, 27 bytes

```
q:T'e-{i2%T,'9*_:)2>S\+?N}/

```

Try it online!

## Explanation:

```
q                            read input:                    | "oreoo"
 :T                          store in variable T            | "oreoo", T="oreoo"
   'e-                       remove all 'e' characters:     | "oroo"
      {                  }/  for each character:            | 'o
       i                       get Unicode value:           | 79
        2%                     modulo 2:                    | 1
          T                    push original input:         | 1 "oreoo"
           ,                   get length:                  | 1 5
            '9*                repeat '9' that many times:  | 1 "99999"
               _               duplicate:                   | 1 "99999" "99999"
                :)             increment every character:   | 1 "99999" ":::::"
                  2>           remove first two characters: | 1 "99999" ":::"
                    S\+        prepend a space:             | 1 "99999" " :::"
                       ?       conditional:                 | "99999"
                        N      add a newline:               | "99999" N
                             (implicit output)              | "99999" N " :::" N "99999" N "99999" N

```

# Answer
> 1 votes
# Lua, 112 bytes

```
s=io.read()for t in s:gmatch"."do io.write(t=="o"and t:rep(#s).."\n"or(t=="r"and" "..t:rep(#s-2).." \n"or""))end

```

---

## Explanation

```
s = io.read() -- Reads the input
for t in s:gmatch(".") do -- For each character in the input, call it 't' and enter the loop
 io.write(t=="o" and t:rep(#s).."\n" or (t=="r" and " "..t:rep(#s-2).." \n" or ""))

          t=="o" and  -- if 't' is equal to "o" then
                     t:rep(#s).."\n"  -- you have to write 't' repeated N times, where N is
                                      -- is the size of the input s, appended by a new line
                                     or (t=="r" and  -- else, if 't' is equal to "r" then
                                                    " "..t:rep(#s-2).." \n"  -- write a space, followed by 't' repeated N-2 times,
                                                                             -- where N is the size of the input.
                                                                             -- followed by a space and a new line.
                                                                            or "" -- else, just don't write anything.

end

```

Try it online!

# Answer
> 1 votes
# JavaScript, 70 bytes

```
x=>x.replace(/()()o|re/g,(_,o=1,s=' ')=>s.padEnd(x.length-o,+o)+s+`
`)

```

Try it online!

Or... If we're allowed to use other characters for whitespace, we can get it down to 65 bytes:

```
x=>x.replace(/()()o|re/g,(_,o=1,s=' ')=>s.padEnd(x.length-o,+o)+s+`
`)

```

Try it online!

...but I don't think that counts.

# Answer
> 1 votes
# JavaScript (Node.js), 65 bytes

```
s=>s[R='replace'](/.e?/g,x=>s[R](/./g,x[0])[R](/^r|r$/g,' ')+`
`)

```

Try it online!

Thanks to Yair Rand, saves 2 bytes.

# Answer
> 1 votes
# x86-64 machine code (Linux), 97 bytes

```
0000000000000000 <oreo_asm>:
   0:   56                      push   %rsi
   1:   57                      push   %rdi

0000000000000002 <len>:
   2:   48 ff c7                inc    %rdi
   5:   80 3f 00                cmpb   $0x0,(%rdi)
   8:   75 f8                   jne    2 <len>
   a:   49 89 fc                mov    %rdi,%r12
   d:   5f                      pop    %rdi
   e:   49 29 fc                sub    %rdi,%r12
  11:   4d 31 f6                xor    %r14,%r14
  14:   eb 18                   jmp    2e <outer_loop.skip>

0000000000000016 <extra>:
  16:   41 c6 01 20             movb   $0x20,(%r9)
  1a:   c6 03 20                movb   $0x20,(%rbx)
  1d:   49 ff ce                dec    %r14
  20:   eb 06                   jmp    28 <outer_loop>

0000000000000022 <newline>:
  22:   c6 06 0a                movb   $0xa,(%rsi)
  25:   48 ff c6                inc    %rsi

0000000000000028 <outer_loop>:
  28:   49 ff c6                inc    %r14
  2b:   48 ff c7                inc    %rdi

000000000000002e <outer_loop.skip>:
  2e:   44 8a 07                mov    (%rdi),%r8b
  31:   41 80 f8 65             cmp    $0x65,%r8b
  35:   74 df                   je     16 <extra>
  37:   45 84 c0                test   %r8b,%r8b
  3a:   74 23                   je     5f <done>
  3c:   48 89 f3                mov    %rsi,%rbx

000000000000003f <inner_loop>:
  3f:   44 88 06                mov    %r8b,(%rsi)
  42:   49 89 f1                mov    %rsi,%r9
  45:   48 ff c6                inc    %rsi
  48:   48 31 d2                xor    %rdx,%rdx
  4b:   48 89 f0                mov    %rsi,%rax
  4e:   48 2b 04 24             sub    (%rsp),%rax
  52:   4c 29 f0                sub    %r14,%rax
  55:   49 f7 f4                div    %r12
  58:   48 85 d2                test   %rdx,%rdx
  5b:   74 c5                   je     22 <newline>
  5d:   eb e0                   jmp    3f <inner_loop>

000000000000005f <done>:
  5f:   5e                      pop    %rsi
  60:   c3                      retq

```

This x86-64 function takes in the pointer to the input string in rsi and builds the output starting at the pointer in rdi (these are the registers used to pass the first two arguments from a C function on Linux). For convenience, I've written a C++ wrapper for this which also does nice input sanitization and prints the output. That code can be located here. This also shows the original nasm syntax assembly I wrote for this function (as well as the non-golfed version I got working first).

A few things to note is that this code doesn't respect any callee saved registers, which means that the C++ code likely will crash if run for a while after calling this function. On my machine it doesn't, but that's rather surprising. I also don't add a null byte to delimit the output string, and instead the space allocated for the output string is pre-filled with bytes. (If this isn't allowed I can add the null terminator at a cost of 3 bytes).

The logic for this code is essentially counting the length of the string, then building a line of this length for each 'o' and 'r' characters seen in the input string, and then for any 'e' character seen, replacing the first and last characters on the previous line with space characters.

~~I can't find anywhere online to compile and run a mix of C++ and nasm source code, so I might write some small wrapper code for this to prove it works.~~ Otherwise you should be able to compile and run this with the makefile in the link I gave with the command:

```
$ make oreo ASM_FILE=oreo_golf.nasm
$ ./oreo oreoorererereoo --use_asm

```

I was able to format the assembly to something acceptable by gcc, so try it online!

# Answer
> 1 votes
# Python 2, ~~70~~ 75 bytes

```
lambda s:"\n".join((c*(len(s)-2*(c<'f'))).center(len(s))for c in s if'r'>c)

```

Try it online!

Uses 'o' for cookie, 'e' for filling. Returns a string.

EDIT: Saved 4 bytes thanks to Jo King.

**Explanation:**

```
# anonymous function, returns a string seperated by line breaks
lambda s:"\n".join(.......................................................)
                                                        # iterate through string, return each non-'r' character
                                                        for c in s if'r'>c
                    # duplicate the character until it is the length of the original string,
                    # minus two characters if the current letter is 'e'
                    c*(len(s)-2*(c<'f'))
                   # pad the string with spaces out to the length of the original string
                   (....................).center(len(s))

```

# Answer
> 1 votes
# Python 2, 64 bytes

```
s=input()
for c in s:
	if'n'<c:j='o'<c;print' '*j+c*(len(s)-2*j)

```

A full program which prints the result.

**Try it online!** Or see the test-suite.

# Answer
> 1 votes
# Tcl, 216 bytes

```
set s [gets stdin]
set l [string map {o { o } re { re }} $s]
set n [string length $s]
foreach i $l {
if {$i eq "o"} {
puts [string repeat █ $n]
} elseif {$i eq "re"} {
puts " [string repeat ░ [expr {$n-2}]] "
}
}

```

Try it online!

# Answer
> 1 votes
# Vyxal `j`, 23 bytes

```
L£\eoƛ\o=[×¥*|ð¥⇩\!*ð++

```

Try it Online!

```
L£                      # Store length to register
  \eo                   # Remove es
     ƛ                  # Map...
      \o=[              # If o then
          ×¥*           # (Register) asterisks
             |          # Else...
               ¥⇩\!*    # (Register-2 !s)
              ð     ð++ # Padded with spaces

```

# Answer
> 1 votes
# Perl 5 \+ `-plF`, 27 bytes

```
s!.!$&x@F.$/!ge;s/r+
ee/ /g
```

Try it online!

## Explanation

`s///`ubstitutes every character (`.`) with itself repeated the length of the string `x@F`, followed by a newline (`$/`). Then replaces any runs of `r+\nee` with a single space.

# Answer
> 1 votes
# Vyxal `j`, 14 bytes

```
\eoƛAd⇩?L+*?L⋏

```

Try it Online!

# Answer
> 1 votes
# APOL, 79 bytes

This could almost certaintly be made shorter.

`v(0 i);j(ƒ(R(⁰ "re" "*") ¿(=(∋ "*") +(" " *("r" -(l(⁰) 2))) *("o" l(⁰)))) "\n")`

## Explanation

```
v(0 i);  Put user's input at memory index 0
j(  List join
  ƒ(  Listbuilder for
    R(  String replace (being iterated through)
      ⁰  Value at index 0
      "re"  Replace "re"
      "*"  with "*"
    )
    ¿(  Returning if (called for each character in replaced string)
      =(  Equals (condition)
        ∋  Current character
        "*"  The string "*"
      )
      +(  Add (true instruction, used here to join strings)
        " "  The string " " (the padding for the filling)
        *(  Multiply (used here to repeat a string)
          "r"  The string "r" (our filling) by
          -(  Subtract
            l(⁰)  The length of the input
            2  from two (one for each character of padding)
          )
        )
      )
      *(  Multiply (the false condition)
        "o"  The string "o"  (our cookie)
        l(⁰)  by the length of the input
      )
    )
  )
  "\n"  Join each string with a newline
)

```

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


title: Number of complete rhyme schemes

text:
# Question
Title: Number of complete rhyme schemes
A rhyme scheme is the pattern of rhymes at the end of the lines in a poem. They are typically represented using letters, like `ABAB`. We consider two rhyme schemes identical if they are isomorphs, and therefore only report the lexicographically earliest. Equivalently, rhyme schemes are simply strings in standard order. The rhyme schemes of length 4 are:

```
AAAA, AAAB, AABA, AABB, AABC, ABAA, ABAB, ABAC, ABBA, ABBB, ABBC, ABCA, ABCB, ABCC, ABCD

```

A *complete* rhyme scheme is one where every line rhymes with at least one other line; that is, every letter in the string appears more than once. For length 4, these are:

```
AAAA, AABB, ABAB, ABBA

```

Now consider the sequence of the number of complete rhyme schemes for any length. With length `0`, `2`, or `3`, there is exactly one way to do this (, `AA`, and `AAA` respectively), and length `1` has no ways. As we see, length 4 gives `4` ways. The first 30 terms of this sequence are:

```
1, 0, 1, 1, 4, 11, 41, 162, 715, 3425, 17722, 98253, 580317, 3633280, 24011157, 166888165, 1216070380, 9264071767, 73600798037, 608476008122, 5224266196935, 46499892038437, 428369924118314, 4078345814329009, 40073660040755337, 405885209254049952, 4232705122975949401, 45398541400642806873, 500318506535417182516, 5660220898064517469939

```

This is A000296 in the OEIS. It is also the number of ways to partition a set into subsets of a size of at least 2.

Your task is to output this sequence.

The sequence should not be limited by the 26 letters in the alphabet; the letters can be abstracted such that the sequence continues infinitely. The complete rhyme schemes which use the digits `1`-`9` is OEIS A273978.

## Rules

* As with standard challenges, you may choose to either:
    + Take an input `n` and output the `n`th term of the sequence
    + Take an input `n`and output the first `n` terms
    + Output the sequence indefinitely, e.g. using a generator
* You may use 0- or 1-indexing
* You may use any standard I/O method
* Standard loopholes are forbidden
* This is , so the shortest code in bytes wins

# Answer
# Haskell, 48 bytes

```
(%1)
0%_=1
n%i|i<n=(i-1)%1+(n-i)/i*n%(i+1)|1>0=0

```

Try it online!

Uses this recursion I found:

$$ f(n)=g(n,1), $$ where $$ \begin{eqnarray} g(0,i) &=& 0\nonumber \\ g(n,i) &=& g(i-1,1) +\frac{n-i}{i} g(n,i+1) \text{, if } i\< n \nonumber \\ g(n,i) &=& 0 \text{, otherwise} \end{eqnarray} $$

**45 bytes**

```
(%0)
0%_=1
n%i|i>n-2=0|j<-i+1=i%0+(n-j)/j*n%j

```

Try it online!

**47 bytes**

```
(%1)
0%_=1
n%i=sum[(i-1)%1+(n-i)/i*n%(i+1)|i<n]

```

Try it online!

**45 bytes**

```
f n=foldr(\j x->f(j-1)+n/j*x-x)(0**n)[1..n-1]

```

Try it online!

Some float inaccuracies show up.
> 9 votes

# Answer
# Jelly, 13 bytes

```
1IS;ƊÄ$¡IIS+¬

```

Try it online!

```
1IS;ƊÄ$¡IIS+¬
1     $¡        Starting from [1], iterate an operation n times:

 IS               Sum the increments (i.e. last minus first),
   ;Ɗ             prepend this to the array,
     Ä            and take the cumulative sum.
                  e.g. [a,b,c,d] → [d-a, d, d+b, d+b+c, d+b+c+d]

        IIS     Increments, increments, sum.
           +¬   This erroneously gives a(0)=0, so add 1 if n=0.

```

This is a port of the Maple code contributed to the OEIS page by Peter Luschny. As far as I understand, it's similar to Neil's answer, but modifies Aitken's array to get the result directly.
> 6 votes

# Answer
# MATL, 23 bytes

```
:Y@!"@Y>@=f@d0<fX=]N~vs

```

Input is 0-indexed. Try it at **MATL Online**!

### Explanation

This uses the following characterization from OEIS:

*a*(*n*) is the number of permutations of \[1, 2, ..., *n*\] for which the positions of the left-to-right maxima coincide with the positions of entries that are followed by a smaller number.

```
:       % Implicit input: n. Range [1 2 ... n]
Y@      % All permutations. Gives a matrix where each permutation is a row
!       % Transpose. Now each permutation is a column
"       % For each column
  @Y>   %   Cumulative maximum of the column
  @=    %   Compare each entry with that of the column
  f     %   Indices of true entries, i.e. of left-to-right maxima (*)
  @d    %   consecutive differences of the column
  0<    %   True for negative values
  f     %   Indices of true entries, i.e. of descents (**)
  X=    %   Are (*) and (**) equal? Gives true or false
]       % End
N~      % Number of terms in the stack, negated. Gives 1 for n=0
v       % Concatenate all values into a column vector
s       % Sum. Implicit display

```
> 5 votes

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

*Avoid another loop variable saves ~~7~~ 8 bytes as suggested by att.*

```
f=(n,i=n)=>i?--i&&f(n,i)*i/(n-i)+f(n+~i):1

```

Try it online!

$$ f(x) = \sum\_{i=1}^{x-1} \binom{x-1}{i}\cdot f(x-1-i) $$

with special

$$ f(0) = 1 $$

For complete rhyme patterns with length n:

1. The first rhyme is `A` by definition
2. We choose `i` rhymes after it and fill it by `A`; 1 \< i \< n-1
3. For unfilled cells, it become a recursive question
4. So we count `f(n-1-i)*combination(n-1,i)` rhyme patterns.
> 5 votes

# Answer
# Wolfram Language (Mathematica), 27 bytes

```
Nest[#'&,E^(E^#-1-#)&,#]@0&

```

Try it online!

Uses the exponential generating function given on OEIS:

> E.g.f.: exp(exp(x) - 1 - x).

---

**alternative 27 bytes:**

```
D[E^(E^x-1-x),{x,#}]/.x->0&

```

Try it online!
> 4 votes

# Answer
# JavaScript (ES7), 90 bytes

Outputs the \\$n\\$-th term, 0-indexed.

```
f=(n,k=n)=>~k&&(h=j=>~j&&(F=n=>n?F(n-1)/n:1)(j)*F(k-j)*(-1)**j--*(-j)**n+h(j))(k)-f(n,k-1)

```

Try it online!

There's a floating-point rounding error for \\$a(3)\\$.

### How?

This is based on the following formula from A000296:

$$a(n)=\sum\_{k=0}^n{(-1)^{n-k}\times\sum\_{j=0}^k\left((-1)^j\times\binom{k}{j}\times (1-j)^n\right)/k!}$$

which can be turned into:

$$a(n)=\sum\_{k=0}^n{(-1)^{n-k}\times\sum\_{j=0}^k(-1)^j\times (1-j)^n/j!/(k-j)!}$$
> 3 votes

# Answer
# Python 3, ~~78~~ 74 bytes

Port of a Maxima function found in the *prog* section on OEIS.

-4 bytes thanks to xnor!

```
from math import*
f=lambda n:sum(comb(n-1,i)*f(i)for i in range(n-1))+0**n

```

Try it online!

Same length with more recursion:

```
f=lambda n,i=0:(n-i>1and comb(n-1,i)*f(i)+f(n,i+1))+0**n
f=lambda n,i=0:~i+n and(n<1or comb(n-1,i)*f(i)+f(n,i+1))

```
> 3 votes

# Answer
# Charcoal, 28 bytes

```
≔¹η⊞υ¹ＦＮ«≦⁻⌊υη⊞υ⌈υＵＭυΣ✂υλ»Ｉη

```

Try it online! Link is to verbose version of code. 0-indexed, obviously, given that this is the number of complete rhyme schemes for a given length, so the input should be the length. Explanation:

```
≔¹η

```

Start with `1` complete rhyme scheme for a length of `0`.

```
⊞υ¹

```

Start computing Bell numbers (A000110).

```
ＦＮ«

```

Loop length times.

```
≦⁻⌊υη

```

Subtract the current result from the current Bell number.

```
⊞υ⌈υＵＭυΣ✂υλ

```

Compute the next row of Aitken's array to obtain the next Bell number. (Actually computes the row reversed because it's golfier.)

```
»Ｉη

```

Output the final number of complete rhyme schemes.
> 3 votes

# Answer
# x86 32-bit machine code, ~~29~~ 28 bytes

```
31 c0 99 e2 09 c3 52 e8 f6 ff ff ff 5a 59 42 51 f3 0f b8 ca 3b 0c 24 7c ed 59 40 c3

```

Try it online!

Following the `fastcall` calling convention, this takes the 0-indexed `n` in ECX and returns the `n`th value in EAX.

-1 with some rearrangement and changes.

Assembly:

```
.intel_syntax noprefix
.global f
f:
    xor eax, eax    # Set EAX to 0.
recursion:      # Starting here will add the value to EAX instead of replacing it.
    cdq             # Set EDX to 0 (as long as EAX hasn't overflowed).
    loop enterloop  # Calculate n-1 and jump if that's not 0 (n≠1).
    ret             # Return with 0 for n=1.

repeat:
    push edx        # Push EDX onto the stack.
    call recursion  # Recursive call, using the number of different positions.
    pop edx         # Restore EDX from the stack.
    pop ecx         # Restore ECX from the stack.
enterloop:      # EDX will be a bitmask of positions different from the last.
    inc edx         # Add 1 to EDX.
    push ecx        # Push ECX (n-1) onto the stack.
    popcnt ecx, edx # Count the different positions, into ECX.
    cmp ecx, [esp]  # Compare that with the value of n-1 on top of the stack.
    jl repeat       # Continue the loop if fewer than n-1 different positions.
    pop ecx         # (Otherwise: all n-1 positions, or n=0) Take n-1 off the stack.
    inc eax         # Count 1 for the all-the-same rhyme scheme.
    ret             # Return.

```
> 3 votes

# Answer
# Pari/GP, 38 bytes

```
n->n!*Vec(exp(exp(x+O(x^n++))-1-x))[n]

```

Try it online!
> 2 votes

# Answer
# Python 3.8, 128 bytes

```
lambda n:round(sum((-1)**(n-k)*sum((-1)**j*comb(k,j)*(1-j)**n/perm(k)for j in range(k+1))for k in range(n+1)))
from math import*

```

Try it online!

Uses the same formula (unchanged) from A000296 that Arnauld uses in his JavaScript answer.
> 1 votes

# Answer
# 05AB1E, 14 bytes

```
1=λD¥OšηOD¥¥O,

```

Port of *@Lynn*'s Jelly answer, but outputs the infinite sequence newline-delimited instead.

Try it online.

**Explanation:**

```
1              # Push 1
 =             # Print it with trailing newline (without popping)
               # (workaround for edge case a(0)=1)
  λ            # Start the recursive environment,
               # to output the infinite sequence
               # Starting with the a(0)=1 we've pushed
               #  (implicitly push the value of a(n-1))
   D           #  Duplicate this a(n-1)
    ¥          #  Pop and push a list of its forward differences
     O         #  Sum those
      š        #  Prepend it in front of the list
       η       #  Pop and push a list of its prefixes
        O      #  Sum those as well
         D     #  Duplicate it (which will be the result of this a(n))
          ¥    #  Pop and push a list of its forward differences
           ¥   #  Do it again
            O  #  Sum those
             , #  Pop and print it with trailing newline

```
> 1 votes

# Answer
# Vyxal, 15 bytes

```
1w?(:¯∑p¦)¯¯∑1⟑

```

Try it Online!

A messy port of Lynn's answer, go upvote that!
> 0 votes

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


title: Find the longest line

text:
# Question
Title: Find the longest line
Given a string containing only the characters `-`, `|`, `+` and newline determine the longest straight line contained in it. A straight line is either an uninterupted run of `-`s and `+`s in a single row or an uninterupted run of `|`s and `+`s in a single column.

So for example:

```
    |
    |  ----
    |
  --+--
    |
    |

```

There are 3 lines here one vertical, two horizontal, with the vertical line being the longest since it is 6 characters.

Your challenge is to write a program or function which takes a string as input and gives the length of the longest line.

You may assume that the input is perfectly rectangular. That is that every row has the same number of characters. You may also assume that the input contains at least 1 of the non-whitespace characters (`-`, `|`, and `+`).

This is , answers will be scored in bytes with fewer bytes being the goal.

## Test cases

```
    |
    |  ----
    |
  --+--
    |
    |

```

6

```

    +

```

1

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

```

4

```
-
-|||||
-

```

1

```
   |
   |

+----+

```

6

```
 |+-
-+|

```

2

```
   |
   |
   |
   |  +
      |
   |  |
   |
   |  |

+-+

```

4

# Answer
> 10 votes
# Jelly, ~~19~~ ~~13~~ 12 bytes

```
OZ%3;ƲḂŒgẎ§Ṁ

```

Try it online!

Takes input as a list of lines/a character matrix

~~First attempt, can probably be improved by a lot.~~ Ports wasif's Vyxal answer for the conversion to `1`/`0` matrices, so make sure you drop them an upvote as well.

-1 byte thanks to Jonathan Allan!

## How it works

```
OZ%3;ƲḂŒgẎ§Ṁ - Main link. Takes a matrix M on the left
O            - Convert each character to an ordinal
     Ʋ       - Last 4 links as a monad f(ord(M)):
 Z           -   Transpose
  %3         -   Mod by 3 (|,+ -> 1, space -> 2, - -> 0)
    ;        -   Concatenate to ord(M)
      Ḃ      - Mod each 2 (1 -> 1, 45, 43 -> 1, 32, 124, 2, 0 -> 0)
       Œg    - Over each list, group adjacent equal elements
         Ẏ   - Drop into a list of lists
          §  - Sums of each (lists of 0 -> 0, lists of 1 -> length)
           Ṁ - Maximum

```

# Answer
> 9 votes
# 05AB1E, 9 bytes

```
ø3%«É€γOZ

```

Try it online!

-2 thanks to @ovs

Takes charcode matrix

This takes inspiration from Arnauld answer:

* Modulo input matrix by 2 (Or is odd number) to get horizontal lines. (Run of 1)
* Take the input matrix again and transpose (to get the columns) then Modulo by 3 are odd numbers? (Vertical runs)
* Pair them, for each
* Group consecutive equals
* Sum them up
* Take the maximum

And that's the result

# Answer
> 8 votes
# JavaScript (ES10), 88 bytes

Expects a matrix of ASCII codes.

```
m=>Math.max(...m.map(r=>r.map(H=(v,x)=>[m.map(V=r=>V=r[x]%3%2*-~V),H=v%2*-~H])).flat(3))

```

Try it online!

### How?

Given an ASCII code \\$v\\$, we use \\$v\bmod 2\\$ and \\$(v\bmod 3)\bmod 2\\$ to identify horizontal and vertical characters respectively.

```
 char. | code | % 2 | % 3 % 2
-------+------+-----+---------
  ' '  |  32  |  0  |    0
  '+'  |  43  |  1  |    1
  '-'  |  45  |  1  |    0
  '|'  | 124  |  0  |    1

```

### Commented

```
m =>                       // m[] = input matrix
Math.max(...               // return the maximum of all values
  m.map(r =>               //   for each row r[] in m[]:
    r.map(H =              //     initialize H to a non-numeric value
    (v, x) =>              //     for each value v at position x in r[]:
      [ m.map(V =          //       initialize V to a non-numeric value
        r =>               //       for each row r[] in m[]:
          V = r[x] % 3 % 2 //         increment V if r[x] is '|' or '+'
              * -~V        //         otherwise, clear V
        ),                 //       end of map()
        H = v % 2          //       increment H if v is '-' or '+'
            * -~H          //       otherwise, clear H
      ]                    //
    )                      //     end of map()
  )                        //   end of map()
  .flat(3)                 //   deep flatten
)                          // end of Math.max()

```

# Answer
> 7 votes
# Dyalog APL, ~~31~~ 27 bytes

```
{≢⍉↑↑⊆⍨¨(↓⍵∊'-+'),↓⍉⍵∊'|+'}

```

-4 thanks to ovs.

Try it online!

Expects a matrix of characters.

```
          ⍵∊'-+'            Turn - and + into 1s and other characters into 0s
         ↓                  and split the matrix into individual rows.
                    ⍵∊'|+'  Take the original matrix, turn | and + into 1s,
                   ⍉        transpose it,
                  ↓         and again split it into rows.
                 ,          Join the rows together.
     ⊆⍨¨                    Extract streaks of 1s for each row.
   ↑↑                       Reduce the level of nesting twice to obtain a
                            3-dimensional array where the 1-streaks, padded
                            with 0s at the end, lie along the last dimension.
 ≢⍉                         Finally, get the length of this dimension,
                            i.e., the length of the longest 1-streak.

```

# Answer
> 5 votes
# 05AB1E, ~~17~~ 16 bytes

```
…-+|ü2Iδå`ø«€γOà

```

Input as a matrix of characters.

Port of *@cairdCoinheringaahing*'s Jelly answer, so make sure to upvote him as well.

Try it online or verify all test cases.

**Explanation:**

```
…-+|              # Push string "-+|"
    ü2            # Create overlapping pairs of this string: ["-+","+|"]
       δ          # Map over this pair of strings:
      I å         #  Check for each character in the input-matrix if it's in this string
         `        # After the map: pop and push both matrices separated to the stack
          ø       # Zip/transpose the top one; swapping rows/columns
           «      # Merge the lists together
            €γ    # Split each inner list into groups of the same digits
              O   # Sum each inner-most list
               à  # And take the flattened maximum of these sums
                  # (after which it is output implicitly as result)

```

# Answer
> 4 votes
# Java (JDK), ~~192~~ ~~175~~ ~~169~~ 167 bytes

```
n->{int i,r,l=0,b,h[]=new int[n[0].length];for(var a:n)for(r=i=0;i<a.length;i++){l=(r=(b=a[i])==45|b==43?r+1:0)>l?r:l;l=(h[i]=b>45|b==43?h[i]+1:0)>l?h[i]:l;}return l;}

```

Try it online!

-6 thanks to Kevin Cruijssen; -2 thanks to Celingcat!

# Answer
> 4 votes
# , ~~87~~ 86 bytes

Or **\>=4.1, 72 bytes** by replacing two `function` appearances with `\`s.

*-1 byte thanks to @Dominic van Essen.*

```
function(s,b=function(x,r=rle(x))max(r$l[r$v==1]))max(apply(s%%2,1,b),apply(s%%3,2,b))

```

Try it online!

That turned out shorter than I expected.

Takes input as matrix of character codes.

### Explanation

```
function(s,     # function takes s as input
 b=function(x,  # helper function for rows/columns
  r=rle(x))     # compute run length encoding
   max(         # get maximum
    r$l[r$v==1] # of run lengths where value is one
   ))
max(            # maximum of
 apply(         # apply to
  s%%2,         # the matrix with ones for | and +
  1,b),         # the helper function along columns
 apply(         # apply to
  s%%3,         # the matrix with ones for - and +
  2,b)          # the helper function along rows
)

```

# Answer
> 4 votes
# GolfScript, 52 bytes

```
n/.zip]"-":a;{{{.a"+"+\?-1>*}%"ø"%{,}/}/"|":a;}%$-1=

```

Try it online!

Explanation:

```
n/.             split input on newline
  .zip          duplicate and zip(transpose rows and columns) the copy
      ]         put them in an array
"-":a; has "-"  for first copy and "|" for the zipped copy
{               map over the copies of input
 {              for each line
  {             map over each char
   .a"+"+\?-1>* returns char if == a ("-" or "|") or "+", otherwise 0
  }%
  "ø"%          splits on ø(null char, "\x00") to get array of lines
  {,}/          for each, get length
 }/
 "|":a;         sets a to "|" for the next copy
}%
                left with array of line lengths
$-1=            sort and get last element, aka get max

                implicit print

```

There is probably some completely different approach that is smaller, but I am pretty happy with how small I got this.

The difference between `{...}~`(map) and `{...}/`(for each) is that map returns an array, while for each dumps them on the stack, essentially `{...}~~`. Rearranging and using `/` allowed me to save a few chars I didn't think I could, so that's pretty cool.

The code has a literal null char that stackoverflow isn't liking, so I replaced it with `ø`. The tio.run link should work.

# Answer
> 3 votes
# Python 3, ~~114~~ 109 bytes

*-5 bytes thanx to Alex Waygood*

```
lambda i,j=''.join:max(map(len,g('[-+]+',i)+g('[|+]+',j(map(j,zip(*i.split('\n')))))))
import re
g=re.findall

```

Try it online!

# Answer
> 3 votes
# C++ (gcc), 124 bytes

```
int f(char*a){char*b=a,*c=a,l=0,h=0;for(;*a;++a)*a%2?l=l>++h?l:h:h=0,*a>10?*a%5>2?*a=0,l=l>++*c?l:*c:*c=0,++c:c=b;return l;}

```

Try it online!

This is my first time submitting a code here, so I'm open to any improvements. I don't think I used anything past `C++98`. The function takes a C-string as input and modifies it.

### Explanation

```
int f(char* a) {              // Take a C-string as input
  char* b = a;                // Preserve a pointer to the beginning
  char* c = a;                // Use the first row of a to keep track of
                              // vertical line lengths; this is tracked by c.
  char l = 0;                 // Maximal line length
  char h = 0;                 // Current horizontal line length

  for (; *a; ++a) {           // *a may be '\0' (0), '\n' (10), ' ' (32),
                              // '+' (43), '-' (45), or '|' (124).
    if (*a % 2) {             // Current character is '+' (43) or '-' (45)
      ++h;                    // Increment current horizontal line length
      l = l > h ? l : h;      // Update maximal line length
    }
    else {
      h = 0;                  // Reset horizontal line length
    }

    if (*a != 10) {
      if (*a % 5 > 2) {       // Current character is '+' (43) or '|' (124)
        *a = 0;               // Set current character to 0 (only needed
                              // for the first row)
        ++*c;                 // Increment current column's vertical line
                              // length
        l = l > *c ? l : *c;  // Update maximal line length
      }
      else {
        *c = 0;               // Reset current column's vertical line length
      }
      ++c;
    }
    else {                    // Current character is '\n' (10)
      c = b;                  // Reset column tracker
    }
  }
  return l;
}

```

# Answer
> 3 votes
# Retina, 74 bytes

```
Lw$`([-+]+)|[|+]((?<=(.)*.).*¶(?<-3>.)*(?(3)^)[|+])*
$1¶_$#2*
%C`.
N^`
0G`

```

Try it online! Explanation:

```
Lw`([-+]+)|[|+]((?<=(.)*.).*¶(?<-3>.)*(?(3)^)[|+])*

```

List all overlapping matches of either horizontal or vertical lines. A .NET balancing group is used to ensure that all of the characters in the vertical line are in the same column. All overlapping matches are needed to ensure that all possible lines are detected, as simple overlaps would only detect the horizontal line of an upside-down `L` shape.

```
L$`
$1¶_$#2*

```

For each match list the horizontal line and a string of underscores of the length of the vertical line. (There is always at least one underscore even when there was no vertical match but the horizontal match is always at least length `1` in this case anyway.)

```
%C`.

```

Count the number of characters in each line.

```
N^`

```

Sort in descending order.

```
0G`

```

Take the maximum.

# Answer
> 3 votes
## Nibbles, 12 bytes

```
`/+.:$`'!$ 3%.%~$%$~,$]

```

That's 23 nibbles which are encoded in 0.5 bytes each. Nibbles isn't on TIO yet.

Translation:

```
`/        special fold
  +       concat
   .      map \a ->
    :     concat
     $    input
     `'   transpose
       !  special zip
        $ input
        3
        % mod
    . map \b ->
     %~   split by \c ->
       $  a
       %  mod
        $ c
        ~ 2
     ,$   length b
 ]        max

```

Usage: pass the input in via the command line as a list of strings. You could use stdin instead but then instead of a $ you'd need ;;@ for the stdin as lines.

```
nibbles longestline.nbl "[\"-+ \",\" | ]\"]"

```

This is inspired by the 05ab1e solution, although surprisingly longer.

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

```
∷¹ǒ∷ÞT"ƛ0ZfĠv∑

```

Try it Online!

-7 thanks to @AaronMiller and @emanresuA

# Answer
> 2 votes
# Pip, 26 bytes

```
MX#*:(J*ZgR'-sALgR'|s)Jn^w

```

Try it online! (Uses the `-r` flag to take input as lines of stdin, but would also work without the flag if input lines were given as command-line arguments.)

### Explanation

```
MX#*:(J*ZgR'-sALgR'|s)Jn^w
                            g is lines of input; s is space; n is newline; w is
                            regex matching runs of whitespace (implicit)
         gR'-s              In g, replace all hyphens with spaces
        Z                   Zip (transpose rows for columns)
      J*                    Join each column into a string
              AL            To the list of columns, append this list:
                gR'|s       In g, replace all pipes with spaces
     (               )Jn    Join the resulting list on newlines
                        ^w  Split on runs of whitespace
  #*:                       Get the length of each run of non-whitespace characters
MX                          Take the maximum

```

# Answer
> 1 votes
# Ruby, 103 bytes

```
->m{eval"(m#{e=".map{|x|x+[' ']}.join.gsub('"}|',' ')+m.transpose#{e}-',' ')).split.map(&:length).max"}

```

Try it online!

* takes a 2d array as input.

We use eval to repeat `e` two times by interpolation.
`e`= adds a column of spaces, joins and calls gsub..
to swap `|` or `-` with a space, we do it on both input and input transposed.
Then we split to get our desired chunks of lines and we get the max length

# Answer
> 1 votes
# Perl 5, 94 bytes

```
sub{$s=$_=pop;max((map y///c,/[-+]+/g),map{map$c=/[|+]/?$c+1:0,$s=~/^.{0,$_}(.?)/mg}0..y///c)}

```

Try it online!

# Answer
> 1 votes
## Wolfram, 98 bytes

```
Max[Length/@Flatten[Map[r|->SequenceCases[r,{#2..}],#]&@@@{{#,"-"|"+"},{Transpose@#,"|"|"+"}},2]]&

```

Explanation

```
Max[                                                    Max of
  Length /@ Flatten[                                    Length of
    Map[r |->                                             For each row
        SequenceCases[r, {#2 ..}], #] &                     Sequences of
     @@@ {{#, "-" | "+"}, {Transpose@#, "|" | "+"}},          - or + in the input
                                                              | or + in the transpose of the input
    2]] &

```

# Answer
> 1 votes
# Charcoal, 35 bytes

```
ＷＳ⊞υιＩＬ⌈⁺Ｅυ⌈⪪⭆ι№-+λ0Ｅ§υ⁰⌈⪪⭆υ№|+§λκ0

```

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

```
ＷＳ⊞υι

```

Input the strings into an array.

```
ＩＬ⌈⁺

```

Output the length of the maximum line in either of the following:

```
Ｅυ⌈⪪⭆ι№-+λ0

```

For each string in the array, replace each character with `1` if it is `-` or `+` otherwise `0`, then split the result on `0`s and take the maximum string of `1`s. This results in a list of strings that have the lengths of the longest line in each row.

```
Ｅ§υ⁰⌈⪪⭆υ№|+§λκ0

```

For each column, build up a string of `1`s and `0`s corresponding to whether each character is `|` or `+` or not, then split on `0`s and take the maximum again, resulting in a list of strings that have the lengths of the longest line in each column.

# Answer
> 1 votes
# Scala, 92 bytes

```
l=>(l.flatMap(_ split "[ |]")++l.transpose.flatMap(_.mkString split "[ -]")).map(_.size).max

```

Try it in Scastie!

Takes a `Seq[String]`.

## Slightly longer solution, 94 bytes

```
l=>(for((m,c)<-Seq(l->"[ |]",l.transpose->"[ -]");r<-m;p<-r.mkString split c)yield p.size).max

```

Try it in Scastie!

Takes input as a `Seq[Seq[Char]]`.

# Answer
> 0 votes
# Japt `-h`, 19 bytes

```
"-|"¬c@zY ôkXi+ÃmÊn

```

Try it

```
"-|"¬c@zY ôkXi+ÃmÊn     :Implicit input of string U
"-|"¬                   :Split "-|" into an array of characters
     c                  :Flat map
      @                 :By passing each X at 0-based index Y through the following function
       zY               :  Rotate U 90 degrees Y times
          ô             :  Split at characters that return truthy (non-empty string)
           k            :  When the following characters are removed
            Xi+         :    "+" prepended to X
               Ã        :End map
                m       :Map
                 Ê      :  Length
                  n     :Sort
                        :Implicit output of last element

```

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


title: Print cos(2π/17) exactly

text:
# Question
Title: Print cos(2π/17) exactly
One way to construct a regular heptadecagon starts with drawing a horizontal line of length `1` from the center to a vertex. Then the distance along that line from the center to the second vertex is `cos(2π/17)`. All other vertices are easy to get.

The goal of this challenge is to print (or produce in any other conventional way) an ASCII math expression involving the operations `+`, `-`, `*`, `/`, `sqrt()` and the natural numbers, which gives `cos(2π/17)` when evaluated. The power operator is not allowed: e.g. `sqrt(17)` cannot be written as `17^(1/2)`.

For example (formula taken from Wikipedia):

```
1/16*(
    -1+
    sqrt(17)+
    sqrt(34-2*sqrt(17))+
    2*sqrt(
        17+
        3*sqrt(17)-
        sqrt(34-2*sqrt(17))-
        2*sqrt(34+2*sqrt(17))
    )
)

```

Whitespace doesn't matter. The length and complexity of the expression doesn't matter, as long as it's syntactically correct (as defined above) and numerically equivalent to `cos(2π/17)`.

Built-in functions are allowed.

# Answer
## CJam (60 bytes)

```
1-4{"(- +sqrt( * -4*
))/2"S/@a*N/\a*}:F~'-\+WF'-\+W-4FWFF'/2

```

Online demo

Output (with added newlines to avoid wrapping):

```
(--(--(-1+sqrt(1*1-4*-4))/2+sqrt(-(-1+sqrt(1*1-4*-4))/2*-(-1+sqrt(1*1-4*-4))/2-4*-1)
)/2+sqrt(-(--(-1+sqrt(1*1-4*-4))/2+sqrt(-(-1+sqrt(1*1-4*-4))/2*-(-1+sqrt(1*1-4*-4))/
2-4*-1))/2*-(--(-1+sqrt(1*1-4*-4))/2+sqrt(-(-1+sqrt(1*1-4*-4))/2*-(-1+sqrt(1*1-4*-4)
)/2-4*-1))/2-4*(-(--1+sqrt(-1*-1-4*-4))/2+sqrt((--1+sqrt(-1*-1-4*-4))/2*(--1+sqrt(-1
*-1-4*-4))/2-4*-1))/2))/2/2

```

I suspect this is the kind of answer OP was secretly hoping for. Rather than apply general-purpose compression to a string, it uses the field structure which Gauss first exploited to present this value in surds, in his *Disquisitiones Arithmeticae*.

I worked from this presentation (pages 18 and 19) but adapted it slightly in order to only ever require the positive root of a quadratic. Unrolled and in pseudo-code, the expression breaks down as

```
# Positive root of x^2 + bx + c = 0
F(b, c) = (-b + sqrt(b*b - 4*c))/2
# (8,1)
p = F(1, -4)
# (4,1)
q = F(-p, -1)
# -(8,3)
r = F(-1, -4)
# (4,3)
s = F(r, -1)
# Result
F(-q, s)/2

```
> 14 votes

# Answer
# JavaScript (ES6), 93

**Edit** 1 byte saved thx @ETHproductions

An anonymous function.

```
x=>"(19)+8-29))+29+39)-8-29))-2*8+29)))-1)/16".replace(/8|9/g,n=>["sqrt(34","*sqrt(17"][n-8])

```

Output:

```
(1*sqrt(17)+sqrt(34-2*sqrt(17))+2*sqrt(17+3*sqrt(17)-sqrt(34-2*sqrt(17))-2*sqrt(34+2*sqrt(17)))-1)/16

```

**TEST**

```
F=x=>"(19)+8-29))+29+39)-8-29))-2*8+29)))-1)/16".replace(/8|9/g,n=>["sqrt(34","*sqrt(17"][n-8])

// Math check

k=Math.cos(Math.PI*2/17)
x=F()

v=eval(x.replace(/sqrt/g,"Math.sqrt"))

O.textContent=k+' (Math.cos(Math.PI*2/17))\n'+v+' ('+x+')\n'+(v==k)
```

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

# Answer
# Mathematica, 26 bytes

```
FunctionExpand@Cos[2Pi/17]

```

**Output**

```
1/(4 Sqrt[2/(15+Sqrt[17]-Sqrt[2 (17-Sqrt[17])]+Sqrt[2 (34+6 Sqrt[17]+Sqrt[2 (17-Sqrt[17])]-Sqrt[34 (17-Sqrt[17])]+8 Sqrt[2 (17+Sqrt[17])])])])

```

---

**Alternative form**

```
CForm@FunctionExpand@Cos[2Pi/17]

```

gives

```
1/(4.*Sqrt(2/(15 + Sqrt(17) - Sqrt(2*(17 - Sqrt(17))) + Sqrt(2*(34 + 6*Sqrt(17) + Sqrt(2*(17 - Sqrt(17))) - Sqrt(34*(17 - Sqrt(17))) + 8*Sqrt(2*(17 + Sqrt(17))))))))

```
> 4 votes

# Answer
# Bubblegum, 50 bytes

Hex dump:

```
78 DA D3 28 2E 2C 2A D1 30 34
D7 D4 06 33 8C 4D 74 61 02 5A
46 50 31 43 73 6D B8 98 B1 2E
16 65 30 31 6D 24 31 30 D2 35
D4 D4 37 34 03 00 AC BC 1B 67

```

Contains a pesky null byte, so you can’t try it online, but it prints this string:

```
(sqrt(17)+sqrt(34-sqrt(17)*2)+sqrt(17+sqrt(17)*3-sqrt(34-sqrt(17)*2)-sqrt(34+sqrt(17)*2)*2)*2-1)/16

```
> 3 votes

# Answer
# Bubblegum, 39 bytes

```
0000000: d3 35 d4 37 34 d3 2e 2e 2c 2a d1 30 34 d7 84 b3  .5.74...,*.04...
0000010: 75 8d b4 60 62 da c6 26 98 e2 a8 d2 ba 58 f4 00  u..`b..&.....X..
0000020: 31 82 0b 32 da 02 00                             1..2...

```

Try it online!

### Verification

```
$ base64 -d > exact-cos.bg <<< 0zXUNzTTLi4sKtEwNNeEs3WNtGBi2sYmmOKo0rpY9AAxggsy2gIA
$ wc -c exact-cos.bg
39 exact-cos.bg
$ bubblegum exact-cos.bg; echo
-1/16+sqrt(17)/16+sqrt(-2*sqrt(17)+34)/16+sqrt(-2*sqrt(2*sqrt(17)+34)-sqrt(-2*sqrt(17)+34)+3*sqrt(17)+17)/8
$ cat verify-cos
#!/usr/bin/python3

from sympy import *

print(Eq(S(input()), cos(2*pi/17)))
$ bubblegum exact-cos.bg | ./verify-cos
True

```
> 3 votes

# Answer
# Vyxal, 37 bytes

```
17√:£‹34¥d-√:→+¥T17+←-34¥d+√d-√d+16/S

```

Try it Online!

So... Vyxal uses sympy for numbers, and sympy represents complex equations, such as `sqrt(17) + 1`, as expressions that resolve to that.

So, all we have to do is calculate the number (using the question's formula for convenience) and stringify it.

```
17√                                   # Push √17
   :£‹                                # Store a copy to the register and push √17 - 1
      34¥d-√                          # Push √(34 - 2√17)
            :→                        # Store a copy to the ghost variable
              +                       # Add to previous
[             ]                       # √17 - 1 + √(34 - 2√17)
               ¥T17+                  # 3√17 + 17
                    ←-                # Subtract ghost variable
                                      # 3√17 + 17 - √(34 - 2√17)
                      34¥d+√d-        # √(34 + 2√17) subtracted from above
               [             ]        # Results in 3√17 + 17 - √(34 - 2√17) - 2√(34 + 2√17)
                              √d      # Take the square root of that doubled
                                +16/S # Add to previous, divide by 16 and format.

```
> 3 votes

# Answer
# golflua, 122 chars

Adapted from this Math.se post.

```
f='sqrt('y='(1-'..f..'17))'x='('..y..'/2+'..f..y..'*'..y..'/4+4))'w('(2/'..x..'+'..f..x..'/2*'..f..'17+4*'..f..'17))))/4')

```

which is pretty damn long :( (mostly because of the wasteful `..` for concatenating strings).

Output

```
(2/((1-sqrt(17))/2+sqrt((1-sqrt(17))*(1-sqrt(17))/4+4))+sqrt(((1-sqrt(17))/2+sqrt((1-sqrt(17))*(1-sqrt(17))/4+4))/2*sqrt(17+4*sqrt(17))))/4

```

Which, when evaluated, returns `0.93247222940436`
> 2 votes

# Answer
# Ruby, 71

I think this could be shorter in another language.

```
'(s/2)+s-s*2))+s*2+s*72)-4*s-s*2))-8*s+s*2)))-1)/16'.gsub(?s,'sqrt(34')

```

The above string expression evaluates to the below string. The idea was to rearrange the expression so that a single substitution of `s` -\> `sqrt(34` would be the only operation needed to decompress it.

```
(sqrt(34/2)+sqrt(34-sqrt(34*2))+sqrt(34*2+sqrt(34*72)-4*sqrt(34-sqrt(34*2))-8*sqrt(34+sqrt(34*2)))-1)/16

```

I assume "produce in any other conventional way" means an expression is enough. If this is not the case: Printing the string in quotation marks would need 2 extra bytes at the beginning of the source code: `p` . For 5 bytes it can be printed without quotation marks by adding `puts`. Enclosing it in `->{}` yields an anonymous function for 4 extra bytes.
> 2 votes

# Answer
# CJam, 68

```
"2* 17 sqrt( 23) 243-41) (1+0+423+1+41-0-4243+41))"S/~5{s/\*}/W")/"G

```

Try it online
> 1 votes

# Answer
# R 68 bytes

```
s=sqrt;x=s(17);y=s(34-2*x);cat((x+y+2*s(17+3*x-y-2*s(34+2*x))-1)/16)

```
> 1 votes

# Answer
# Vim, 70 keystrokes

```
:im a *sqrt(<CR>
:im b a17)<CR>
i(1b-1+1a34-2b)+2b<bsp>+3b-1a34-2b)-2a34+2b)))/16<esc>

```
> 1 votes

# Answer
# Perl 5, 78 bytes

A subroutine:

```
{'(1S)+T-2S))+2S+3S)-T-2S))-2*T+2S)))-1)/16'=~s/S/*sqrt(17/gr=~s/T/sqrt(34/gr}

```

View the returned value by means of `print sub{...}->()` or the like.

Hat tip.
> 0 votes

---
Tags: code-golf, math, kolmogorov-complexity, trigonometry
---


title: Encode Antarctic claims

text:
# Question
Title: Encode Antarctic claims
Seven countries lay official claims to parts of Antarctica: Argentina, Australia, Chile, France, New Zealand, Norway, and the United Kingdom. We will focus only on the claims of the main Antarctic landmass south of 60° S, which are:

* Chile: between 90° W and 53° W
* United Kingdom: between 80° W and 20° W
* Argentina: between 74° W and 25° W
* Norway: between 20° W and 44°38 E
* Australia: between 44°38 E and 136°11 E; and between 142°2 E and 160° E
* France: between 136°11 E and 142°2 E
* New Zealand: between 160° E and 150° W

The region between 150° W and 90° W is unclaimed. Note also that Chile's, the UK's, and Argentina's claims overlap to some degree.

Here is a map:

The above image modified from work at https://w.wiki/4e3R; used under CC-BY-SA 3.0.

More information and maps are available on Wikipedia.

All of these claims extend northwards from the South Pole at 90° S. It is unclear where Norway's stops, but it does not matter because we will only ask about the claims *just* north of the South Pole.

## Task

Your task is to encode the information about the claims in the fewest bytes possible: given an input \\$ x \\$, output the set of countries which claim Antarctica at longitude \\$ x \\$° and latitude 89.9° S.

You should represent outputs of countries using any seven distinct values, within reason.

For the areas where multiple claims overlap (which are variously those of Argentina, Chile, and the United Kingdom), you should output the multiple values representing those countries. These multiple outputs may be in any order.

For the unclaimed region between 150° W and 90° W, you should output an empty list.

## Test cases

```
     Input     ->  Output(s)
--------------------------------------
  0.0 /  360.0 ->  [Norway]
180.0 / -180.0 ->  [New Zealand]
223.2 / -136.8 ->  []
270.1 /  -89.9 ->  [Chile]
280.5 /  -79.5 ->  [Chile, United Kingdom]
296.6 /  -63.4 ->  [Argentina, Chile, United Kingdom]
337.6 /  -22.4 ->  [United Kingdom]
340.3 /  -19.7 ->  [Norway]
 44.6          ->  [Norway]
 44.7          ->  [Australia]
139.4          ->  [France]
142.0          ->  [France]
142.1          ->  [Australia]
161.8          ->  [New Zealand]
190.5 / -169.5 ->  [New Zealand]

```

## Rules

* Your code must support non-integer longitudes. Small errors due to floating-point precision errors are acceptable
* You may choose to require input \\$ x \\$ between -180° and 180° (with negative values representing west of the Prime Meridian), or between 0° and 360°. You only need to support one of the two edges of whichever range you choose
* Behaviour exactly on the boundaries of claims (e.g. at exactly 20° W) is undefined
* You may use any standard I/O method
* Standard loopholes are forbidden
* This is , so the shortest code in bytes wins

# Answer
# JavaScript (ES10), 128 bytes

Expects a signed value.

Returns **0** for New Zealand, **2** for Argentina, **32** for Norway, **34** for Chile, **64** for United Kingdom, **65** for France, **98** for Australia.

```
v=>[90,100,106,160,a=13478/60,b=19322/60,c=18971/60,0,340].flatMap((x,i)=>v<x|v>[127,160,155,a,c,340,b,30][i]?[]:x*29&99,v+=180)

```

Try it online!
> 5 votes

# Answer
# Charcoal, 137 bytes

```
≔×⁶⁰ＮθＥΦＥ⪪”}∧¡8↥″⟧ＭＸ⬤～m→⊖⊗9⁸'DQζF%f¹ψz‖aνy("⟲?⎚‹3Ｉ‹4↥GNＯk³▷Ｈ!Ｊ;⁵´j‹Ｚ*I:↷¡!β↑}1⊞↘≦ＱêY(¦≔πω/_²≔▶⁶ω≧N4Þ⁰^⊕﹪ＷÞ｜l⎚Ｖ2⊖¬|η&f≔”¶⪪ι ››Ｉ⊟ιθ›Ｉ⊟ιθ⪫ι

```

Try it online! Link is to verbose version of code. Assumes input is non-negative but less than `360`. Not much shorter than the JS version because I output country names.

```
≔×⁶⁰Ｎθ

```

Multiply the input by `60` to convert it into minutes.

```
ＥΦＥ⪪”...”¶⪪ι ››Ｉ⊟ιθ›Ｉ⊟ιθ⪫ι

```

Split the compressed data string on newlines and again on spaces. Keep only those where the input is between the boundaries or on the lower boundary. Fix up "United Kingdom" back into a single string (using "UK" would save a byte, and double-spacing the output would save a further 3 bytes).

78 bytes using custom output:

```
≔×⁶⁰ＮθＩ﹪⌕ＡＥＥ⪪”←＆!ω\⟧≕Ｇ⁵↑³yυ~r,S⦃›F⁷ω(Ｄ⧴aM↖G≕%›"‽.⊞⭆↓‽ⅈ0ÀG→$”¶⪪ι ››Ｉ⊟ιθ›Ｉ⊟ιθ¹¦⁷

```

Try it online! Link is to verbose version of code. Explanation: Obtains the indices of the matching ranges and reduces modulo 7 to output digits according to the following key:

```
0 Norway
1 Australia
2 France
3 New Zealand
4 Chile
5 United Kingdom
6 Argentina

```

(Note that the ranges are ordered slightly differently in this version.)
> 5 votes

# Answer
# C (gcc), ~~247~~ 172 bytes

* -7 thanks to pxeger
* -3 by changing the output values (and fixed a bug)
* -6 thanks to gastropner
* -8 by changing the range format to (offset, starting longitude)
* -61(!) thanks to Neil

Takes a floating-point longitude from `[0, 360)` degrees, but performs all the computations using integer minutes. For Norway, I split up the range into two sections to make calculations easier.

Countries are expressed in the following format:

* 0: Norway
* 1: Australia
* 2: Chile
* 3: United Kingdom
* 4: Argentina
* 5: France
* 6: New Zealand

```
g[]={1078,8522,2678,0,3e3,9600,351,8171,2940,17160,3600,16800,2220,16200,5493,2678,1201,20400},i,j,*a;f(float l){for(i=l*60,j=9,a=g;j--;)*a+++0u>i-*a++&&printf("%d,",j%7);}

```

Try it online!

Ungolfed:

```
g[]={
  1078,8522, // Australia
  2678,0, // Norway
  3000,9600, // New Zealand
  351,8171, // France
  2940,17160, // Argentina
  3600,16800, // United Kingdom
  2220,16200, // Chile
  5493,2678, // Australia
  1201,20400 // Norway
  },
  i,j,*a;

f(float l) {
  for(i=l*60, // Convert input into minutes
      j=9,a=g;j--;)
    *a+++0u>i-*a++&& // (Input-start longitude) within range?
      printf("%d,",j%7);
}

```
> 5 votes

# Answer
# 05AB1E, ~~55~~ 54 bytes

```
60*ò•1ζ_ʒǝ=¶Ò´™p]·ÐΘä¥ËrªÞ÷Â0[₁µÑ…εC`£•Ž≠¶в2ô€ŸQOƶ0K7%

```

-1 byte thanks to *@Neil* by also using modulo-7.

Input as a longitude float in the range \\$\[0,360)\\$. Outputs \\$0\\$ for Argentina, \\$1\\$ for Australia, \\$2\\$ for Norway, \\$3\\$ for France, \\$4\\$ for New Zealand, \\$5\\$ for Chile, and \\$6\\$ for the United Kingdom.

Try it online or verify all test cases.

**Explanation:**

```
60*              # Multiply the (implicit) input by 60
   ò             # (Bankers) round it to the nearest integer
•1ζ_ʒǝ=¶Ò´™p]·ÐΘä¥ËrªÞ÷Â0[₁µÑ…εC`£•
                 # Push compressed integer 129995249012016373632115353299026583238712674313934551571472125857818360468822
 Ž≠¶             # Push compressed integer 21601
    в            # Convert the larger integer to base-21601 as list:
                 #  [2678,8171,0,2678,8171,8522,9600,12600,16200,18420,16800,20400,17160,20100,8522,9600,20400,21600]
     2ô          # Split it into parts of size 2:
                 #  [[2678,8171],[0,2678],...]
       €Ÿ        # Map each pair to an inclusive ranged list
                 #  [[2678,2679,2680,...,8170,8171],[0,1,2,...,2677,2678],...]
         Q       # Check for each inner integer if its equal to the round(input*60)
          O      # Sum each inner list, resulting in 1 if it was within that range
           ƶ     # Multiply each by its 1-based index
            0K   # Remove all 0s
              7% # Modulo-7 to transform the 8 to 1 and 9 to 2
                 # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*) to understand why `•1ζ_ʒǝ=¶Ò´™p]·ÐΘä¥ËrªÞ÷Â0[₁µÑ…εC`£•` is `129995249012016373632115353299026583238712674313934551571472125857818360468822`; `Ž≠¶` is `21601`; and `•1ζ_ʒǝ=¶Ò´™p]·ÐΘä¥ËrªÞ÷Â0[₁µÑ…εC`£•Ž≠¶в` is `[2678,8171,0,2678,8171,8522,9600,12600,16200,18420,16800,20400,17160,20100,8522,9600,20400,21600]`.

---

Outputting with the actual title-cased countries from the dictionary would be **85 bytes** instead, by removing the no longer necessary `7%` and adding some additional trailing bytes:

```
60*ò•1ζ_ʒǝ=¶Ò´™p]·ÐΘä¥ËrªÞ÷Â0[₁µÑ…εC`£•Ž≠¶в2ô€ŸQOƶ0K”²Ðˆ‚¬ìˆÖ€¢1¸ŽƒŠ0”#sèεT”™ÆŠß”#1ú‡

```

Try it online or verify all test cases.

**Explanation:**

```
”²Ðˆ‚¬ìˆÖ€¢1¸ŽƒŠ0”
             # Push dictionary string "Argentina Australia Norway France New1 Chile United0"
 #           # Split on spaces
  sè         # Modular 0-based index the calculated value into this list
    ε        # Map over each result:
     T       #  Push 10
      ”™ÆŠß” #  Push dictionary string "Zealand Kingdom"
       #     #  Split it on spaces
        1ú   #  Pad each with a leading space
          ‡  #  Transliterate the "1" to " Zealand" and "0" to " Kingdom"
             # (after which the resulting list is output implicitly)

```

See the same 05AB1E tip I linked earlier (section *How to use the dictionary?*) to understand why `”²Ðˆ‚¬ìˆÖ€¢1¸ŽƒŠ0”` is `"Argentina Australia Norway France New1 Chile United0"` and `”™ÆŠß”` is `"Zealand Kingdom"`.
> 2 votes

---
Tags: code-golf, kolmogorov-complexity
---