title: Alice's First Code Review

text:
# Question
Title: Alice's First Code Review
Alice is an intern in a company that uses Brainfuck as a primary language for both client-side and server-side development. Alice just has written her first code and she's a bit nervous as she's getting ready for her first code review.

Alice wants to make her code properly formatted and look nice, but she has no time to read the 328-pages company code style guide, so she decided to format it as a *perfect square*. Alas, code length may be insufficient to form a square, so she decided to leave a *rectangular* gap in the middle. Gaps must be perfectly *centered* and as *close to square* as possible.

### Examples

```
++++++         +++++         +++++         +++++         +++++         +++++
++++++         +++++         +++++         +  ++         ++ ++         +++++
++++++         ++ ++         +   +         +  ++         +   +
++++++         +++++         +++++         +++++         ++ ++         +++++
++++++         +++++         +++++         +++++         +++++         +++++

Perfect         OK         Acceptable   Unacceptable    No way!        Nope.

```

Write a program or a function to help Alice. Given Alice's code as an input string, output properly formatted code as described below if possible. If formatting is impossible, output crying emoji `:~(`.

This is so answers are scored in bytes with fewer bytes being the aim.

### Constraints

1. Your program or function should take a single string as an input and output one or more lines of text (or return multi-line string or array of strings, if you implement a function).
2. Input string may contain any ASCII characters including whitespaces.
3. All whitespaces in input must be ignored. They shouldn't count for code length and they shouldn't be used in output.
4. Input string contains at least one non-whitespace character.
5. Formatted code must have the same non-whitespace characters in the same order as in input code.
6. Formatted code must be a perfect square, i.e. all lines should have same length, and number of lines should be equal to the lines' length.
7. Formatted code may contain a gap in the middle.
8. Only space characters (ASCII code 32) may be used in the gap.
9. Gap (if present) must be rectangular.
10. Every line of formatted code must contain at least one non-whitespace character, i.e. gap width must be strictly less than square width (gap 5x1 is unacceptable for 5x5 square).
11. Gap should be horizontal, i.e. gap width should be greater than or equal to gap height.
12. Gap must be perfectly centered.
13. Consequently gap width and height parity should be the same as square width parity (for example for 5x5 square gap may be 1x1, 3x1, or 3x3).
14. If possible, output square with no gap at all.
15. In case of multiple solutions, choose one with gap closest to square, i.e. difference between gap width and gap height is minimal (for example: gap 10x10 is more preferable than 8x6, and 8x6 is more preferable than 6x2).
16. If still there's a tie, choose solution with minimal gap area (for example gap 2x2 is more preferable than 4x4).
17. If it is impossible to format code at all, output `:~(`.
18. Newline after last line is optional.
19. **\[New\]** You may safely assume that any character with code below 33 is a white-space. I hope it will help you for golfing.

### Tests

```
Input           Output      Code length     Comment

+++++++++       +++                   9     Alice is lucky,
                +++                         her code perfectly fits a square.
                +++

++++++++        +++                   8     Though code length isn't enough for a square,
                + +                         a small gap fixes it.
                +++

++++++          :~(                   6     No luck, code cannot be formatted.

Hello,          Hell                 12     Input may contain any ASCII characters,
World!          o  ,                        but whitespaces in input should be ignored.
                W  o
                rld!

+++++ + +++++   +++++                22     Gap is not required to be a square,
+++++ + +++++   +++++                       it can be a rectangle.
                +   +
                +++++
                +++++

+++ + +++       ++++++++             28     There exists another solution:
+++ + +++       +      +                    6x6 square with 4x2 gap,
+++ + +++       +      +                    but in Alice's opinion square gap
+++ + +++       +      +                    makes code more readable.
                +      +
                +      +
                +      +
                ++++++++

```

### Tricky tests

```
This must be    Thism                24     7x7 with 5x5 gap looks good,
5x5 with 1x1    ustbe                       but 5x5 with 1x1 gap is better,
gap.            5x 5w                       because gap area is smaller.
                ith1x
                1gap.

+++ +++ +++     :~(                  18     In case you tried 5x5 square
+++ +++ +++                                 with 7x1 gap ;)

```

### Resources

To save space you can find sample code and extra test cases on tio.run

**\[New\]** You may take a look at the table of accepted solutions for inputs upto 100 characters. I swapped width and height because it seems to look more intuituve.

Inspired by: A square of text

### Changes

* Added 2 tests, fixed bug in sample code.
* Added table of solutions upto 100, added white-space clarification.

# Answer
# C (gcc), ~~354~~ 348 bytes

-6 thanks to ceilingcat

```
h,i,j,k,l,m;g,v,w,d;f(char*s){for(j=l=0;i=s[j];d=g=l+=!isspace(s[j++]));for(;i++<l;)if(h=i*i-l)for(j=0;j<i-++j;h>0&h%k<1&k<=m&m<i&m+~k&m-k<g|m==k+g&(d-2*v)*(d-2*w)>h?w=i-m>>1,v=j,g=m-k,d=i:0)k=i-2*j,m=h/k;else g=0,v=w=d=i;if(g-l)for(i=j=1;*s;j+=!i++,k=0,i%=~d)for(putchar(i?v>=j|j>d-v|w>=i|i>d-w?k=1,*s:32:10);k;k*=isspace(*++s));else puts(":~(");}

```

Try it online!
> 5 votes

# Answer
# Stax, 80 bytes

```
ö╦Çc▀╕╡ëé╓]µiÖ9♪`W|╣▐↑╖D┘↕♫╗╔äƒ■úφ■U`ÿ⌠%é┴☼vAú)☺@Ä±◄¬¶¢(îÉ┼6⌠D~♀└lfæA.I@º╤∟òîü╦(

```

Run and debug it

How does it work?

* Consider all squares with rectangle cutouts.
* Filter out program shapes that aren't the right size.
* Filter out program shapes that don't have matching parity.
* Filter out program shapes where the cutout is too big for the square.
* If none are found, output failure and quit.
* Find the shape that minimizes "rectangularity" of cutout, then by cutout size.
* Replace each character in the program shape with the corresponding character in the program input.

Unpacked, ungolfed, and commented it looks like this.

```
                input e.g. "big socks"
L$j$            remove whitespace from input e.g. "bigsocks"
cr{~F           copy push each remaining character to input stack in reverse order
%c              get length L of flattened input and copy e.g. 8
^r3:$           create triples [a,b,c] in range 0..n e.g. [[0,0,0], [0,0,1], ... [8,8,8]]
{E*NsJ+n=f      filter triples: require a*a-b*c=L e.g. [[3,1,1], [4,1,8], ...]
{ET>f           filter triples: a>b and a>c e.g. [[3,1,1]]
{{2%m:u_0#+f    filter triples: a%2=b%2=c%2 or b*c=0 e.g. [[3,1,1]]
":~("s|c        if there are no triples, output ":~(" and terminate
{D:s_D:*\oh     sort by [abs(b-c),b*c]; keep the first e.g. [3,1,1]
X               store the chosen triple in the X register
E               explode onto stack e.g. 3, 1, 1
z)]*            using last two values, make a rectangle of zeroes e.g. 3, [[0]]
~               this will be the cutout, push it to the input stack
c'X*]*          make a square of "X" e.g. ["XXX", "XXX", "XXX"]
xEd-h           given the dimensions in x register, calculate the centered cutout coordinates
xEsd-h          e.g. ["XXX", "XXX", "XXX"], 1, 1
,||             embed the cutout grid at the specified coordinates e.g. ["XXX", "X X", "XXX"]
m'X{,]}R        for each line, regex replace "X" with a character from the input stack

```

Run this one
> 5 votes

# Answer
# JavaScript (ES6),  ~~284 ... 274~~  270 bytes

*Saved 4 bytes thanks to @Shaggy*

Returns an array of strings.

```
s=>(s=s.replace(/\s/g,''),n=s.length,o=[':~('],W=d=g=(x,w=0,h=p=0)=>4*~-x>n?o:h>w?++w>x-2?g(-~x):g(x,w):g(x,w,h+1,o=n-x*x+w*h|(w^x|h^x)&!!(w|h)|w-h>d|w-h==d&w>W?o:[...Array(x)].map((_,Y,a)=>a.map((_,X)=>2*X>=x-w&2*X<x+w&2*Y>=x-h&2*Y<x+h?' ':s[p++]).join``,d=w-h,W=w)))``

```

Try it online!
> 4 votes

# Answer
# Charcoal, 120 bytes

```
≔Ｅ⮌⪫⪪Ｓ ωιθ≔⁰ηＦ⊕Ｌθ¿⁼Ｌθ×ιι«≔ιη≔ιζ≔ιε»Ｆ⊘ιＦ⊕κＦ∧⁼Ｌθ⁻×ιι×⁻ι⊗⊕κ⁻ι⊗⊕λ∨¬η›⁻ζε⁻κλ«≔ιη≔⊕κζ≔⊕λε»¿η«ＵＯη#ＪεζＦ›η⊗ζＵＯ⁻η⊗ε⁻η⊗ζψＵＭＫＡ⊟θ»:~(

```

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

```
≔Ｅ⮌⪫⪪Ｓ ωιθ

```

Strip the spaces from the input, then reverse it and split it into characters, so that we can loop over the characters more easily later.

```
≔⁰η

```

Start with a size of zero, indicating no result found (yet).

```
Ｆ⊕Ｌθ

```

Check all side lengths up to the length of the string. (Throwing a division in would of course make the code faster.)

```
¿⁼Ｌθ×ιι«≔ιη≔ιζ≔ιε»

```

If the result turns out to be a perfect square then save the square size and also set that as the border size.

```
Ｆ⊘ιＦ⊕κ

```

Loop over the possible border heights and widths (the border width is no greater than the border height, making the gap height no greater than the gap width.)

```
Ｆ∧⁼Ｌθ⁻×ιι×⁻ι⊗⊕κ⁻ι⊗⊕λ∨¬η›⁻ζε⁻κλ«≔ιη≔⊕κζ≔⊕λε»

```

If the size of the border is the desired length and we don't have a solution yet or it's not as square as this solution then update the solution with this square and border sizes.

```
¿η«

```

If we have a solution...

```
ＵＯη#

```

Draw a rectangle of an arbitrary character of the given square size.

```
ＪεζＦ›η⊗ζＵＯ⁻η⊗ε⁻η⊗ζψ

```

If the border is small enough to leave a gap then erase the gap. (The drawing command will draw upwards and leftwards for negative values and doesn't like zero values at all.)

```
ＵＭＫＡ⊟θ

```

Replace all (remaining) characters with characters from the input.

```
»:~(

```

Otherwise output `:~(`.
> 2 votes

# Answer
# Jelly, ~~91~~ 85 bytes

```
ÆDżU$<Ạa;ḂEɗʋƇṢƑƇ;€€
ḟ⁶ḟ⁷;©⁶L’²<¥Ðḟ²_ç;,`Wɗ¹?⁸ʋ€$Ẏạ/ÞḢµIH+""Rp"/ḟ@/ŒṬ€ĖP€Sị®Yµ“:~(”¹?

```

Try it online!

A monadic link that takes the input string as its argument and returns a string either with the formatted output or `:~(`.
> 2 votes

# Answer
# Python 2, ~~287~~ ~~281~~ 279 bytes

```
c=list("".join(input().split()))
l=len(c)
p=[]
for q in range(l*l):x=q%l;y=q/l;s=(l+x*y)**.5;p+=[(abs(x-y)/2,int(s),-x)]*(s%1==0)*(x<s-1>y>=s%2==x%2==y%2or x<1)
if p:d,s,x=min(p);b=(s+x)/2;Y=0;exec"c[b:b]=' '*-x*(b+d<=Y<s-b-d);print''.join(c[:s]);c=c[s:];Y+=1;"*s
else:print':~('

```

Try it online!

Uses Python's lexicographic list comparison by using the same values for both choosing a solution and printing it. I'm pretty sure ~~10~~ ~~4~~ 2 or so bytes can still be shaved off.

### Explanation

```
c=list("".join(input().split()))
l=len(c)
p=[]

```

Remove whitespaces by splitting with whitespace and joining with `""`, then convert input to a list for later. Also initialize `l` to length of actual code and `p` to list of valid possibilities.

```
for q in range(l*l):x=q%l;y=q/l;s=(l+x*y)**.5;

```

Loop through all possibilities of gap sizes from `0*0` to `l*l`. Compute the edge length of the square with `l` code chars and `x*y` spaces as `s`.

```
p+=[(abs(x-y)/2,int(s),-x)]*(s%1==0)*(x<s-1>y>=s%2==x%2==y%2or x<1)

```

Check if the following conditions match:

* `s % 1 == 0`, i.e. a perfect square would be formed
* `x < s-1 > y`, i.e. `x` and `y` are at most `s-2` and fit inside the square
* `s % 2 == x % 2 == y % 2`, i.e. both `x` and `y` match the edge's parity and can be centered
* but if `x < 1`, i.e. `x == 0`, ignore all but the perfect square requirement

If the conditions matched, add the following items in a tuple to `p` to find the optimal one:

* `abs(x-y)/2`; first find the minimal difference of `x` and `y` to get the most square gap. This is always even so we divide by 2.
* `int(s)`; next find the minimal side length. Since `s` is an integer and increases as the gap area `x*y`, this sorts by gap area.
* `-x`; next find the maximal width to prefer horizontal gaps. This comes after the area due to how it was developed, but the area is the same for `x*y` and `y*x` so it works.

```
if p:d,s,x=min(p);b=(s+x)/2;Y=0

```

If we found any valid layouts, find the optimal one as described above. Compute the horizontal border `b` and initialize the line number `Y` to 0.

```
exec"c[b:b]=' '*-x*(b+d<=Y<s-b-d);print''.join(c[:s]);c=c[s:];Y+=1;"*s

```

If the line number `Y` is inside the gap (the vertical border is `b+d`, with `d` from the tuple), add the gap width's worth of spaces after the horizontal border in `c`. (The modification of `c` is why we need it to be a list.) Then print a line of the square and remove it from `c`. Repeat `s` times, incrementing the line number.

```
else:print':~('

```

If no layouts were found, fail.
> 1 votes

# Answer
# Pyth, ~~99~~ 98 bytes

```
#JscQ)=QshKh|oaFtNSf!|%hT1&eT|t{%R2TgeStThT+L@+lJ*Fd2^UJ2
":~("Am/-Qd2tKW=W}~hZrG-QGJj*eKdcJ]H<~>J

```

Try it online!

This uses the same algorithm as my Python answer, but many details are significantly changed to be shorter in Pyth.

Pyth shows its age here, since it hasn't been updated in ages and only uses the printable ASCII characters (for code, not data), wasting a lot of space.

Interestingly, if Pyth used the same kind of base-256 packing as Stax, this program could be ⌈98 log256 95⌉ = 81 bytes long, right next to Stax (80 bytes) and Jelly (85 bytes). I think this nicely shows how close golfing languages are even with their drastically different paradigms.

### Explanation (only slightly less unreadable than the code)

`#` wraps everything in a `while True:` that suppresses the message and quits on error.

`JscQ)` `c`hops input (`Q`) at whitespace, `s`ums the parts together and saves the result in `J`.

`^UJ2` makes the list of indices (`U`) of `J` and takes its `2`nd Cartesian power (`^`), resulting in all pairs `[h,w]` with `0<=h<len(J)` and `0<=w<len(J)`.

`+L@+lJ*Fd`: for all (`L`) such pairs `d`, adds (`+`) the square root (`@``2`) of (the `l`ength of `J` plus (`+`) the product (`*F`) of the pair `d`) to the left side of the pair, creating a triplet `[side length, gap height, gap width]`.

`f!|%hT1&eT|t{%R2TgeStThT`: `f`ilter for triplets `T` where

* neither of (`!|`):
    + side length (`hT`) modulo 1 (`%``1`) is nonzero
    + both of (`&`):
        - gap height (`eT`) is nonzero
        - either of (`|`):
            * each number in the triplet (`R`) modulo 2 (`%``2`), with duplicates (`{`) and the first unique (`t`) removed, is nonempty
            * the larger (`eS`) of gap height and gap width (`tT`) is `g`reater-or-equal than side length (`hT`)

`S` sorts the triplets lexicographically (by side length, then by gap height). `oaFtN` then `o`rders the triplets by the `a`bsolute difference between gap height and gap width (`tN`).

At this point, if we have no valid solutions, `|` evaluates its second argument, `\n":~("`, which prints and returns `:~(`. `h` takes the optimal solution (or `":"` if none) and it is saved in `K`. Then `h` takes its side length (or `":"` if none), `s` casts it to integer (or fails and quits if none) and it is saved (`=`) in `Q`.

Each of (`m`) `[gap height, gap width]` (`tK`) is then subtracted (`-`) from side length (`Q`) and the result divided by 2 (`/``2`). The results are `A`ssigned to `G` and `H`.

Finally, we enter a `W`hile loop. `Z` starts at 0 and each iteration we increment it but use the old value (`~hZ`, think `Z++` in C).

* If (`W`) the old value is in (`{`) the `r`ange `G` to (side length - `G`) (`-QG`), assign (`=`) to `J` the following: `c`hop `J` at position (`]`) `H` and `j`oin the halves with gap width `eK` times (`*`) a space (`d`). If the value was not in the range, just return `J`. If this result is empty, stop the loop.
* Remove (`>`) the first `Q` characters from `J` and assign (`~`) the result to `J`. From the old value of `J`, take (`<`) the first `Q` characters and print them.

Finally, the `#` loop starts again, errors and quits because `cQ)` with `Q` containing a number is invalid.
> 1 votes

# Answer
# 05AB1E, ~~95~~ 89 bytes

```
…
    мDg©Ý3ãʒćnsP-®Q}ʒć‹P}ʒÈËyß_~}Dg_i…:~(ëΣ¦DÆÄsP‚}н©¤_iнë¬Ućα¤®Ås<иs;R`X*+šXnª£®θð×ýX}ô»

```

A few bytes here and there can definitely be golfed.

The first three steps of the program are inspired by *@recursive*'s Stax answer, so make sure to upvote him!

Try it online or verify all test cases.

**Explanation:**

Step 1: Remove all white-spaces:

```
…
                   # Push string " \n\t"
    м              # And remove those from the (implicit) input-string

```

Step 2: Create all possible triplets \\$\[a,b,c\]\\$, where \\$a\\$ is the dimension of the resulting \\$a×a\\$ square, and \\$b×c\\$ is the size of the gap. We do this by creating all possible triplets using integers in the range \\$\[0,a\]\\$. And then we filter these where all of the following is truthy for the triplet:

* \\$a^2-b×c=L\\$, where \\$L\\$ is the length of the string
* \\$(a\gt b)\text{ and }(a\gt c)\\$
* \\$(a\pmod2=b\pmod2=c\pmod2)\text{ or }(min(a,b)\neq0)\\$

For example: \\$L=28\\$ will result in the triplets `[[6,2,4],[6,4,2],[8,6,6]]`.

```
Dg                 # Get the length of this string (without popping by duplicating first)
  ©                # Store this length in variable `®` (without popping)
   Ý               # Create a list in the range [0,®]
    3ã             # Create all possible triplets by repeating the cartesian product 3 times
ʒ                  # Filter these triplets by:
 ć                 #  Extract head; pop and push remainder-list and head to the stack
  n                #  Square the head
   sP-             #  Take the product of the remainder, and subtract it from the squared head
      ®Q           #  And check if it's equal to the string length in variable `®`
}ʒ                 # Filter the remaining triplets further by:
  ć‹P              #  Where the first integer is larger than the other two
}ʒ      }          # And filter it a third time by:
  ÈË               #  Where all three are either odd or even
       ~           #  Or
    yß_            #  It does not contain any 0s

```

Step 3: Check if we still have any triplets left. If not, output `":~("`; if we do, determine which one to use by sorting and only leaving the first. We do this by sorting the tuples \\$(abs(b-c),b×c)\\$.

For example: the triplets `[[6,2,4],[6,4,2],[8,6,6]]` will be sorted to `[[8,6,6],[6,2,4],[6,4,2]]`, after which only `[8,6,6]` remains.

```
Dg_i               # If this completely filtered list is now empty:
    …:~(           #  Push string ":~("
ë                  # Else:
 Σ                 #  Sort the triplets by:
  ¦                #   Remove the first character
   DÆÄ             #   Get the absolute difference between the remaining two integers
   sP‚             #   And pair it with the product of the remaining two integers
      }н           #  After we're done sorting: only leave the first triplet

```

Step 4: Create a list on how we should split the string to insert the spaces. This is done like this:

Given \\$\[a,b,c\]\\$, create a list with:

* As first item: \\$\frac{a-b}{2}×a + \frac{a-c}{2}\\$
* As middle \\$b-1\\$ items: \\${a-c}\\$
* As last item: \\$a^2\\$

For example: triplet `[7,3,5]` will result in the list `[15,2,2,35]`.

```
©                  #  Store this triplet in variable `®` (without popping)
 ¤_i               #  If the last value is 0 (which means the string is a square without gap):
    н              #   Simply keep the first value of the triplet
   ë               #  Else:
    ¬U             #   Store the first value in variable `X` (without popping)
      ć            #   Extract the first value; pop and push remainder-list and head to the stack
       α           #   Get the absolute difference of this head with the other two values
        ¤          #   Push the last value (without popping the pair itself)
         ®Ås<и     #   And repeat it the middle element or `®` minus 1 amount of times
       s           #   Swap to get the difference pair again
        ;          #   Halve both values
         R`        #   Push them reversed to the stack
           X*      #   Multiple the first value by `X`
             +     #   And then add it to the second value
              š    #   Prepend this in front of the repeated list
               Xnª #   And also append the square of `X`

```

Step 5: And finally we split the string based on this list, join it back together with \\$c\\$ amount of spaces, split it into parts of size \\$c\\$, and join those together by newlines. For example:

String `"Alongtesttoseeifitworksasintended."` split according to list `[15,2,2,35]` will result in: `["Alongtesttoseei","fi","tw","orksasintended."]`. This is then joined by \\$c=5\\$ amount of spaces to `"Alongtesttoseei fi tw orksasintended."`. And then split into parts of size \\$a=7\\$ to this: `["Alongte","sttosee","i f","i t","w o","rksasin","tended."]`. Which is then joined by newlines to output.

```
    £              #   Then split the string into parts based on this list
     ®θð×          #   Push a string consisting of the last value of `®` amount of spaces
         ý         #   Join the list of substrings by this
          X        #   Push variable `X`
   }ô              #  After the if-else: split the string into parts of that size
     »             #  And then join these by newlines
                   # (after which the top of the stack is output implicitly as result)

```
> 1 votes

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


title: How many Jimmys can fit?

text:
# Question
Title: How many Jimmys can fit?
In this simple but fun challenge, you were asked to determine if Jimmy would fall of their platform. Jimmy has three body parts `/`, `o`, and `\` arranged like this

```
/o\

```

Platforms are represented with `-`. Jimmy will fall off their platform iff they have two or more body parts that are not directly above a platform.

Some examples:

```
   /o\
- -------

```

Jimmy will balance since all their body parts are above a `-`.

```
   /o\
    ------   ---

```

Jimmy will balanced since two body parts are above `-`s.

```
 /o\
-- ----  --

```

Jimmy will balance even though they are split between two platforms

```
  /o\
   -

```

Jimmy will not be balanced since two body parts are not above a platform.

---

Your task is to write a program that takes a platform as a lengthed container containing only `-`s and s (e.g. a string) and outputs the number of Jimmys that can be placed on the platform such that none of them will fall and none of them will overlap. A Jimmy may have one of their body parts to the left of the beginning of the string or the right of the end of the string.

This is so answers are scored in bytes with fewer bytes being the aim.

## Test cases

### Inputs

```
-  -  -

- -
--
-- --
----
- -- --
------- -

```

### Respective outputs

```
0
0
1
1
2
2
2
3

```

# Answer
> 15 votes
# JavaScript (ES6),  ~~45 41~~  40 bytes

*Saved 4 bytes thanks to @Shaggy*

```
s=>(0+s+0).split(/.--|-.-|--./).length-1

```

Try it online!

# Answer
> 9 votes
# Python 2, 53 bytes

```
lambda s:len(re.findall('.--|-.-|--.',`s`))
import re

```

Try it online!

Based on Arnauld's regex. Greedily searches for all the non-overlapping length-3 substrings with two or more `-`. A trick is to do ``s`` to enclose the input string in quotes as padding to leave room for Jimmys to hang off on either end like

```
/o\/o\
'----'

```

**Python 2, 57 bytes**

```
f=lambda s:'--'in s[:3]*2and-~f(s[3:])or s>''and f(s[1:])

```

Try it online!

Requires a cheesy I/O format of the input already in quotes. Outputs `False` for 0.

A recursive function that places each Jimmy on the leftmost position allowed, by either placing Jimmy over the first three characters if they can hold Jimmy, or otherwise deleting the first character. A cute trick is to check if `s[:3]` contains two or more `-` by doing `'--'in s[:3]*2`, which concatenates two copies of `s[:3]` and checks for two adjacent `-`.

# Answer
> 3 votes
# Japt, 16 bytes

Based on Arnauld's original JS solution. I tried a few different methods to get the necessary padding either side of the input but all came in at the same length - still searching for a shorter way...

```
ûUÊÄÄ è".--|-."ê

```

Test it

```
ûUÊÄÄ è".--|-."ê     :Implicit input of string U
û                    :Centre pad with spaces to length
 UÊ                  :  Length of U
   ÄÄ                :  Add 1, twice
      è              :Count the occurrences of
       ".--|-."ê     :  ".--|-." palindromised, resulting in the RegEx /.--|-.-|--./g

```

# Answer
> 3 votes
# Perl 5 `-p`, 28 bytes

Uses the same method as @Arnauld's JavaScript.

```
$_=@a=" $_ "=~/.--|-.-|--./g

```

Try it online!

# Answer
> 3 votes
# Excel, 96 bytes

`A1` = platform. Entered as array Formula `Ctrl`+`Shift`+`Enter`

```
=SUM(IF(LEN(TRIM(MID(IF(MOD(LEN(A1),3)=1," ","")&A1,3*ROW(INDIRECT("A1:A"&LEN(A1)))-2,3)))>1,1))

```

# Answer
> 3 votes
# 05AB1E, 16 bytes

```
ðì‚ε3ôʒ'-¢2@}g}à

```

Can definitely be golfed.. Sometimes it's annoying to see all these regex answers in a challenge when using 05AB1E, which is lacking regex of any kind. ;)

Try it online or verify all test cases.

**Explanation:**

```
ðì            # Prepend a space before the (implicit) input
  ‚           # Pair it with the unmodified (implicit) input
   ε          # Map both to:
    3ô        #  Split them into parts of size 3
      ʒ       #  Filter these parts by:
       '-¢   '#   Where the amount of "-"
          2@  #   Is larger than or equal to 2
      }g      #  After the filter: take the length to get the amount of items left
   }à         # After the map: get the maximum of the two
              # (which is output implicitly as result)

```

# Answer
> 3 votes
# Ruby, 39 bytes

```
->s{s.scan(/(^|.)--|-.-|--(.|$)/).size}

```

Try it online!

# Answer
> 2 votes
# Stax, 13 bytes

```
ƒó±KêyG←à╛Ωô∟

```

Run and debug it

# Answer
> 2 votes
# Java 8, 41 bytes

```
s->(0+s+10).split(".--|--.|-.-").length-1

```

Try it online.

Port of *@Arnauld*'s JavaScript answer, except that `+0` is `+10` to fix test cases like `----`. This is necessary because the `String#split` builtin in Java will remove trailing empty Strings by default. This can be changed by adding an additional parameter to the `split` builtin (which is `0` by default in the `split`-builtin with a single String argument). To quote the usage of this additional parameter from the docs:

> The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.
> If the limit \\$n\\$ is **greater than zero** then the pattern will be applied at most \\$n-1\\$ times, the array's length will be no greater than \\$n\\$, and the array's last entry will contain all input beyond the last matched delimiter.
> If \\$n\\$ is **non-positive** then the pattern will be applied as many times as possible and the array can have any length.
> If \\$n\\$ is **zero** then the pattern will be applied as many times as possible, the array can have any length, **and trailing empty strings will be discarded**.

Because of this, usually `.split("...",-1)` is used to retain *ALL* trailing empty Strings, and I could have used it for this answer as well (Try it online). In this case changing the `+0` to `+10` saves two bytes over the `,-1`, though. :)

# Answer
> 1 votes
# Elm 0.19, 108 bytes

```
import Regex as R
f p=List.length<|R.find(Maybe.withDefault R.never<|R.fromString".--|-.-|--.")(" "++p++" ")

```

Based on the regex in Arnauld's JavaScript answer. Verify all test cases here.

Alternative solution without regex, significantly longer at **171 bytes**:

```
f p=(String.foldl(\z{x,y,s,c}->let(t,d)=if s<1&&List.length(List.filter((==)'-')[x,y,z])>1 then(2,c+1)else(max 0 s-1,c)in{x=y,y=z,s=t,c=d}){x=' ',y=' ',s=0,c=0}(p++" ")).c

```

Verify all test cases here.

# Answer
> 0 votes
# Jelly, 12 bytes

```
n⁶,Ż$s€3§Ẓ§Ṁ

```

Try it online!

Based on @KevinCrujissen’s 05AB1E answer so be sure to upvote him too.

# Answer
> 0 votes
# Charcoal, 25 bytes

```
Ｐθ↖Ｆθ¿›№ＫＭ-¹«⊞υωＭ³→»→⎚ＩＬυ

```

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

```
Ｐθ↖

```

Print the platform without moving the cursor, then move the cursor up and left as that is the first potential Jimmy position.

```
Ｆθ

```

Look for as many Jimmies as there are platform positions.

```
¿›№ＫＭ-¹

```

Check to see whether there is more than one piece of platform at this position.

```
«⊞υω

```

If so then note a valid Jimmy position...

```
Ｍ³→»

```

... and move three characters to the right so that the Jimmies don't overlap.

Otherwise the next potential Jimmy position is one character to the right.

```
⎚ＩＬυ

```

Clear the platform and output the count of discovered positions.

# Answer
> 0 votes
# PowerShell, 38 bytes

Port of Arnauld's JavaScript answer.

```
(" $args "-split'.--|-.-|--.').count-1

```

Try it online!

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


title: Analog is Obtuse!

text:
# Question
Title: Analog is Obtuse!
An analog clock has 2 hands\*: Hour and minute.
These hands circle the clock's face as time goes by. Each full rotation of the minute hand results in 1/12th of a rotation of the hour hand. 2 full rotations of the hour hand signifies a full day.

As these hands are fixed to the same central point, and rotate around that point, you can always calculate the angle between the hands. In fact there are 2 angles at any given time; A larger one, and a smaller one (sometimes they will both equal 180, but that's not important)

*\*Our hypothetical clocks don't have second hands*

## Task

Given a time in 24 hour format, output the smaller angle between the hands, in degrees. If the hands are directly opposite eachother (such as at `6:00`, `18:00` etc) output 180

## Rules

Input may be taken as: \- A delimiter separated string: `6:32`, `14.26` \- 2 separate values, strings or ints: `6, 32`, `14, 26` \- An array of 2 values, strings or ints: `[6, 32]`, `[14, 26]`

You may also optionally specify that your answer requires inputs be padded to 2 digits (assuming you take strings), ie: `06:32`, `06, 32`, `[06, 32]`

You may also optionally reverse the order of the inputs, taking minute then hour, ie: `32:6`, `32, 6`, `[26, 14]`

Hour will be an integer value between `0` and `23` (inclusive) Minute will be an integer value between `0` and `59` (inclusive)

You can assume that the minute hand snaps to increments of 6 degrees along the face (one evenly-spaced position for each minute value)
You can assume that the hour hand snaps to increments of 0.5 degrees along the face (one evenly-spaced position for each minute value per hour value)

Output must be given in degrees, not radians. You may include a trailing `.0` for whole numbers

## Scoring

This is so fewest bytes *in each language* wins!

## Testcases

```
Input: 06:32
Output: 4

Input: 06:30
Output: 15

Input: 18:32
Output: 4

Input: 06:01
Output: 174.5

Input: 00:00
Output: 0

Input: 00:01
Output: 5.5

Input: 12:30
Output: 165

Input: 6:00
Output: 180

Input: 23:59
Output: 5.5

```

# Answer
# JavaScript (ES6),  ~~41 40~~  39 bytes

Takes inputs as `(h)(m)`.

```
h=>m=>((x=4+h/3-m*.55/9)&2?12-x:x)%4*90

```

Try it online!

### How?

Instead of working directly in the range \\$\[0..360\]\\$, we define a temporary variable \\$x\\$ in the range \\$\[0..4\]\\$:

$$x=\left|\frac{4h}{12}+\frac{4m}{60\times12}-\frac{4m}{60}\right|\bmod 4$$ $$x=\left|\frac{4h}{12}-\frac{44m}{60\times12}\right|\bmod 4$$ $$x=\left|\frac{h}{3}-\frac{11m}{180}\right|\bmod 4$$

The angle in degrees is given by:

$$\min(4-x,x)\times90$$

However, the formula is implemented a bit differently in the JS code, as we definitely want to avoid using the lengthy `Math.abs()` and `Math.min()`.

Instead of computing the absolute value, we force a positive value in \\$\[0..12\]\\$ by computing:

$$x'=4+\frac{h}{3}-\frac{11m}{180}$$

And instead of computing the minimum, we determine in which case we are by simply doing a bitwise AND with \\$2\\$ -- and this is why we chose an interval bounded by a power of \\$2\\$ in the first place.
> 14 votes

# Answer
# Jelly, ~~14~~ 12 bytes

```
×“<¿‘Iæ%Ø°AH

```

Try it online!

A monadic link which takes the time as a list of two integers: hour, minute.

Thanks to @JonathanAllan for saving 2 bytes!

### Explanation

```
×“<¿‘        | Multiply hour by by 60 and minute by 11
     I       | Find difference
      æ%Ø°   | Symmetric mod 360 [equivalent to (x + 360) mod 720 - 360]
          A  | Absolute
           H | Half

```
> 5 votes

# Answer
# MATL, 18 bytes

```
30*i5.5*-t360-|hX<

```

Accepts two inputs of hours followed by minutes. Uses the same method as this answer

Try it at MATL Online

**Explanation**

```
      % Implicitly grab first input (hours)
30*   % Multiply by 30
i     % Explicitly grab second input (minutes)
5.5*  % Multiply by 5.5
-     % Take the difference
t     % Duplicate the result
360-  % Subtract 360
|     % Take the absolute value
h     % Horizontally concatenate
X<    % Determine the minimum value
      % Implicitly display the result

```
> 4 votes

# Answer
# Wolfram Language (Mathematica), ~~30~~ ~~29~~ 28 bytes

```
5Abs@Mod[#.{6,-1.1},72,-36]&

```

Try it online!

ungolfed version:

```
Abs[Mod[#.{30,-5.5}, 360, -180]] &

```

The argument of the function is `# = {h,m}` containing the hour and the minute. This length-two list is interpreted as a vector and the dot-product with `{30,-5.5}` is calculated: `#.{30,-5.5} = 30*h-5.5*m`. Then we calculate the symmetric modulus of 360 with `Mod[#.{30,-5.5}, 360, -180]` giving an angle in the interval -180..+180. `Abs` takes the absolute value thereof.

As all involved operators are linear, we can multiply and divide all appearing numbers however they are most convenient. By pulling a factor of `5` out of the expression and dividing all numbers in the expression by 5, the byte-count is minimized.
> 4 votes

# Answer
# Alchemist, 134 bytes

```
_->In_h+In_m+720d+360a+f
h->60d
m+11d->
0m+d+a+0r->b
0a+0x->r
d+b+r->r+a
r+0b->
b+0d+0h+0y->5y
b+0d+5y->x
0b+0d+f->Out_x+Out_"."+Out_y

```

Try it online!

## Explanation

```
_->In_h+In_m+720d+360a+f

```

Initial setup. Inputs hours and minutes into `h` and `m`, sets current angle `d` to 360 degrees (720 half-degrees), sets up `a` to compute the principal angle, and sets the output flag.

```
h->60d
m+11d->

```

Each hour adds 30 degrees, and each minute subtracts 5.5 degrees.

```
0m+d+a+0r->b
0a+0x->r

```

While the `r` (reverse) flag is not set, each `d` atom should move one `a` atom to `b`. This occurs after the minutes are all used up, to avoid a "race condition". When there are no `a` atoms remaining, set `r` to reverse this flow.

Note that this second rule can trigger multiple times, and can even trigger before the initial setup rule. This does not harm anything, so there's no need to prevent this. The `0x` condition handles an edge case: when the input is 6:00, there are no `a` atoms when the program terminates, but there are `x` atoms if the final result is at least 1 degree.

```
d+b+r->r+a
r+0b->

```

The reverse: when the signed angle is greater than 180 degrees, move `b` atoms to `a` to decrease the angle to output. Stop reversing when the angle reaches "360".

```
b+0d+0h+0y->5y
b+0d+5y->x

```

When all of the degree atoms are used up, divide by 2 to get the angle to output.

```
0b+0d+f->Out_x+Out_"."+Out_y

```

After this is done, output exactly once using the `f` flag from the initial setup.
> 3 votes

# Answer
# Python 3.8 (pre-release), ~~45~~ 43 bytes

-2 bytes thanks to Erik.

```
lambda h,m:min(x:=abs(h%12*30-m*5.5),360-x)

```

Try it online!

`h%12` \- hour in 12-hour format
`h%12*30` \- angle of hour hand at the full hour
`m/2` \- angle the hour hand moved in `m` minutes
`h%12*30+m/2` \- current position of the hour hand as an angle
`m*6` \- angle of the minute hand (`360°/60 = 6°`)
> 3 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~47~~ 45 bytes

```
h=>m=>(h=(360+h%12*30-m*5.5)%360)<180?h:360-h

```

Try it online!
> 3 votes

# Answer
# Stax, 15 bytes

```
Ç╢e╛╦¡uøßmì♪║└├

```

Run and debug it

* `m =` number of minutes since midnight
* `d = 5.5 * m`
* The result is `min(d % 360, -d % 360)`.
> 3 votes

# Answer
# Charcoal, 22 bytes

```
Ｉ↔⁻¹⁸⁰﹪⁻×³⁰⁺⁶Ｎ×⁵·⁵Ｎ³⁶⁰

```

Try it online! Link is to verbose version of code. Takes input as two integers. Explanation:

```
             Ｎ          First input
           ⁺⁶           Plus literal 6
        ×³⁰             Multiplied by literal 30
       ⁻                Minus
                  Ｎ     Second input
              ×⁵·⁵      Multiplied by literal 5.5
      ﹪            ³⁶⁰  Modulo literal 360
  ⁻¹⁸⁰                  Subtracted from literal 180
 ↔                      Absolute value
Ｉ                       Cast to string
                        Implicitly print

```
> 2 votes

# Answer
# Perl 6, 28 bytes

```
((*/3-*/9*.55+2)%4-2).abs*90

```

Try it online!

Uses a few tricks stolen from other answers and calculates

```
r = abs((h/3 - m/9*0.55 + 2) % 4 - 2) * 90
  = abs((h*30 - m*5.5 + 180) % 360 - 180)

```
> 2 votes

# Answer
# Tcl, ~~71~~ ~~74~~ ~~59~~ 54 bytes

```
{{h m {x (60*$h-$m*11)%720}} {expr min($x,720-$x)/2.}}

```

Try it online!

saved 5 bytes by using a lambda expression
> 2 votes

# Answer
# Python 3, 40 bytes

```
lambda h,m:180-abs(180-(h*30-m*5.5)%360)

```

Try it online!

`h*30` \- angle between noon and the hour `h` when the minute is `0`; if the hour is equal or greater than 12, this angle can be equal or greater than 360°
`m*6` \- angle between noon and the minute hand
`m*.5` \- angle the hour hand moved forward from the full hour after `m` minutes (e.g: if it's 4:24, the hour hand moved forward 12 degrees from the position it was in at 4 o'clock)
`h*30-m*5.5` \- one of the two angles between the hour hand and the minute hand; the coefficient for `m` is `5.5` because `m*6-m*.5=m*5.5`; this is still not the answer because it can be a value greater than 360° (e.g: if `h,m=13,0`) or less than 0° (e.g: if `h,m=12,30`)
`(h*30-m*5.5)%360` \- this modulo takes into account the cases where the computed value above is not between 0 and 360°; this is still not the answer because it could be the ampler of the two angles, while we want the most narrow
`180-abs(180-(h*30-m*5.5)%360)` \- this is the final result; the general rule is that `x-abs(x-y)` is equivalent to `min(y,x-y)`, which would give the correct result
> 2 votes

# Answer
# Python 3, ~~58~~ 57 Bytes

-1/-2 Thanks to @Shaggy

```
h,m=eval(input())
x=(30*h-5.5*m)
print(abs(min(x,360-x)))

```

Naive implementation, takes input in the form of `[6,32]`. Some bytes can probably be shaved off the last line especially.

# Python 2, ~~52~~ 50 Bytes

```
h,m=input()
x=(30*h-5.5*m)
print abs(min(x,360-x))

```
> 1 votes

# Answer
# Japt, 16 bytes

```
*FÑ aV*5½
mUa360

```

Try it

```
*FÑ aV*5½     :Implicit input of integers U=h and V=m
*F            :Multiply U by 15
  Ñ           :Multiply by 2
    a         :Absolute difference with
     V*5½     :V multiplied by 5.5
mUa360        :Reassign to U
m             :Minimum of U and
 Ua360        :Absolute difference of U and 360

```
> 1 votes

# Answer
# Perl 5 `-MList::Util=min -p`, 37 bytes

```
$_=abs<>*5.5-$_%12*30;$_=min$_,360-$_

```

Try it online!

Takes input as hours followed by minutes on a separate line because it saved a few bytes.
> 1 votes

# Answer
# 05AB1E, 16 bytes

```
60*+5.5*D(‚360%ß

```

Takes hours as first input, minutes as second.

Try it online or verify all test cases.

**Explanation:**

Basically implements the following formula:

$$t = (60h+m)×5.5$$ $$r = min(t\bmod360,-t\bmod360)$$

```
60*               # Multiply the (implicit) hours-input by 60
   +              # Add it to the (implicit) minutes-input
    5.5*          # Multiply it by 5.5
        D(‚       # Pair it with it's negative
           360%   # Take modulo-360 on both
               ß  # And then pop and push the minimum of the two
                  # (which is output implicitly as result)

```
> 1 votes

# Answer
# \[R\] , 45 bytes

```
 function(h,m)min(t=(60*h+m)*5.5%%360,-t%%360)

```
> 1 votes

# Answer
## \>\<\>, 17 bytes

```
b*$6a**-:0)12,-*n

```

Try it online! (6:32)

Takes input as h, m on the stack.

### Explanation

```
b*$6a**-:0)12,-*n
b*                Multiplies m by 11
  $               Swaps m & h
   6a**           Multiplies h by 60
       -          Subtracts m & h (v)
        :0)       Checks if v > 0 (b=0/1)
           12,-   Subtracts .5 from b (-.5/.5)
               *  Multiplies v by b (halve & abs)
                n Outputs result
b*                Errors

```
> 0 votes

# Answer
## Pyret, 59 bytes

```
{(h,m):x=(30 * h) - (m * 5.5)
num-abs(num-min(x,360 - x))}

```
> 0 votes

---
Tags: code-golf, math, number, date
---


title: Reverse Cat Programme

text:
# Question
Title: Reverse Cat Programme
Simple problem, create a programme that takes one input, and the outputs that input in reverse.

Some test cases are \[input -\> output\]:

```
 Hello World! -> !dlroW olleH
 Code Golf -> floG edoC
 Reverse Cat Programme -> emmarporG taC esreveR

```

Shortest answer wins

Note: It doesn’t have to support multi-line inputs and it doesn’t matter how input is taken

# Answer
## Keg, ~~4~~ 1 byte

This is in the documentation:

```
^

```

The mechanism is simple: Reverse the whole stack. The stack is in fact a string, and input will trivially be the items in the stack.

There isn't an online implementation; download the Python interpreter and run this program, with the input prepending the `^`.
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~30~~, 29 bytes

```
s=>string.Concat(s.Reverse())

```

Try it online!
> 2 votes

# Answer
# Whitespace, 80 bytes

```
[S S S N
_Push_0][N
S S N
_Create_Label_LOOP][S N
S _Duplicate_top][S N
S _Duplicate_top][T N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve_input][S S S T    S T S N
_Push_10][T S S T   _Subtract][N
T   S S N
_If_0_Jump_to_Label_PRINT_LOOP][S S S T N
_Push_1][T  S S S _Add][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT_LOOP][S S S T   N
_Push_1][T  S S T   _Subtract][S N
S _Duplicate_top][T T   T   _Retrieve_input][T  N
S S _Print_as_character][N
S N
S N
_Jump_to_Label_PRINT_LOOP]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Since Whitespace inputs one character at a time, the input should contain a trailing newline so it knows when to stop reading characters and the input is done.

Try it online (with raw spaces, tabs, and new-lines only).

**Explanation in pseudo-code:**

```
Integer i = 0

Start LOOP:
  Read STDIN as character, and store at heap-address i
  Character c = character at heap-address i
  If(c == '\n'):
    Jump to PRINT_LOOP
  i = i + 1
  Go to next iteration of LOOP

function PRINT_LOOP:
  i = i - 1
  Character c = character at heap-address i
  Print c as character to STDOUT
  Go to next iteration of PRINT_LOOP

```
> 2 votes

# Answer
# APL (Dyalog Unicode), 1 byteSBCS

Anonymous tacit prefix function.

Try it online!

Do I need to explain this?
> 1 votes

# Answer
# 05AB1E, 1 byte

```
R

```

Try it online!
> 1 votes

# Answer
# Japt, 1 byte

```
Ô

```

`w` also works.

Try it
> 1 votes

# Answer
# ZX81 BASIC (Timex TS-1000/1500, ZX80 with 8K ROM etc... assuming sting input only) 87 tokenized BASIC bytes

```
 1 INPUT A$
 2 LET B$=""
 3 FOR I=LEN A$ TO 1 STEP -1
 4 LET B$=B$+A$(I)
 5 NEXT I
 6 PRINT A$;"->";B$

```

Very simple, enter a string (stored in `A$`) which is then transferred one character at a time to `B$` from the last to first character in the `FOR/NEXT` loop between lines 3 through 5 inclusive.

Output is shown on line 6.
> 1 votes

# Answer
# Haskell, 7 bytes

I think it is self explanatory.

```
reverse

```

Try it online!
> 1 votes

# Answer
## Pyret, 65 bytes

```
{(x):string-from-code-points(string-to-code-points(x).reverse())}

```

Unfortunately Pyret doesn’t have a built in string reverse function, so you have to convert it to a list, reverse it, and convert it back.
> 1 votes

# Answer
# Java 8, 14 bytes

```
s->s.reverse()

```

I/O is a `StringBuilder`.

Try it online.

**35 bytes with `String` as I/O instead:**

```
s->new StringBuffer(s).reverse()+""

```

Try it online.
> 1 votes

# Answer
# Dart, 34 bytes

```
f(s)=>s.split('').reversed.join();

```

Try it online!

Pretty convoluted, you have to get a String List then reverse it and join it back for it to work.
> 1 votes

# Answer
# Octave, 11 bytes

```
@(a)flip(a)

```

Try it online!
> 1 votes

# Answer
# Jelly, 1 byte

```
U

```

Try it online!

would also work here.
> 1 votes

# Answer
# Python 3 (or 2), 16 bytes

```
lambda x:x[::-1]

```

Try it online!

Lambda that reverses its input
> 1 votes

---
Tags: code-golf
---


title: Find the closest three-digit hex colour

text:
# Question
Title: Find the closest three-digit hex colour
In CSS, colours can be specified by a "hex triplet" - a three byte (six digit) hexadecimal number where each byte represents the red, green, or blue components of the colour. For instance, `#FF0000` is completely red, and is equivalent to `rgb(255, 0, 0)`.

Colours can also be represented by the shorthand notation which uses three hexadecimal digits. The shorthand expands to the six digit form by duplicating each digit. For instance, `#ABC` becomes `#AABBCC`.

Since there are fewer digits in the hex shorthand, fewer colours can be represented.

## The challenge

Write a program or function that takes a six digit hexadecimal colour code and outputs the closest three-digit colour code.

Here's an example:

> * Input hex code: #28a086
> * Red component
>     + 0x28 = 40 (decimal)
>     + 0x22 = 34
>     + 0x33 = 51
>     + 0x22 is closer, so the first digit of the shortened colour code is 2
> * Green component
>     + 0xa0 = 160
>     + 0x99 = 153
>     + 0xaa = 170
>     + 0x99 is closer, so the second digit is 9
> * Blue component
>     + 0x86 = 134
>     + 0x77 = 119
>     + 0x88 = 136
>     + 0x88 is closer, so the third digit is 8
> * The shortened colour code is #298 (which expands to #229988)

Your program or function must accept as input a six digit hexadecimal colour code prepended with `#` and output a three digit colour code prepended with `#`.

## Examples

* #FF0000 → #F00
* #00FF00 → #0F0
* #D913C4 → #D1C
* #C0DD39 → #BD3
* #28A086 → #298
* #C0CF6F → #BC7

## Scoring

This is a code-golf challenge, so shortest answer in your language wins! Standard rules apply.

# Answer
# JavaScript (ES6), 55 bytes

```
s=>s.replace(/\w./g,x=>(('0x'+x)/17+.5|0).toString(16))

```

Try it online!
> 4 votes

# Answer
# 05AB1E, 13 bytes

```
ćs2ôH8+17÷hJ«

```

**Try it online!**

### How?

```
ćs2ôH8+17÷hJ« | string, S   e.g. stack: "#B23F08"
ć             | decapitate              "B23F08", "#"
 s            | swap                    "#", "B23F08"
  2           | two                     "#", "B23F08", 2
   ô          | chuncks                 "#", ["B2", "3F", "08"]
    H         | from hexadecimal        "#", [178, 63, 8]
     8        | eight                   "#", [178, 63, 8], 8
      +       | add                     "#", [186, 71, 16]
       17     | seventeen               "#", [186, 71, 16], 17
         ÷    | integer divide          "#", [10, 4, 0]
          h   | to hexadecimal          "#", ["A", "4", "0"]
           J  | join                    "#", "A40"
            « | concatenate             "#A40"
              | print top of stack

```
> 8 votes

# Answer
# Japt, 16 bytes

```
r"%w"²_n16_r17Ãg

```

Try it or run all test cases

```
r"%w"²_n16_r17Ãg     :Implicit input of string
r                    :Replace
 "%w"                :RegEx /\w/g
     ²               :Duplicate, giving /\w\w/g
      _              :Pass each match through a function
       n16           :  Convert to decimal
          _          :  Pass through the following function, and convert back to hex
           r17       :    Round to the nearest multiple of 17
              Ã      :  End function
               g     :  Get first character

```
> 6 votes

# Answer
# 8088 Assembly, IBM PC DOS, ~~59~~ 58 bytes

**Unassembled listing:**

```
BE 0082     MOV  SI, 82H    ; SI to begining of input string
AC          LODSB           ; load first '#' char into AL
B4 0E       MOV  AH, 0EH    ; BIOS display char function
CD 10       INT  10H        ; call BIOS
B3 11       MOV  BL, 17     ; set up for divide by 17
B9 0304     MOV  CX, 0304H  ; hex byte loop counter (CH=3), shift counter (CL=4)
        LOOP_BYTE:
AD          LODSW           ; load next two ASCII hex chars into AX
B7 02       MOV  BH, 2      ; hex chars loop counter
        LOOP_ALPHA:
2C 30       SUB  AL, '0'    ; convert from ASCII
3C 0A       CMP  AL, 10     ; is digit > 10 (A-F)?
7C 02       JL   NOT_ALPHA  ; if not, jump to next char
2C 07       SUB  AL, 7      ; ASCII adjust alpha char to binary
        NOT_ALPHA:
86 E0       XCHG AH, AL     ; swap first and second chars
FE CF       DEC  BH         ; decrement loop counter
75 F2       JNZ  LOOP_ALPHA ; loop to next hex char
D2 E0       SHL  AL, CL     ; shift low nibble to high nibble
02 C4       ADD  AL, AH     ; add first and second nibbles
32 E4       XOR  AH, AH     ; clear AH for add/division
05 0008     ADD  AX, 8      ; add 0.5 (8/16) to round (with overflow)
F6 F3       DIV  BL         ; divide by 17
3C 0A       CMP  AL, 10     ; is digit > 10?
7C 02       JL   DISP_CHAR  ; if not, jump to display digit
04 07       ADD  AL, 7      ; binary adjust alpha char to ASCII
        DISP_CHAR:
04 30       ADD  AL, '0'    ; convert to ASCII
B4 0E       MOV  AH, 0EH    ; BIOS display char function
CD 10       INT  10H        ; call BIOS
FE CD       DEC  CH         ; decrement loop counter
75 D4       JNZ  LOOP_BYTE  ; loop to next hex byte
C3          RET             ; return to DOS

```

Standalone PC DOS executable. Input is via command line, output is to console.

Most of the code length is handling the conversion of required hex string I/O into bytes, since DOS/x86 machine code has no built-ins for that.

**I/O:**

Download and test HEXCLR.COM, or `xxd` hexdump:

```
0000000: be82 00ac b40e cd10 b311 b904 03ad b702  ................
0000010: 2c30 3c0a 7c02 2c07 86e0 fecf 75f2 d2e0  ,0<.|.,.....u...
0000020: 02c4 32e4 0508 00f6 f33c 0a7c 0204 0704  ..2......<.|....
0000030: 30b4 0ecd 10fe cd75 d4c3                 0......u..

```
> 5 votes

# Answer
# Retina 0.8.2, 88 bytes

```
(\w)(.)
$1,$2;
[A-F]
1$&
T`L`d
\d+
$*
+`1,
,16$*
,
8$*
(1{17})*1*;
$#1;
T`d`L`1\d
B\B|;

```

Try it online! Link includes test cases. Explanation:

```
(\w)(.)
$1,$2;

```

Pair up the hex digits.

```
[A-F]
1$&
T`L`d

```

Convert each digit separately to decimal.

```
\d+
$*

```

Convert each decimal digit to unary.

```
+`1,
,16$*

```

Finish the hexadecimal conversion of the pair of digits.

```
,
8$*
(1{17})*1*;
$#1;

```

Add 8 and divide by 17.

```
T`d`L`1\d
B\B|;

```

Convert back to hexadecimal.
> 3 votes

# Answer
# PHP, ~~75~~ 67 bytes

```
#<?php for($m=3;$m;)echo dechex((hexdec($argn)>>--$m*8&255)/17+.5);

```

Try it online! or verify all test cases.
> 3 votes

# Answer
# Python 3, ~~72~~ ~~70~~ 68 bytes

```
lambda x:'#'+''.join(f"{(int(x[i:i+2],16)+8)//17:X}"for i in(1,3,5))

```

Try it online!

This is a port of Grzegorz Oledzkis original answer, which I helped him golfing down.

Two features of Python 3 help us save bytes:

* Floating point division by default
* Format string literals

*-2 bytes thanx to Jonathan Allan*
> 3 votes

# Answer
# Jelly, ~~20~~ 19 bytes

```
ḊØHiⱮs2ḅ⁴+8:17ịØHṭḢ

```

Try it online!
> 3 votes

# Answer
# C# (Visual C# Interactive Compiler), 81 bytes

```
x=>"".Aggregate("#",(a,b)=>a+$"{(Convert.ToInt32(x[b]+""+x[b+1],16)+8)/17:X}")

```

Try it online!
> 2 votes

# Answer
# Wolfram Language (Mathematica), ~~63~~ 48 bytes

```
"#"<>Round[15List@@RGBColor@#]~IntegerString~16&

```

Try it online!

-15 bytes thanks to attinat! Replacing `StringJoin` with `<>` and compressing the syntax.

1. `RGBColor@#` converts the input string to a color of the form `RGBColor[r, g, b]` with three floating-point arguments in the range 0..1.
2. `Round[15 List @@ %]` multiplies the list of three arguments by 15 and rounds them to the nearest integer. We now have a list of three integer values corresponding to the three desired hexadecimal digits.
3. `%~IntegerString~16` converts this list of three integers to a list of three hexadecimal strings of one character each.
4. `"#"<>%` prepends a `#` character and joins all these characters together.
> 2 votes

# Answer
# MathGolf, ~~19~~ 12 bytes

```
╞2/¢8+F/¢'#▌

```

Output as character-list. If this is not allowed, an additional trailing `y` has to be added to join the character-list to a string.

-7 bytes thanks to *@maxb*, since I looked past a builtin (`2ô_2<\1>]` to `2/`).

Try it online.

**Explanation:**

```
╞              # Remove the first character from the (implicit) input-string
 2/            # Split the string into parts of size 2
   ¢           # Convert each part from hexadecimal to integer
    8+         # Add 8 to each integer
      F/       # Integer-divide each integer by 17
        ¢      # Then convert back from integer to hexadecimal
         '#▌  '# Prepend '#' in front of the list
               # (which is output implicitly as result)

```
> 2 votes

# Answer
## Ruby (2.5.3), 45, 44, 42 bytes

```
->a{a.gsub(/\w./){|b|"%X"%((8+b.hex)/17)}}

```

EDIT: saved one byte because we don't need a character group for the second character in the regex (inspired by Neil's answer)

EDIT 2: saved 2 bytes because the dash rocket lambda syntax doesn't need brackets around the argument
> 2 votes

# Answer
## Python 2 (109 101 97 85 83 74 bytes)

```
lambda x:'#'+''.join(hex(int(int(x[i:i+2],16)/17.+.5))[2:]for i in[1,3,5])

```

The "nearest distance" is handled by division by 17 and rounding.

Improvements:

-8 bytes by using the `int(...+.5)` trick instead of `int(round(...))`

-4 bytes by using list comprehension instead of `map()`

-1 byte by hardcoding `#` in the output (thanks @movatica)

-10 bytes by not using `re.findall("..",...)` in favor of explicit String splicing

-2 bytes by not using list comprehension, but an inline generator expression in `join` (thanks @movatica)

-1 byte by not splicing the `:7` ending for blue part

-9 bytes by better iteration over colors - i.e. iterating over indices, not actual characters (thanks @movatica)
> 1 votes

# Answer
# Perl 5 `-p`, ~~35~~ 34 bytes

*@nwellnhof saved a byte*

```
s|\w.|sprintf'%X',.5+(hex$&)/17|ge

```

Try it online!

Reads from STDIN, replaces each pair of items that is not `#` with the appropriate single character using the division by 17 method for finding the nearest, then implicitly outputs (`-p`) the result.
> 1 votes

# Answer
# Python 3, 67 bytes

```
f=lambda x:(f(x[:-2])if x[3:]else"#")+f'{(int(x[-2:],16)+8)//17:X}'

```
> 1 votes

# Answer
# , 57 bytes

```
cat("#",sprintf("%x",(col2rgb(scan(,""))+8)%/%17),sep="")

```

Try it online!
> 0 votes

# Answer
# Red, 103 bytes

```
func[c][r: to 1 c to #1 rejoin reverse collect[loop 3[keep to-hex/size r % 256 + 8 / 17 1 r: r / 256]]]

```

Try it online!

It turned out that the current Linux version of Red doesn't have an implementation of the `hex-to-rgb` function, that's why I make the base conversion "manually" :)

# This works fine in the Red GUI console on Windows:

# Red, 94 bytes

```
f: func[c][r: hex-to-rgb c to #1 rejoin collect[repeat n 3[keep to-hex/size r/:n + 8 / 17 1]]]

```
> 0 votes

# Answer
# Perl 6, 35 bytes

```
{S:g[\w.]=fmt :16(~$/)/17+.5: '%X'}

```

Try it online!
> 0 votes

# Answer
# Charcoal, 22 bytes

```
#Ｆ⪪⮌…⮌Ｓ⁶¦²⍘÷⁺⁸⍘ι¹⁶¦¹⁷φ

```

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

```
#                       Literal `#`
      Ｓ                 Input string
     ⮌                  Reversed
    …  ⁶                Truncated to length 6
   ⮌                    Reversed
  ⪪      ²              Split into pairs of characters
 Ｆ                      Loop over each pair
               ι        Current pair
              ⍘ ¹⁶      Convert from base 16
            ⁺⁸          Add 8
           ÷       ¹⁷   Integer divide by 17
          ⍘          φ  Convert to large base
                        Implicitly print

```
> 0 votes

# Answer
# Pyth, 20 bytes

```
+\#sm.H/+8id16 17c3t

```

Try it here.

NOTE: In case the link above raises an `ImportError`, go here instead; there is currently a bug in the "official" page, and this is a temporary solution by Maltysen. This link may stop working after the official one is fixed.
> 0 votes

# Answer
# Forth (gforth), 87 bytes

```
: f d>s 1- hex ." #"3. do 2 + dup 2 s>number d>s 17 /mod swap 8 > - 1 .r loop decimal ;

```

Try it online!

### Explanation

1. Ignore/truncate first character of input (`#`)
2. Set interpreter to hexadecimal mode
3. Output `#`
4. Loop 3 times, in each loop:
    1. Add 2 to string starting address
    2. Convert next 2 characters in string to a hexadecimal number
    3. Use division and module by 17 (`0x11`) to get closest value for shortened component
    4. Output with no preceding space
5. Set interpreter back to Decimal mode

### Code Explanation

```
: f                    \ start a new word definition
  d>s                  \ convert double-length int to single-length (cheaper drop)
  1- hex               \ subtract 1 from string address, set current base to 10
  ." #"                \ output #
  3. do                \ start a loop from 0 to 2 (inclusive)
    2 + dup            \ add 2 to string starting address and duplicate
    2 s>number         \ parse the next 2 characters to a hexadecimal value
    d>s                \ convert result to single-length value
    17 / mod           \ get the quotient and remainder of dividing by 17
    swap               \ move the remainder to the top of the stack
    8 > -              \ if remainder is greater than 8, add 1 to quotient
    1 .r               \ output result (as hexadecimal) with no space
  loop                 \ end the loop
  decimal              \ set interpreter back to base 10 (decimal)
;                      \ end the word definition

```
> 0 votes

# Answer
# Stax, 13 bytes

```
Ç┤!usτ╓♪╩⌂^÷◙

```

Run and debug it
> 0 votes

# Answer
# K4, 39 bytes

**Solution:**

```
"#",{x@_1%17%8+16/:x?y}[.Q.nA]@/:3 2#1_

```

**Explanation:**

Uses the same strategy as a lot of these answers (i.e. add 8, divide by 17):

```
"#",{x@_1%17%8+16/:x?y}[.Q.nA]@/:3 2#1_ / the solution
                                     1_ / drop first character
                                 3 2#   / reshape as 3x2 (e.g. "FF", "00", "00")
                              @/:       / apply each-right to left lambda
    {                 }[     ]          / lambda with first argument populated
                        .Q.nA           / "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                   x?y                  / get index of hex character, e.g. "AA" => 10 10
               16/:                     / convert from base-16
             8+                         / add 8
          17%                           / 17 divided by...
        1%                              / 1 divided by...
       _                                / floor
     x@                                 / index into .Q.nA to get hex character
"#",                                    / prepend "#"

```

**Extra:**

* `"#",{x@*16\:a?&/a:abs(17*!16)-16/:x?y}[.Q.nA]@/:3 2#1_` \- my original idea for **54 bytes**
> 0 votes

---
Tags: code-golf, hexadecimal, color
---


# Question
Title: Multiplication in Brainfuck - minimum number of evaluations
Given two numbers in tape location #0 and tape location #1 in Brainfuck, compute their product into another tape location (specify with answer). Optimize for the least amount of time-units used, where the interpretation of any command uses one time-unit. As example, here is a quick C++ program to determine the number of time-units used by a Brainfuck program:

```
#include <iostream>
#include <fstream>
#include <stack>
#include <algorithm>
#define MEMORY 10000
#define DATATYPE uint32_t
#define ALWAYSPOSITIVE true

DATATYPE tape[MEMORY];
int loc, instp;

int main(int argc, char* argv[]) {
    std::string infile = "a.bf";
    bool numeric = false;
    bool debug = false;
    std::string flag;
    for(int i=1; i<argc; i++) {
        std::string arg = argv[i];
        if(arg[0] == '-') flag = arg;
        else {
            if(flag == "-i" || flag == "--in") infile = arg;
        }

        if(flag == "-n" || flag == "--numeric") numeric = true;
        if(flag == "-d" || flag == "--debug") debug = true;
    }
    if(infile == "") {
        std::cerr << "Fatal: no input file specified. Usage: ./pp2bf -i <file> [-n] [-d]" << std::endl;
        return 1;
    }
    std::ifstream progf(infile);
    std::string prog; std::string line;
    std::stack<int> loop;
    while(progf >> line) prog += line;
    instp = 0; uint64_t instc = 0, ptmove = 0, mchange = 0;
    int maxaccessedmem = 0;
    while(instp != prog.size()) {
        char inst = prog[instp];
        if(debug) {
            std::cout << inst << " #" << instp << " @" << loc;
            for(int i=0; i<=maxaccessedmem; i++)
                std::cout << " " << tape[i];
            std::cout << "\n";
        }
        if(inst == '[') {
            if(!tape[loc]) { // automatically advance to matching ]
                int n = 1;
                for(int i=instp+1;;i++) {
                    if(prog[i] == '[') n++;
                    if(prog[i] == ']') n--;
                    if(n == 0) {
                        instp = i+1;
                        break;
                    }
                }
                continue;
            }
            loop.push(instp);
        } else if(inst == ']') {
            if(tape[loc]) {
                instp = loop.top() + 1;
                continue;
            } else {
                loop.pop();
            }
        } else if(inst == '>') {
            loc++;
            maxaccessedmem = std::max(maxaccessedmem, loc);
            ptmove++;
            if(loc == MEMORY) {
                std::cerr << "Fatal: Pointer out of bounds (try increasing memory) @ instruction " << instp << std::endl;
                return 1;
            }
        } else if(inst == '<') {
            loc--;
            ptmove++;
            if(loc == -1) {
                std::cerr << "Fatal: Pointer out of bounds @ instruction " << instp << std::endl;
                return 1;
            }
        } else if(inst == '+') {
            mchange++;
            tape[loc]++;
        } else if(inst == '-') {
            mchange++;
            if(tape[loc] == 0) {
                if(ALWAYSPOSITIVE) {
                    std::cerr << "Fatal: Negative tape value at " << loc << " @ instruction " << instp << std::endl;
                    return 1;
                } else {
                    std::cerr << "Warning: Tape value at " << loc << " @ instruction " << instp << std::endl;
                }
            }
            tape[loc]--;
        } else if(inst == '.') {
            mchange++;
            if(numeric) {
                std::cout << (DATATYPE)(tape[loc]) << std::endl;
            } else {
                std::cout << (char)(tape[loc]);
            }
        } else if(inst == ',') {
            mchange++;
            if(numeric) {
                int inp; std::cin >> inp;
                tape[loc] = inp;
            } else {
                char inp; std::cin >> inp;
                tape[loc] = inp;
            }
        }
        instp++;
        instc++;
    }
    std::cout << "\nTerminated after " << instc << " time-units." << \
                 "\nMoved pointer " << ptmove << " times." << \
                 "\nChanged a memory location " << mchange << " times." << std::endl;
}

```

Note: In this implementation the tape is allotted 10K locations and each tape is an unsigned 32-bit integer - not the 8 bits used in a standard Brainfuck implementation.

For starters, here's mine:

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

```

When you compile the C++ program as `rbf`, save the Brainfuck program as `mult.bf`, run `./rbf -i mult.bf -n`, and type `1000` followed by pressing Enter twice, the following output appears:

```
1000000

Terminated after 17011009 time-units.
Moved pointer 12006004 times.
Changed a memory location 5001003 times.

```

Your goal is to minimize the first value (i.e. `17011009`). In case of ties minimize the second (`12006004`) and then the third (`5001003`).

The standard test case is

```
1000
1000

```

However, your code shouldn't be optimized for this test case only, but expend minimal time-units for any two numbers.

EDIT: For well-formedness, and not hardcoding an answer, take the sum of the expended time units in all test cases

```
x
x

```

where x = 900...1000 inclusive to get the final time units expended.

# Answer
# 7,009,011 timesteps for \\$1000\*1000\\$

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

```

Try It Online!

This increases the counter on both the initial transfer and the second transfer back to the original position. This makes it almost the same efficiency for both orderings of the input, for example, \\$100\*1000\\$ is \\$709011\\$ steps, while \\$1000\*100\\$ is \\$700911\\$ steps.

I'm not really sure I want to attempt calculating sum of the given test cases.
> 2 votes

---
Tags: math, fastest-code, optimization, brainfuck
---


title: Tips for golfing in Grass

text:
# Question
Title: Tips for golfing in Grass
What general tips do you have for golfing in Grass? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Grass (e.g. "remove no-op characters" is not an answer).

Please post one tip per answer.

# Answer
# Define λx.f x instead of copying f

In Grass you could usually copy something to the top of the stack to reduce the length of code referring to them.

But instead of defining the identity function and applying it:

```
wvWwwwww

```

You could define a new function that calls the original function instead:

```
wWWWWWw

```

Depending on the surrounding code and the number of items to be copied, it could be sometimes longer than the copying code. But it would likely still save you characters because it has one less item in the stack, and makes all references across this point shorter.

It doesn't work for characters that you would apply Out or Succ on them. It also cannot be used in a function. But it's likely you'll find other workarounds and make it still shorter.
> 5 votes

# Answer
# Hide intermediate values in a function

For the intermediate values in a chain of statements that only one final result is useful afterwards, you could hide all the intermediate values in a function, to not use spaces in the main stack.

If the function is pure (doesn't involve I/O), and the argument isn't used, instead of defining the function and immediately calling it, you could save one item in the stack by defining the function to apply the argument as a function to the supposed return value and delaying the call to where it is used.

That is, for such a function, its application and further uses of its return value:

```
w WWwwww WWWw WWWWw v
Ww
WWWw WWWWww

```

Apply the argument to the supposed return value in the end of the function, remove the application, and swap the function and the argument when you need to use the supposed return value later:

```
w WWwwww WWWw WWWWw WWWWw v

Www WWwww

```

If you try them as full programs, they give different results, because the function calls Out which isn't pure, and they ran twice for the two calls.
> 1 votes

# Answer
# Fluent interface for printing

It's often more useful to make the output function return itself, instead of the outputted character, when you are writing programs to print a block of hardcoded text. You could do this by quining:

```
ww WWWw WWWwww v     a = λf.λx.(Out(x);f(f))
Ww                   Out2 = a(a)

```
> 1 votes

---
Tags: code-golf, tips
---


title: Compute my Sacred Geometry

text:
# Question
Title: Compute my Sacred Geometry
In the tabletop RPG named Pathfinder, there is a feat that characters can take called Sacred Geometry, which allows a character who has it to buff their spells in exchange for doing some math: to use it, the character rolls a number of six-sided dice equal to their ranks in a particular skill, consults a table based on their spell level to determine which three prime numbers are the "Prime Constants" for that spell level, then calculates whether or not it's possible to produce one of the Prime Constants by performing some combination of addition, subtraction, multiplication, and division and parenthetical grouping on all the numbers rolled.

The table of Prime Constants by Spell Level are as follows:

```
+-------------+-----------------+
| Spell Level | Prime Constants |
+-------------+-----------------+
| 1st         | 3, 5, 7         |
| 2nd         | 11, 13, 17      |
| 3rd         | 19, 23, 29      |
| 4th         | 31, 37, 41      |
| 5th         | 43, 47, 53      |
| 6th         | 59, 61, 67      |
| 7th         | 71, 73, 79      |
| 8th         | 83, 89, 97      |
| 9th         | 101, 103, 107   |
+-------------+-----------------+

```

So, for instance, if a character has 5 skill ranks and they're casting a 4th level spell, they would roll five six-sided dice and would need to be able to calculate a value of 31, 37, or 41. If they rolled a 6, 6, 4, 3 and 1, then they could produce a value of 37 by performing the following computation: (6 × 6) + (4 – 3) × 1 = 37, or they could produce a value of 41 by doing (\[6 + 6\] × 3) + 4 + 1 = 41. As a result, their casting of the spell would succeed.

For this programming puzzle, your job is to write a function with two input parameters, Spell Level and Skill Ranks, roll a number of six-sided dice equal to the Skill Ranks parameter, then compute if you can produce (at least) one of the Prime Constants associated with the Spell Level parameter, then output a Boolean value.

Answers would be ranked primarily by the efficiency of their algorithm (I'm pretty sure that a brute force algorithm would scale very quickly as the Skill Ranks parameter increases), and then by the size of the submitted source code in bytes.

# Answer
# Python 2.7, 285 bytes

```
from itertools import*
from random import*
def f(s,r):
 p=[];n=1;k=1;P=1;d=choices('123456',k=r);D=permutations(d,r);O=product('+-*/',repeat=r-1)
 while-~s*3>n:p+=P%k*[k];n,k,P=n+P%k,k+1,P*k*k
 return any(n in{eval('int(%s)'%'%s'.join(i)%o)for i in D for o in O}for n in p[-4:-1])

```

Technically conforms to the specifications of the challenge. Only returns True/False, does not expose the dice rolls used or the expression used to caller.

Also, this algorithm ignores grouping, since we can perform the same operations without grouping by using ordering instead. (This would not be true if exponentiation was one of the possible operations, for example.)

Exponential runtime, since it generates all possibilities and then checks if at least one solution exists.
> 1 votes

---
Tags: decision-problem, random, game, combinatorics, fastest-algorithm
---


title: Reverse your code, reverse the OEIS

text:
# Question
Title: Reverse your code, reverse the OEIS
The task here is to write a program that takes an natural number, \\$n\\$, and produces the \\$n\\$th term of an OEIS sequence. That sequence should have an identifier in the form of `A` followed by 6 digits. Now when you take your source code and reverse the order of it's bytes to produce a new program, that program should also implement an OEIS sequence. The new sequence should be identified by an `A` followed by the same 6 digits as last time but in reverse order (including leading zeros).

Now to keep things from being trivial neither the OEIS identifier number nor your program can be palindromes. That is the sequences and programs should be different. You cannot choose a sequence for which it's reverse does not exist or is empty.

For each of your sequences you may choose to either use 0 or 1 indexing. They do not have to use the same indexing. Since some OEIS sequences have a limited domain you need only output the correct numbers for the domain of the sequence. Your required behavior is undefined outside of the domain (you can output `0`, crash, order a pizza, etc.).

This is so answers will be scored in bytes with fewer bytes being better.

# Answer
> 11 votes
# 05AB1E, ~~9~~ 4 bytes (A000040 and A040000)

```
Ø=>≠

```

Try it online!

!enilno ti yrT

Explanation:

```
Ø          # nth prime
 =         # output
  >≠       # ignored

```

:noitanalpxE

```
≠          # boolean negation (0 if n == 1, 1 otherwise)
 >         # increment
  =        # output
   Ø       # ignored

```

# Answer
> 4 votes
# Perl 6, 55 bytes (A055642 and A246550)

```
+*.comb#}]1-_$[)4+_$^**X]_$^[)*..2,emirp-si&(perg(tros{

```

Try it online!

This is a anonymous Whatever lambda implementing the OEIS sequence A055642 (length of the decimal representation of \\$n\\$) 0-indexed.

```
{sort(grep(&is-prime,2..*)[^$_]X**^$_+4)[$_-1]}#bmoc.*+

```

Try it online!

The reverse is the sequence A246550 (the ordered list of \\$x^e\\$ where \\$x\\$ is prime and \\$e \ge 4\\$) 1-indexed.

Most of this challenge was just finding a good sequence with a not too complicated reverse.

Update: Using torcado's answer, this can be 19 bytes (A010851 and A158010)

```
{256*$_**2-$_}#{21}

```

Try it online!

# Answer
> 2 votes
# \\/\\/\>, ~~15~~ 14 bytes (A010851 and A158010)

```
cn;n*-1*"Ā":j

```

effectively `cn`, output 12

```
j:"Ā"*1-*n;nc

```

effectively `j:"Ā"*1-*n`, n(256n-1)

thanks to a friend for finding incredibly simple sequences!

# Answer
> 1 votes
# Python 2, 59 bytes (A030000 and A000030)

```
f=lambda n,k=0:k if`n`in`2**k`else f(n,k+1)#]0[`n`:n adbmal

```

Try it online!

Defines a function `f`, returning the nth term of A030000 (smallest nonnegative number \\$k\\$ such that the decimal expansion of \\$2^k\\$ contains the string \\$n\\$), 0-indexed

```
lambda n:`n`[0]#)1+k,n(f esle`k**2`ni`n`fi k:0=k,n adbmal=f

```

Try it online!

An anonymous function returning the nth term of A000030 (Initial digit of \\$n\\$), 0-indexed

---

Shorter version, which takes strings as input (for both sequences), and both still 0-indexed:

# Python 2, 56 bytes

```
f=lambda n,k=0:`k`*(n in`2**k`)or f(n,k+1)#]0[n:n adbmal

```

Try it online!

```
lambda n:n[0]#)1+k,n(f ro)`k**2`ni n(*`k`:0=k,n adbmal=f

```

Try it online!

# Answer
> 1 votes
# Haskell, 47 bytes (A000010 and A010000)

Both sequences are relatively simple.

```
p n=sum[1|x<-[1..n],gcd x n<2]--2+n*n=n p;1=0 p

```

Try it online!

`p n` = the Euler totient function of n (A000010) (1-indexed)

Reversed:

```
p 0=1;p n=n*n+2--]2<n x dcg,]n..1[-<x|1[mus=n p

```

Try it online!

`p n` = 1 if n = 0, otherwise n^2 + 2

It would be interesting to see an answer which doesn't use comments...

---
Tags: code-golf, sequence, source-layout
---


title: How do I exit Vim?

text:
# Question
Title: How do I exit Vim?
Vim is a great text editor for unix systems, but it's notorious for being difficult to exit.

Write a full program that will output `:q` to exit Vim. It should then read a single line of input, as it will then either be given a bash prompt, in which case the exit was successful, or an error, in which case there are unsaved changes.

The bash prompt will be this:

```
E37@vimmachine: /var/override)

```

While the error will be this:

```
E37: No write since last change (add ! to override)

```

Upon being given the bash prompt, the program's work is done, and it should not give any more output (except for whitespace).

Upon being given the error, your program should randomly (ie each possibility has a non-zero probability of being chosen) output `:q!`, to exit without saving, or `:x`, to save and exit.

This is so fewest bytes **in each language** wins!

# Answer
> 16 votes
# Python 2, 66 bytes

Saved 3 bytes thanks to @Mr.Xcoder and 4 thanks to @Mayube!

```
from random import*
if'('in input(':q'):print choice([':x',':q!'])

```

Try it online!

# Answer
> 7 votes
# Ruby, 35 bytes

```
p:q
p %i(q! x)[rand 2]if/\(/=~gets

```

Try it online!

# Answer
> 6 votes
# 05AB1E, 19 bytes

```
„:q,'Nåi„:x…:q!‚.R,

```

Try it online!

```
„:q,                # Print the string ":q"
    'Nåi            # If N is in the input
        „:x         #   Push the string ":x"
           …:q!     #   Push the string ":q!"
               ‚    #   Wrap them into an array
                .R, #   Randomly print one of them

```

# Answer
> 6 votes
# Vimscript, 45 41 bytes

```
ec"q"|exe"/("|ec["q!","x"][getpid()%2]

```

Shaved off 4 bytes by using `getpid()` to get a number. (Can anyone think of a shorter way to get a number that won't be the same everywhere, all the time?)

Assuming +3 bytes for invoking Vim with `-c` to run the above script and `-` to read input from stdin:

```
vim -c 'ec"q"|exe"/("|ec["q!","x"][reltime()[1]%2]' -

```

# Answer
> 5 votes
# Python 2, ~~76~~ ~~75~~ ~~72~~ 69 bytes

**This answer has been out-golfed.**

*-1 byte thanks to Rod. -3 bytes thanks to Mayube. -3 bytes thanks to Artyer.*

```
from random import*
print'::qx!'[random()>.5:('N'in input(':q'))*5:2]

```

Try it online!

# Answer
> 3 votes
# C# (.NET Core), 140 139 138 bytes

```
using static System.Console;class P{static void Main(){Write(":q");if(ReadLine()[3]==':')Write(new System.Random().Next()>9?":x":":q!");}}

```

Try it online!

* 1 byte saved thanks to LiefdeWen!
* 1 byte saved thanks to Mord Zuber!

# Answer
> 3 votes
# \>\<\>, ~~32~~ ~~30~~ 29 bytes

* Had a redundant `!o`.
* -1 byte thanks to Aaron.

```
iii0["@!qx:q:"ooi{=?;o!ox~oo;

```

Try it online!

## Explanation (old)

```
"@!qx:q:"ooi~i~i~i{=?;o!ox~oo;
"@!qx:q:"                        Push @!qx:q: on the stack (in reverse)
         oo                      Print :q [stack: @!qx:]
           i~i~i~                Remove first 3 input characters
                 i               Load @ or : from the input (= i)
                  {              Shift stack to the left [stack: !qx:i@]
                   =?            If 4th character was @
                     ;              Exit
                                 Else
                      o             Print :
                       !o           Jump to
                         x          Random direction (left or right because
                                    up and down retrigger x)
                                       Left:
                     ;o!o                 Print x and exit.
                                       Right:
                          ~oo;            Remove x, print q! and exit.

```

(will update soon)

# Answer
> 3 votes
## JavaScript, ~~52~~ 46 bytes

*Saved 6 bytes thanks to @ETHProductions*

```
prompt(':q')[30]&&alert(new Date%2?':q!':':x')

```

# Answer
> 2 votes
# Actually, 27 bytes

```
":q"ü[":x",":q!"]`⌂`J'!,cIƒ

```

Try it online! (Note: As TIO doesn't play nice with stdin, I've replaced the `,` (read from stdin) with the literal string, which you can change to test it. Also, you'll need to disable output cache in order to get a different response with the random output.)

Explanation:

```
":q"ü[":x",":q!"]`⌂`J'!,cIƒ
":q"ü                       - Push the literal :q and print
     [":x",":q!"]           - Push the list of literals :x and :q!
                 `⌂`J       - Push function literals ⌂ (terminate) and J (choose random element from list)
                     '!     - Push the literal !
                       ,    - Read from stdin
                        c   - Pop top two values a,b and return "a".count(b)
                         I  - Pop top three values a,b,c and return b if a is truthy and c if a is falsy
                          ƒ - Pop a function from the stack and call it

```

# Answer
> 1 votes
# APL (Dyalog), 27 bytes

```
':q'⋄('!'∊⍞)/':q!' ':x'⊃⍨?2

```

Try it online!

`':q'` print this

then

`?2` random integer among the first two

`⊃⍨` use that to select from

`':q!' ':x'` this list of two strings

`(``)/` replicate that with, i.e. make *n* copies of each element in that, where *n* is

`'!'∊⍞` is exclamation point a member of the text input? (Boolean, i.e. 0 or 1)

# Answer
> 1 votes
# JavaScript, ~~76~~ ~~71~~ 50 bytes

```
prompt(":q")[3]<"@"?alert(new Date%2?":q!":":x"):0

```

Saved a bunch of bytes thanks to Artyer and Neil, as well as condensing my ternaries and moving first alert to prompt (duh).

# Answer
> 1 votes
## Batch, 98 bytes

```
@echo :q
@set/ps=
@if %s:~3,1%==@ exit/b
@set/an=%random%%%2
@if %n%==0 (echo :x)else echo :q!

```

# Answer
> 1 votes
# Ruby, 33 bytes (32 code, +1 for -n flag)

```
p:q;$_[?!]? p([:q!,:x][$$%2]): p

```

I'm not too sure on the `$$%2` snippet. I'm using it to generate a random bit to index my array by taking the current ruby process's pid modulo 2, and it'll be fairly unpredictable. `.sample` adds an extra byte.

Try it online!

# Answer
> 1 votes
# Python 2, 64 bytes

```
import time
if'w'in input(':q'):print'::qx!'[time.time()%2>1::2]

```

Try it online!

Since this is just an agglomeration of both of these Python answers, I've marked this as community wiki.

# Answer
> 1 votes
# Python 2, 47 bytes

```
print'::qx!'[id(0)%3<2:('N'in input(':q'))*5:2]

```

**Try it online**

**Explanation:**

The source of randomness is `id(0)%3<2`. The function `id` returns the memory location of the parameter. Passing anything will give a non-deterministic memory address. The result will always be even, but it will only sometimes be divisible by 3. The results modulo 3 vary. So, this can be a source of randomness. Using `<2` means that roughly 2/3 of the time, the resulting boolean is `True`.

The rest of the answer is inspired by this one.

# Answer
> 1 votes
## Keg, ~~14~~ 12 bytes

```
\:~2%[q\!|x]

```

This pushes a random number and outputs corresondingly to the random number.

# Answer
> 0 votes
# TCL, 95 bytes

```
puts :q;puts [if [string match *!* [gets stdin]] {puts [lindex ":q! :x" [expr round(rand())]]}]

```

A simple and rather long solution in tcl...

# Answer
> 0 votes
**Assembly 86Bytes** Linux System Calls

```
global _start
_start:
mov edx,4
mov ecx,g
mov ebx,1
mov eax,4
int 0x80
g db ':q!',10

```

# Answer
> 0 votes
# LOGO, ~~37~~ 36 bytes

```
pr[:q]if 4<count rl[pr pick[:q! :x]]

```

Try it online at Anarchy Golf Performance checker.

# Explanation:

```
pr[:q]if 4<count rl[pr pick[:q! :x]]   Main program.
pr                                     Print
  [:q]                                 the list `[:q]` without delimiter `[]`
      if           [              ]    If...
         4<                            4 is less than...
           count                       the number of word in the...
                 rl                    ReadLine (from stdin),
                    pr                 print
                       pick            a random word picked from the list...
                           [:q! :x]    [:q! :x]

```

(because `E37@vimmachine: /var/override)` has 2 words, while `E37: No write since last change (add ! to override)` has 10 words)

# Answer
> 0 votes
# Perl 5 (with -E flag), 35 bytes

```
say":q";<>=~l&&say qw(:q! :x)[$$%2]

```

Run this with `perl -E 'say":q";<>=~l&&say qw(:q! :x)[$$%2]'`.

Try it online!

Ungolfed:

```
say(":q");
if(<> =~ /l/){ #read a line and check if it contains 'l'
    @a=(":q!",":x");
    say($a[$$ % 2]); #print one element from array based on PID
}

```

---
Tags: code-golf
---


title: Am I a Pillai prime?

text:
# Question
Title: Am I a Pillai prime?
A Pillai prime is a prime number \\$p\\$ for which there exists some positive \\$m\\$ such that \\$(m! + 1) \equiv 0 \\:(\text{mod } p)\\$ and \\$p \not\equiv 1\\:(\text{mod }m)\\$.

In other words, an integer \\$p\\$ is a Pillai prime if it is a prime number, if there exists another positive integer \\$m\\$ such that the factorial of \\$m\\$, plus \\$1\\$ is divisible by \\$p\\$ and if \\$p - 1\\$ isn't divisible by \\$m\\$.

---

Given a positive integer as input, decide whether it is a Pillai prime. The sequence of Pillai primes is OEIS A063980.

For example, \\$23\\$ is a Pillai prime because:

* It is a prime number, having only 2 factors.
* \\$m = 14\\$ and \\$m = 18\\$ satisfy the above conditions: \\$23 \mid (14! + 1)\\$ and \\$14\\$ does not divide \\$22\\$; \\$23 \mid (18! + 1)\\$ and \\$18\\$ does not divide \\$22\\$ either.

## Test cases

Truthy:

```
23
59
83
109
139
593

```

Falsy:

```
5
7
8
73
89
263
437

```

For the truthy cases, the respective **m**'s are `[(23, [14, 18]), (59, [15, 40, 43]), (83, [13, 36, 69]), (109, [86]), (139, [16]), (593, [274])]`.

---

You can either follow the standard output format (that is, truthy / falsy values) or have a consistent value for Pillai primes and a non-consistent value otherwise or vice-versa.

You can compete in any programming language and can take input and provide output through any standard method, while taking note that these loopholes are forbidden by default. This is , so the shortest submission (in bytes) for *every language* wins.

# Answer
> 10 votes
# Jelly, ~~11~~ 8 bytes

```
Ṗ!%ẹ’ḍ’E

```

Returns **0** for Pillai prime, **1** otherwise.

Try it online!

### How it works

```
Ṗ!%ẹ’ḍ’E  Main link. Argument: n

Ṗ         Pop; yield [1, ..., n-1].
 !        Take the factorial of each integer.
  %       Take the factorials modulo p.
   ẹ’     Find all indices of n-1.
     ḍ’   Test n-1 for divisibility by each of these indices.
       E  Return 1 if all of the resulting Booleans are equal (all 1 means there is
          no suitable m, all 0 means n is not prime), 0 if they are different.

```

# Answer
> 9 votes
# Python 2, ~~115~~ ~~111~~ ~~110~~ 109 bytes

<sup>-6 bytes thanks to Mr. Xcoder</sup>

```
lambda n:n>2and cmp(*map(all,zip(*[[n%x==1or~f(x)%n,n%x]for x in range(2,n)])))<0
f=lambda x:0**x or x*f(x-1)

```

Try it online!

The functions consist of two parts `~-n%x<1or~f(x)%n>0` that verifies if `n` **don't** satisfies the "Pillai conditions", and `n%x>0` for the prime validation.
After that `all` is applied to both items, the first item will contain `False`/`0` if there **is** a valid "Pillai number", and the second will contain `True`/`1` if `n` is prime.
These are passed to `cmp` that will return `-1` in this cenario (is a valid Pillai prime). The other combinations `[[0, 0], [1, 0], [1, 1]]` will return `0` or `1`

# Answer
> 6 votes
# Pari/GP, 44 bytes

```
p->isprime(p)&&sum(m=2,p,p%m-1&&!((m!+1)%p))

```

Try it online!

# Answer
> 5 votes
# Brachylog, 19 bytes

```
ṗ>.ḟ+₁;?%0&-₁;.%>0∧

```

Try it online!

Pretty straightforward translation of the question:

```
ṗ          Input is a prime
>.         And output is a number less than the input
ḟ+₁;?%0    And output's factorial + 1 mod input is 0
&-₁;.%>0   And input - 1 mod output is greater than 0
∧          No further constraints

```

# Answer
> 3 votes
# , 30 26 bytes

-4 bytes thanks to FrownyFrog

```
1 e.i.((|1+!)~<1~:|)1&p:*]

```

Try it online!

## Explanation:

```
                        1&p:*]      checks if the number is prime and if not sets it to 0
                   1~:|             checks if p is not 1 mod m
           (|1+!)~                  m factorial plus 1 modulo n
                  <                 are both conditions met?
       i.                           generates successive m's (a list 0..n-1)
   1 e.                             1's are at the indices of m, so if there's 1 - Pillai

```

# Answer
> 3 votes
# Python 2, ~~65~~ ~~64~~ ~~53~~ 52 bytes

```
f=lambda n,k=3,m=2:~m%n<1<n%k%(n%~-k)or f(n,k+1,m*k)

```

Output is via presence or absence of an error.

Try it online!

# Answer
> 2 votes
### as you probably can see in the tio link not all cases pass, thats because js cant handle big numbers,if such requirement exists ill try to implement it :)

there is a double check `F%n>n-2&(F+1)%n<1` to prevent false positive(but not the other way around with js big number issues,we do really need `(F+1)%n<1` for smaller numbers whice reduces the solution byte count to **60**

# JavaScript (Node.js), 90 88 86 72 68 bytes

* thanks to Arnauld for reducing by 1 byte

```
f=(n,F=i=2,g=0)=>n%i?f(n,F*=++i,g|=F%n>n-2&(F+1)%n<1&~-n%i>0):i==n*g

```

Try it online!

# Answer
> 2 votes
# Python 2, ~~109~~ 107 bytes

```
lambda p:any(~-p%m>~l(m)%p<1for m in range(2,p))*all(p%i for i in range(2,p-1))
l=lambda a:0**a or a*l(a-1)

```

Try it online!

---

**Explanation**

The `l` finds the factorial of the number passed in, so `5` as input returns `120`.

The `all(p%i for i in range(2,p-1))` checks to see if a number is prime, we ignore 0 and 1 as our other conditions already rule those out.

Finally, we use `any(~-p%m>-~l(m)%p==0for m in range(2,p))` to iterate through all potential m's looking to see if any satisfies our needs. `~-p` means `p+1`. Then we check to see if it is greater than `-~l(m)%p` (which translates to `(m!-1)%p`, and then we compare it to `0`. Basically `~-p%m` must be greater than 0 and `-~l(m)%p` must be 0.

---

**Sources**

---

**Improvements**

# Answer
> 2 votes
# Brachylog, 13 bytes

```
>.ḟ+₁ḋ∋?-₁f≡ⁿ

```

Try it online!

Succeeds for Pillai primes, providing the smallest *m* through the output variable, and fails for anything else. Since a large part of how this saves bytes over sundar's solution is that it repeatedly computes the prime factorizations of some pretty big numbers, it's quite incredibly slow on larger inputs. (I'll probably run those cases on my local Brachylog installation once my laptop isn't on battery power.)

```
 .               The output
>                is less than the input,
       ?         the input
      ∋          is an element of
     ḋ           the prime factorization of
 .               the output's
  ḟ              factorial
   +₁            plus one,
           ≡ⁿ    and the output is not an element of
          f      the list of all factors of
       ?         the input
        -₁       minus one.

```

# Answer
> 1 votes
# \[Perl\], 45 bytes

```
use ntheory":all";is_prime($n)&&is_pillai($n)

```

The number theory module has the predicates as built-in functions (is\_pillai actually returns either 0 or the smallest m, so solves A063828 as well). The underlying C and Perl code is not golfed (of course). The C code looks like:

```
UV pillai_v(UV n) {
  UV v, fac = 5040 % n;
  if (n == 0) return 0;
  for (v = 8; v < n-1 && fac != 0; v++) {
    fac = (n < HALF_WORD) ? (fac*v) % n : mulmod(fac,v,n);
    if (fac == n-1 && (n % v) != 1)
      return v;
  }
  return 0;
}

```

(generically replace UV with uint64\_t or similar, and HALF\_WORD decides whether we can optimize the mulmod into simple native ops).

The pure Perl code is similar to:

```
sub is_pillai {
  my $p = shift;
  return 0 if $p <= 2;
  my($pm1, $nfac) = ($p-1, 5040 % $p);
  for (my $n = 8; $n < $p; $n++) {
    $nfac = mulmod($nfac, $n, $p);
    return $n if $nfac == $pm1 && ($p % $n) != 1;
  }
  0;
}

```

# Answer
> 1 votes
# C (gcc), 64 bytes

```
f(n,k,m,r){for(k=m=1,r=0;k<n;m=m*++k%n)r|=m/~-n<<(n%k==1);r/=3;}

```

Try it online!

# Answer
> 1 votes
# Whispers v2, 230 bytes

```
> 1
> Input
>> 1…2
>> L!
>> L+1
>> L∣2
>> L⋅R
>> 2%L
>> Each 4 3
>> Each 5 9
>> Each 6 10
>> Each 7 11 3
> {0}
>> 12∖13
>> Each 8 14
>> L≠1
>> Each 16 15
>> Each 7 17 15
>> 18∖13
>> [19]
>> 2’
>> 21⋅20
>> Output 22

```

Try it online!

This returns an empty list for non-Pillai primes, and a non-empty list otherwise.

## How it works

Whispers was designed for manipulation on real/complex numbers, with a little bit of array commands added for good measure, hence the repeated use of `Each` to iterate over the generated lists.

**A bit of background on Whispers:**

Whispers is slightly different in it's execution path to most other languages. Rather than work through each line linearly, only branching at conditionals, Whispers begins on the last line in the file beginning with `>` (the rules are slightly more complicated than that, but that's all we need to know for now), and the meanings of numbers differ, depending on whether the line starts with `>` or `>>`.

If the line starts with `>`, such as `> 1` or `> Input`, this is a **constant** line - it returns the same value each time. Here, numbers represent their numerical form, so the first line will always return **1** when called.

If the line starts with `>>` however, numbers are treated as references to other lines, sort of like function calls, if you will. For example, in the line `>> 1…2`, this does not perform the  command on the integers **1** and **2**, but rather on the values returned from lines **1** and **2**. In this case, those values are the integer **1** and whatever integer we're passed as input.

For this example, let's consider the input of **23**. Keep in mind that, due to Whispers' preprocessing, the second line (`> Input`) is converted to `> 23`.

Our first command is on line 3: `>> 1…2`.  is dyadic range, in this case from **1** to **23**, yielding **{1, 2, ... 22, 23}**. Next, we skip down to lines **9** through **12**:

```
>> Each 4 3
>> Each 5 9
>> Each 6 10
>> Each 7 11 3

```

Here we have 4 consectutive `Each` statements, each of which iterate over the previous result, essentially mapping the 4 commands over the array on line **3**: the range. The first three statements are simple maps, with lines **4**, **5** and **6**:

```
>> L!
>> L+1
>> L∣2

```

These three commands, over an integer **n**, yields **(n!+1)∣x**, where **!** denotes factorial,  denotes divisbility and **x** is the input. Finally, line **12** has a *dyadic map* structure.

A *dyadic map* structure takes three integers: the target, the left and the right, each indexes to other lines. Here, we zip the left and the right to produce a list of pairs, then reduce each pair by the dyadic command (the target). Here, if the input is **23**, the lists are **{1, 2, ... 22, 23}** and **{0, 0, ... 1, 0}** and the command is

```
>> L⋅R

```

which multiplies the left argument by the right. This produces an array of integers, with **0** at the indexes of integers whose factorials incremented aren't divisible by the inputs, and the original index where they are. We'll call this array **A**. Next, we remove the **0**s from **A** by taking the set difference between **{0}** and **A**:

```
> {0}
>> 12∖13

```

With our example input, this produces the set **{14, 18, 22}**. Next we take the remainder of the input being divided by each value in the set, and check if that remainder is not equal to **1**:

```
>> 2%L
>> Each 8 14
>> L≠1
>> Each 16 15

```

Again, we have a list of either **0** or **1**s and need to remove the **0**s and replace the **1**s with the original values. Here we repeat the code we saw above, but with `>> 18∖13` rather than `12`. Finally, we cast this resulting set to a list for a final check. Unfortunately, our code must also reject composite numbers which achieve all these criteria, such as **437**. So we add our final check, multiplying our final list by the primality of the input. Due to how Python multiplication works on lists, **0** replaces it with an empty list, and **1** has no effect. So we calculate the primality of the input, multiply that by the list of **m**s for the input and ouput the final result:

```
>> 2’
>> 21⋅20
>> Output 22

```

# Answer
> 0 votes
# APL(NARS), 65 chars, 130 bytes

```
{∼0π⍵:0⋄m←⎕ct⋄⎕ct←0⋄r←⍬≢a/⍨{0≠⍵∣p}¨a←k/⍨0=⍵∣1+!k←⍳p←¯1+⍵⋄⎕ct←m⋄r}

```

Here 23x it would mean 23r1 and so the fraction 23/1, so all the others; test:

```
  f←{∼0π⍵:0⋄m←⎕ct⋄⎕ct←0⋄r←⍬≢a/⍨{0≠⍵∣p}¨a←k/⍨0=⍵∣1+!k←⍳p←¯1+⍵⋄⎕ct←m⋄r}
  f¨23x 59x 83x 109x 139x 593x
1 1 1 1 1 1
  f¨5x 7x 73x 89x 263x 437x
0 0 0 0 0 0

```

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), 138+22=160 bytes

```
n=>Enumerable.Range(2,n-2).All(x=>n%x>0)&Enumerable.Range(1,n).Any(x=>{BigInteger a,b=1;for(a=1;a<=x;a++)b*=a;return(b+1)%n<1&(n-1)%x>0;})

```

TIO has not implemented the System.Numerics library in it's release of Mono, so you can see the results ~~Try it online!~~ Here instead.

Explanation:

```
using System.Numerics; //necessary to handle large numbers created by the factorials

return
    Enumerable.Range(2,n-2).All(x=>n%x>0)       // is prime
    &
    Enumerable.Range(1,n).Any(x=>
    {
        BigInteger a,b=1;for(a=1;a<=x;a++)b*=a; //b = a!
        return (b+1)%n<1
               &                                //the condition for PPs
               (n-1)%x>0;
    });

```

# Answer
> 0 votes
# CJam, 37 bytes

```
ri_mp\[_{_M)m!)@%!\_M)%1=!@&\}fM]);:|

```

Outputs `11` if input is a pillai prime, otherwise `00`, `01` or `10`

**Explanation:**

```
                                         e# Explanation | Stack
ri_mp\[_{_M)m!)@%!\_M)%1=!@&\}fM]);:|    e# Whole code | Example input: 593
ri                                       e# Read input as integer | 593
  _                                      e# Duplicate | 593 593
   mp                                    e# Is it prime? | 593 1
     \                                   e# Swap top two stack elements | 1 593
      [                         ]        e# Delimits an array. Any operations that
                                         e# push a value are placed into the array
       _                                 e# Duplicate | 1 593 [593]
        {                    }fM         e# A for loop from 0 to (n-1) looped through
                                         e# variable M
         _                               e# Duplicate top stack value | ...[593 593]
          M)                             e# Get M+1, as if we try M=0 we get an error
                                         e# | ...[593 593 1]
            m!                           e# Factorial | ...[593 593 1]
              )                          e# Add one | ...[593 593 2]
               @                         e# Rotate stack | ...[593 2 593]
                %                        e# Modulus | ...[593 2]
                 !                       e# Equal to 0? | ...[593 0]
                  \_                     e# Swap and duplicate | ...[0 593 593]
                    M)                   e# Push M+1 | ...[0 593 593 1]
                      %                  e# Modulus | ...[0 593 0]
                       1=!               e# Not equal to 1? | ...[0 593 1]
                          @              e# Rotate | ...[593 1 0]
                           &             e# AND | ...[593 0]
                            \            e# Swap | ...[0 593]
                             }
                                ]
                                 );      e# Dump and discard last element
                                         e# | 1 593 [...]
                                   :|    e# Flatten array with OR | 1 1
                                         e# Implicit output

```

Try it online!

---
Tags: code-golf, math, decision-problem, number-theory, primes
---