title: Onion Programming

text:
# Question
Title: Onion Programming
Using only printable ASCII (hex codes 20 to 7E), write a square N×N *core* program **without comments** that is surrounded by 4 more *layers*, creating a (N+8)×(N+8) square program (N \> 0). For N = 3 the layout (to be replaced by actual code) looks like this:

```
44444444444
43333333334
43222222234
43211111234
4321CCC1234
4321CCC1234
4321CCC1234
43211111234
43222222234
43333333334
44444444444

```
* The C's represent the core 3×3 program.
* The 1\`s represent the first layer, the 2's represent the second layer, etc.

The program always takes a string of space separated integers such as `0 -1 31 -1 2 2 2` via stdin or similar (it should just be the plain numbers, no quotes or brackets or anything). The output depends on what parts of the layout were run.

There are five ways to run the program (newlines are included in the run). Each does something different to the list:

1. Run just the core:

```
CCC
CCC
CCC

```

This computes the maximum of the absolute values of the input list elements, and prints `CORE` on a new line that many times. If the max is 0 nothing is output (a newline is fine).

* The output for `0 -1 31 -1 2 2 2` would be

    ```
    CORE
    CORE
    ...

    ```

    31 times.
2. Run the core with layer 1:

```
11111
1CCC1
1CCC1
1CCC1
11111

```

This outputs the average (arithmetic mean) of the list values to standard floating point precision.

* The output for `0 -1 31 -1 2 2 2` would be 35 / 7 = `5` (`5.0` is fine).
3. Run the core with layers 1 and 2:

```
2222222
2111112
21CCC12
21CCC12
21CCC12
2111112
2222222

```

This outputs a space separated list of the input list reversed.

* The output for `0 -1 31 -1 2 2 2` would be `2 2 2 -1 31 -1 0`.
4. Run the core with layers 1, 2, and 3 (the pattern should be obvious).
This outputs a space separated list of the sorted input list.

* The output for `0 -1 31 -1 2 2 2` would be `-1 -1 0 2 2 2 31`.
5. Run the core with layers 1, 2, 3, and 4.
This outputs a space separated list of the input list with duplicates removed, the ordering doesn't matter.

* The output for `0 -1 31 -1 2 2 2` could be `-1 0 2 31`.

All output is to stdout or a similar alternative.

Only these 5 layout combinations have specified behavior.

### Notes

* **Comments are not allowed** in the core or layers or combinations thereof. Code that is a no-op or does nothing constructive does not count as a comment.
* Remember that the core can have any (positive) N×N dimensions, but the layers are only one character thick.
* You may assume the input has no leading or trailing spaces and exactly one space between numbers. It will always contain at least one number. (The output lists should be formatted like this too.)
* You may assume the list and calculations necessary for output won't have values that overflow (or underflow) your integers (as long as their max is something reasonable like 216).

# Scoring

Writing this program normally would be easy. Writing it with a small core is hard.

The program with the smallest core size (the smallest N) wins. In case of ties the winner is the full program (the (N+8)×(N+8) square) with the fewest distinct characters (not counting newlines).

Please report your N value at the top of your answer.

# Answer
## CJam, N = 5, 27 (26) unique characters

It's 26 characters if I don't count the spaces. The program could actually be converted to one that doesn't use spaces, by just filling up all empty spaces with no-ops (e.g. `_;` which duplicates the top stack element and then discards, or by sorting the array again and again), but it would just distract from the actual code.

```
l~]_|S*
{l~]$S*
 {l~]W%S*
  {l~]_,\
   {l~]{z
    }%$W=
    "CORE
    "*
         }
   ;:+d\/ }
  ;        }
 ;          }
;

```

Test it here.

The core is

```
l~]{z
}%$W=
"CORE
"*

```

(Plus an empty line.)

I'm fairly sure that `N = 4` can't be done in CJam (and I'm sure Dennis will convince me otherwise :D). The above has 17 characters, and while it might be possible to get it down to 16 (e.g. if CJam didn't have a bug to choke on `:z`, which requires `{z}%`, or by using ARGV), I don't think you can fit it in the layout without introducing a line break within `CORE`.

All of the implementations are very straightforward solutions to the given tasks. All of them start with `l~]` which reads STDIN, evaluates it, and puts it in an array.

The previous layer is always surrounded in `{...}`, which makes it a block that isn't automatically executed. And instead of executing it, I just discard it from the stack with `;`, so no layer depends on code in the previous layer. In the Layer 1, the code didn't fit into the first line, so I continued it after discarding the core block.

Now for the actual programs:

* Core:

```
{z}%$W="CORE
"*

```

Map `abs` onto the list, sort it, take the last element, repeat `CORE` (and a line break) that many times.
* Layer 1:

```
_,\:+d\/

```

Duplicate the list, take the length, swap the stack elements, get the sum, cast to `double`, swap the stack elements, divide. I think this can be shorter, but there's no incentive to do so.
* Layer 2:

```
W%S*

```

Reverse the array, riffle with spaces.
* Layer 3:

```
$S*

```

Sort the array, riffle with spaces.
* Layer 4:

Duplicate, take set union, riffle with spaces.

Some other optimisations are also possible, like reusing the `;` and `*S` of Layer 2, but again, but it doesn't affect the score.
> 10 votes

# Answer
# Python 2 - N = 17, 53 characters

Oh I love source-layout challenges with Python...

```
i=4                     ;
ii=3                    ;
iii=2                   ;
iiii=1                  ;
iiiii=0;R=raw_input     ;
iiiii;w=R().split()     ;
iiiii;n=map(int,w)      ;
iiiii;S=set(n);M=max    ;
iiiii;s=sorted(n)       ;
iiiii;J="\n".join       ;
iiiii;j=" ".join        ;
iiiii;k=M(map(abs,n))   ;
iiiii;A=J(["CORE"]*k)   ;
iiiii;B=sum(n)/len(n)   ;
iiiii;C=j(w[::-1])      ;
iiiii;D=j(map(str,s))   ;
iiiii;E=j(map(str,S))   ;
iiiii;P=A,B,C,D,E       ;
iiiii;print P[i]        ;
iiiii;" /__----__\  "   ;
iiiii;"|/ (')(') \| "   ;
iiii;"  \   __   /  "   ;
iii;"   ,'--__--'.   "  ;
ii;"   /    :|    \   " ;
i;"   (_)   :|   (_)   ";

```

There's still some unused whitespace, though.

I could still improve the unique character count, but I'll stick with better readability - if there is any at all.

**Edit:** Oh, it's Stan again!
> 19 votes

# Answer
# Python 3: N=11, 40 distinct characters

```
if 1:
 if 1:
  if 1:
   if 1:
    p=print;R=0
    a=input()
    b=a.split()
    m=map;a=abs
    E=max;l=len
    n=m(int,b);
    C=['CORE']
   "R=E(m(a,n))"
   OO=C*R;s=sum
   "x='\n'.join"
   "p(x(O))    "
  "p(s(n)/l(b)) "
 "p(*b[::-1])    "
"p(*sorted(n))    "
p(*set(n))

```

Thanks to @Falko for being my muse. This works, because Python does not create a new scope for each if statement, so the variables persist in the outer `print` statements. One annoying thing was that a `map` object (in our case `n`) can be used only once. So it was necessary to string out the `R=E(...)` line, but then `R` was not defined. Therefore I was lucky that there were four spaces left in the first line!

The output can be solved by providing multiple elements `*b[::-1]` instead of the list. The alternative `' '.join(...)` would have been too long.
> 6 votes

# Answer
# C (gcc), N = 15, 47 unique characters

Assumes `sizeof(int) == 4` and `sizeof(int*) >= sizeof(int)`.

```
;                     ;
 ;                   ;
  ;                 ;
   ;           float
    s;c(a,b)int*a,*
    b;{b=*b-*a;}i,n
    ,*f;*q,*R,C,E ;
    main(a){for(;0<
    scanf("%i",&a);
    i=i<abs(a)?a:i,
    s+=f[n-!0]=a)f=
    realloc(f,++n*4
    );qsort(f,n*C,4
    ,c);for(i=q?R?n
    :!0:i;i--;a=f[i
    ])!E|n-i<2|a!=f
    [i]&&printf(q?R
    ?R:q:"CORE\n",!
    q+R?f[i]:s/n);}
   ;*q="%f";       ;
  ;*R="%.0f ";      ;
 ;C=!0;              ;
;E=!0;                ;

```

4 Layers

3 layers

2 layers

1 layer

Core
> 2 votes

# Answer
# Runic Enchantments, ~~N=9~~ N=8, 38 Characters

```
/ o/\  \     \S\
" //RiU\      \}
@            q "
"        }+1\r @
}   ^U \    {q "
     \{\?)}\+  }
  o\/'|A:{:/R' S
 //r/Ril2=?\?R :
   ,A~/"OC"/=? {
   @| \"RE"\3= =
 D$\' /rqka/l2S?
    i \*@   il\/
   'R1i     Ui ~
 R$/Rak      U \
 ?!D  Rlril1-{=
R   R: }S:{=?\~

```

Try it online!

Turns out I was wrong, I forgot I had an explicit s`o`rt command already, due to having encountered the "sort a list" problem before. This does, however, limit the size of inputs that the final program can take (8 values) due to the internal costs of the sort command. A slight tweak can increase the input size to 13 at the cost of 1 unique character or to 19 for two unique characters (all additional characters are on Layer 1 and added at the same time, but the increased capacity of the IP's stack isn't needed until Layer 3, as C, L1, and L2 can perform their calculations without holding the entire input in memory).

Core: Try it online!

Layer 1: Try it online!

Layer 2: Try it online!

Layer 3: Try it online!

Layer 4: Try it online!

Further compression is highly unlikely, due to the smaller space necessitating an increase in the number of flow control characters. I found an arrangement that gave 9 empty spaces in the core program, but that is not enough, as we need (a correctly arranged) 15.

Explaining how any of these programs work is difficult without a visual map of the path the IP takes, which is cumbersome and time consuming to construct. The initial entry point is the upper left corner of the Core program (`^`) which allows for consistent flow control as new layers are added, as each layer has an opportunity to intercept on the newly added line at the top or the bottom.

Layers 1 and 2 intercept at the bottom (so that the top line remains empty for future layers) and then perform their operations along the right hand edge (a loop arranged vertically). Layer 1 is slightly too long and takes 3 characters along the top edge as well, but the diagonal reflector (`\`) in the top right realigns the IP with the next loop iteration.

Layer 3 intercepts along the top edge in order to grab the first input value before redirecting to the bottom edge (Layer 4 leaves a NOP in this column on its bottom line) and reads the full input using the bottom edge loop, redirecting on the Down command (`D`) in the lower left. From there the IP bounces a few times before ending up in an output (`$`) loop in the lower left in order to space-separate the values.

Layer 4 utilizes all of the functionality of layer 3 (hence the blank space), but intercepts on its own new top edge (upper left) in order to perform its own functionality at the end of Layer 3's processing. The top left corner inserts a string `"@"` which is used to denote the end of the array before entering the processing loop along the bottom. If a duplicate value is found, it's popped (`~`, lower right corner) otherwise the branch is taken that consumes the new right hand edge. This side branch checks to see if the end of the array has been reached, and if so, break out and head to the same space-separated output loop from Layer 3. Otherwise use the blank space on Layer 3 to return back to the main loop.
> 1 votes

# Answer
# JavaScript (Node.js), ~~N=14, C=44~~ N=13, C=40

```

    (s,a=s.split
    ` `)=>[[`CORE
    `.repeat(Math
    .max(...a.map
    (Math.abs)))]
    ,a.reverse(),
    [a.reduce((i,
    j)=>i- -j,2-2
    )/a.length],[
    ...new Set(a)
    ],[...a].sort
    ((i,j)=>i-j)]
[[[[[2-2].join` `
   - -2].join` `
  -2/2].join` `
 - -2-2/-2].join` `
-2/2].join` `

```

Try it online!

# JavaScript (Browsers), N=15, C=52

Full program. The TIO uses `process.argv[2]` for `prompt()`

```
(r=4)?r:
 (r=3)?r:
  (r=2)?r:
   (r=1)?r:
    r=0;p=prompt().
    split` `;m=p.
    reduce((i,j)=>i
    - -j)/p.length
    v=p.reverse().
    join` `;t=[...p
    ].sort((i,j)=>i
    -j).join` `;s
    =new Set(p);
    console.log(
((((r==0?Array(Math
    .max(...p.map(
    Math.abs)))
    .fill(`CORE`)
    .join`\n`:``)  +
   (r==1?m:``))     +
  (r==2?v:``))       +
 (r==3?t:``))         +
[...s].join` `)

```

Try it online!
> 0 votes

# Answer
# TlanG 177 bytes N=4 (\*3)

```
############
############
############
####CORE####
####||||####
####CORE####
############
############
############

```

prints `CORE`

Explaination on the github linked in title

Not quite the requested but i think its fine!
> -1 votes

---
Tags: code-challenge, printable-ascii, source-layout
---


title: Is it an Arithmetic Sequence or not?

text:
# Question
Title: Is it an Arithmetic Sequence or not?
# Challenge

In this challenge, the input will be an ordered set of numbers and the program should be able to tell if the set of numbers is an Arithmetic Sequence.

# Input

* The input will be a list separated by `,`(comma) or `,` (comma+space). The minimum length of the list should be 3 elements.

# Output

* The Output can be a Boolean (True or False), or a number (1 for True, 0 for False).

# Test cases

```
In: 1, 3, 5
Out: True

In: 1,4, 7
Out: 1

In: 5, 9,10
Out: 0

In: 5,3,1
Out: False

```

# Rules

* This is , so the shortest code by bytes wins.
* The input will be finite

Best of Luck

# Answer
# MathGolf, 5 bytes

```
ê│▀£┴

```

Input `,`-delimited; outputs `1`/`0` for truthy/falsey respectively.

Try it online. (MathGolf is able to execute multiple test cases at once for each line of STDIN input, but feel free to only use a single input if you'd like.)

**Explanation:**

```
ê      # Read the comma-delimited input-string as integer-list
 │     # Get the forward differences of each overlapping pair in this list
  ▀    # Uniquify these differences
   £   # Pop and push the length to get the amount of unique differences
    ┴  # Check that this length is equal to 1 (1 if 1; 0 if >= 2)
       # (after which the entire stack joined together is output implicitly as result)

```
> 1 votes

# Answer
# Retina 0.8.2, 47 bytes

```
\d+
$*
A`(1+),(?!\1)
(?<=(1+),)\1

^1*(,1*)\1*$

```

Try it online! Only works on nondescending sequences of at least two integers. Explanation:

```
\d+
$*

```

Convert to unary.

```
A`(1+),(?!\1)

```

Check that the sequence is ascending.

```
(?<=(1+),)\1

```

Compute the differences after the first value.

```
^1*(,1*)\1*$

```

Check that all of the differences are equal.
> 1 votes

# Answer
# APL (Dyalog Unicode), 8 bytes (SBCS)

```
1=≢∪2-/⎕

```

Try it online!

`1=` Is 1 equal to

the count of

unique

`2-/` pairwise differences

in the evaluated input?

The  prompts for input and executes it. Luckily, `,` is APL's concatenation functions, so the required input format evaluates to a list. Spaces are ignored.
> 1 votes

# Answer
# 05AB1E, 5 bytes

```
',¡¥Ë

```

Input `,`-delimited; outputs `1`/`0` for truthy/falsey respectively.

Try it online or verify a few more test cases.

**Explanation:**

```
',¡   '# Split the (implicit) input-string on ","
   ¥   # Get the deltas (forward differences) of each overlapping pair in this list
    Ë  # Check if all differences are equal (1 if truthy; 0 if falsey)
       # (after which this result is output implicitly)

```

Of course, this would have been **2 bytes** with default I/O rules by taking a list input: `¥Ë`.
> 1 votes

---
Tags: code-golf, math, number, sequence, decision-problem
---


# Question
Title: Get string "-" with JavaScript using only the symbols from "+[]"
**Challenge:** Get the JavaScript string value containing only the "`-`" character using code only containing the following three symbols: `+[]`. *Note: I'm not sure if this is possible*.

**Scoring criterion**: The number of bytes of code used.

**Why?** I've set myself a challenge to be able to write code using only the above three characters that can evaluate to ANY JavaScript number. The only thing left I am missing is having access to the "`-`" character. Once I have this, everything else becomes possible. This question is what gave me inspiration for this.

# Definitions

Here is a list of definitions I've so far come up with to write a JavaScript expression (on the left) using only the `+[]` symbols (on the right). Most definitions reuse existing definitions.

> ```
> **0**: +[]
> **1**: ++[[]][**0**]
> **(**EXPR**)**: [EXPR][**0**]
> **1**: **(**1**)**
> **2**: **1**+**1**
> **3**: **1**+**2**
> **4**: **1**+**3**
> **5**: **1**+**4**
> **6**: **1**+**5**
> **7**: **1**+**6**
> **8**: **1**+**7**
> **9**: **1**+**8**
> POSITIVE_INTEGER: +**((**DIGIT1**+""****)**+DIGIT2+DIGIT3+**...)**
> **""**: []+[]
> EXPR**+""**: EXPR+[]
> **undefined**: [][**0**]
> **"undefined"**: **undefined+""**
> **"undefined"**: **("undefined")**
> **"u"**: **"undefined"**[**0**]
> **"n"**: **"undefined"**[**1**]
> **"d"**: **"undefined"**[**2**]
> **"e"**: **"undefined"**[**3**]
> **"f"**: **"undefined"**[**4**]
> **"i"**: **"undefined"**[**5**]
> **NaN**: +**undefined**
> **"NaN"**: **NaN+""**
> **"N"**: **"NaN"**[**0**]
> **"a"**: **"NaN"**[**1**]
> **Infinity**: +**(1**+**"e"**+**3**+**1**+**0)**
> **"Infinity"**: **Infinity+""**
> **"I"**: **"Infinity"**[**0**]
> **"t"**: **"Infinity"**[**6**]
> **"y"**: **"Infinity"**[**7**]
> **"function find() { [native code] }"**: **(**[][**"f"**+**"i"**+**"n"**+**"d"**]**+"")**
> **"c"**: **"function find() { [native code] }"**[**3**]
> **"("**: **"function find() { [native code] }"**[**13**]
> **")"**: **"function find() { [native code] }"**[**14**]
> **"{"**: **"function find() { [native code] }"**[**16**]
> **"["**: **"function find() { [native code] }"**[**18**]
> **"a"**: **"function find() { [native code] }"**[**19**]
> **"v"**: **"function find() { [native code] }"**[**22**]
> **"o"**: **"function find() { [native code] }"**[**17**]
>
> ```

# Unfinished definitions

These definitions contain missing pieces, highlighted in red (never mind, I can't figure out how to change the color, I'll use italics for now).

> ```
> ***Number***: **0**[**"con*s*t*r*ucto*r*"**]
> *OBJ**.**FUNC**()***: +*{valueOf:*OBJ.FUNC*}*
> *OBJ**.**FUNC**()***: *{toString:*OBJ.FUNC*}***+""**
> *"-"*: **(*Number.MIN_SAFE_INTEGER*+"")**[**0**]
> *"-"*: **(*Number.NEGATIVE_INFINITY*+"")**[**0**]
> *"-"*: **(*Number.MIN_VALUE*+"")**[**2**]
> *"-"*: **(""*.indexOf()*+"")**[**0**]
> ".": **(**+**"1e*-*1")**[**1**]
>
> ```

---

Thanks to the amazing answers to this question, I've created a JSFiddle that can generate any JavaScript number using those 3 characters. Input a number, tap "Go!", and then copy and paste the JavaScript into your devtools console to see it in action. You can also hover over the generated output in the explanation section for details on how it works.

# Answer
# ~~260 ... 210~~  205 bytes

*Saved 5 bytes thanks to @user202729*

```
[+[[+[++[[]][+[]]+[++[[]][+[]]]+[[+[][[]]]+[][[]]][+[]][++[[]][+[]]+[+[]]]+[++[[]][+[]]]+[+[]]+[+[]]]+[]][+[]][++[[]][+[]]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[++[[]][+[]]]]+[]][+[]][++[++[[]][+[]]][+[]]]

```

Try it online!

### How?

We first generate the string `"11e100"` and coerce it to an number to get `1.1e+101`. By coercing it back to a string and extracting the 2nd character, we obtain a `"."`

Using this `"."`, we can now generate the string `".0000001"`. When forced to a number, this gives `1e-7`, which can be used to extract a `"-"`.

Below is a slightly more readable version:

```
[+[[+['11' + [[NaN] + undefined][0][10] + '100'] + []][0][1] + '0000001'] + []][0][2]

```

### Commented

```
[                           // singleton array:
  +[                        //   coerce to a number:
    [                       //     singleton array:
      +[                    //       coerce to a number:
        ++[[]][+[]] +       //         1 +
        [++[[]][+[]]] +     //         "1" +
        [                   //         singleton array:
          [+[][[]]] +       //           "NaN" +
          [][[]]            //           undefined
        ][+[]]              //         [0] -> "NaNundefined"
        [                   //         build [10]:
          ++[[]][+[]] +     //           1 +
          [+[]]             //           "0"
        ]                   //         -> "e"
        + [++[[]][+[]]]     //         + "1"
        + [+[]] + [+[]]     //         + "0" + "0" -> "11e100"
      ]                     //       -> 1.1e101
      + []                  //       coerce to a string
    ][+[]]                  //     [0] -> "1.1e101"
    [ ++[[]][+[]] ]         //     [1] -> "."
    + [+[]] + [+[]] + [+[]] //     + "0" + "0" + "0"
    + [+[]] + [+[]] + [+[]] //     + "0" + "0" + "0"
    + [++[[]][+[]]]         //     + "1" -> ".0000001"
  ]                         //   -> 1e-7
  + []                      //   coerce to a string
][+[]]                      // [0] -> "1e-7"
[                           // build [2]:
  ++[                       //   pre-increment:
    ++[[]][+[]]             //     1
  ][+[]]                    //   [0]
]                           // -> "-"

```
> 36 votes

# Answer
# ~~286~~ ~~256~~ ~~251~~ ~~247~~ ~~244~~ 240 bytes

```
[+[[+[++[[]][+[]]+[++[[]][+[]]]+[[][[]]+[]][+[]][++[[]][+[]]+[++[[]][+[]]][+[]]+[++[[]][+[]]][+[]]]+[++[[]][+[]]]+[+[]]+[+[]]]+[]][+[]][++[[]][+[]]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[++[[]][+[]]]]+[]][+[]][++[[]][+[]]+[++[[]][+[]]][+[]]]

```

Did I just outgolf *@Arnauld* in his favorite language despite barely knowing JS?! ;) EDIT: Never mind, he just golfed it the moment I post it.. Of course. XD

Try it online.

**Explanation:**

Techniques used:

* `+[]`: 0
* `++[[]][+[]]`: 1
* `[][[]]`: `undefined`
* `[EXPRESSION]+[]`: Cast to string
* `+[EXPRESSION]`: Cast to a number
* `"STRING"[INDEX]`: Get the INDEX'th character of the STRING
* `[EXPRESSION][+[]]`: Wrap and extract to have access to the next command (necessary after we casted to a string, number, or concatted some strings together); a.k.a. it acts as wrapping the EXPRESSION in parenthesis: `(EXPRESSION)`.

I first create the string `"11e100"`. Casting this to a number and then back to a string will result in `"1.1e+101"`. From this, I extract the `.`, and use it to create the string `".0000001"`. Casting this to a number and then back to a string will result in `"1e-7"`, from which we can extract the `-`.

Of course I didn't come up with this myself, since I barely program in JavaScript nor JSFuck. The genius behind this is *@Lynn*, who posted the following in this answer of his/her for the *JSF\**k with only 5 symbols?* challenge:

> Also, we can make `"11e100"`, cast to number and back to string, to get `"1.1e+101"`, from which we extract `.` and `+`.
>
> Using that `.`, in turn, we can make the string `".0000001"`, cast it to number and back, to get `"1e-7"`, winning us `-`.

**Code explanation:**

Step 1: Create `"11e100"`:

```
++[[]][+[]]            // Push 1
+[           ]         // Concat:
  ++[[]][+[]]          //  Another 1
+[...]                 // Concat:
   [][[]]              //  Push undefined
         +[]           //  Cast it to a string: "undefined"
  [         ][+[]]     //  Wrap it in a list, and extract it again
                  [3]  //  Get the (0-based) 3rd character of this string: "e",
                       //  where the 3 is created like this:
 ++[[]][+[]]           //   Push 1
 +                     //   Add:
   ++[[]][+[]]         //    Push another 1
  [           ][+[]]   //    Wrap it in a list, and extract it again
 +[++[[]][+[]]][+[]]   //   And do the same to add another 1
+[++[[]][+[]]]         // Concat another 1
+[+[]]                 // Concat a 0
+[+[]]                 // And concat another 0

```

Step 2: Convert it to `"1.1e+101"`:

```
+[^]                   // Cast "11e100" to a number
    +[]                // And convert it back to a string

```

Step 3: Extract the `.`:

```
[^][+[]]               // Wrap it in a list, and extract it again
        [1]            // Get the (0-based) 1st character of this string: ".",
                       // where 1 is created as before:
         ++[[]][+[]]   //  Push 1

```

Step 4: Create `".0000001"`:

```
^+[+[]]                // Concat a 0 to the "."
+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]
                       // And concat five more 0s
+[++[[]][+[]]]         // Concat a 1

```

Step 5: Convert it to `"1e-7"`:

```
+[^]                   // Cast ".0000001" to a number
    +[]                // And convert it back to a string

```

Step 6: Extract the `-`:

```
[^][+[]]               // Wrap it in a list, and extract it again
        [2]            // Get the (0-based) 2nd character of this string: "-",
                       // where 2 is created like this:
 ++[[]][+[]]           //  Push 1
 +                     //  Add:
   ++[[]][+[]]         //   Push 1
  [           ][+[]]   //   Wrap it in a list, and extract it again

```
> 14 votes

---
Tags: code-golf, string, kolmogorov-complexity, restricted-source, javascript
---


title: Find the discrete logarithm

text:
# Question
Title: Find the discrete logarithm
# Task

Write a program/function that when given 3 positive integers \\$a, b\\$ and \\$m\\$ as input outputs a positive integer \\$x\\$ such that \\$a^x\equiv b\ (\text{mod}\ m)\\$ or that no such \\$x\\$ exists.

A reference implementation can be found here.

# Constraints

You can expect \\$a\\$ and \\$b\\$ to be less than \\$m\\$.

# Scoring

This is so shortest bytes wins.

# Sample Testcases

```
# a, b, m -> x

10, 10, 50 -> 1
10, 100, 200 -> 2
10, 1, 127 -> 42
35, 541, 1438 -> 83
35, 541, 1438 -> 1519
1816, 2629, 3077 -> 223
3306, 4124, 5359 -> 1923
346, 406, 430 -> None
749430, 2427332, 2500918 -> 8025683
3442727916, 3990620294, 6638635157 -> 5731137125

```

**Note:** in the third testcase the solution cannot be 0 since the solution has to be a positive number

# Answer
> 10 votes
# C (gcc), <sup>~~59~~ ~~53~~</sup> 51 bytes

Saved 6 bytes thanks to the man himself Arnauld!!!

Saved 2 bytes thanks Dominic van Essen!!!

```
p;x;f(a,b,m){for(p=a,x=1;p-b&&++x<m;)p=p*a%m;x%=m;}

```

Try it online!

Inputs positive integers \\$a,b,m\\$ with \\$a,b\<m\\$.
Outputs a positive integer \\$x\\$ such that \\$a^x\equiv b\ (\text{mod}\ m)\\$ or \\$0\\$ if no such \\$x\\$ exists.

# Answer
> 6 votes
# Python 2, ~~55~~ 51 bytes

```
def f(a,b,m,x=1):a**x%m==b<exit(x);x<m<f(a,b,m,x+1)

```

Try it online!

A recursive function that simply tests all exponents from \\$1\\$ to \\$m\\$. Returns through exit code: a positive exponent \\$x\\$, or \\$0\\$ if no such \\$x\\$ exists.

# Answer
> 5 votes
# JavaScript (Node.js),  ~~38~~  33 bytes

Expects `(a,m)(b)` as 3 BigInts. Throws *RangeError* if there's no solution.

```
(a,m,x=m)=>g=b=>a**--x%m-b?g(b):x

```

Try it online!

---

# JavaScript (Node.js), 39 bytes

Expects `(a,m)(b)` as 3 BigInts. Returns *false* if there's no solution.

NB: This version always returns the smallest solution.

```
(a,m,x=0n)=>g=b=>a**++x%m-b?x<m&&g(b):x

```

Try it online!

# Answer
> 5 votes
# 05AB1E, ~~10~~ 7 bytes

```
Lm¹%³k>

```

Inputs in the order \\$m,a,b\\$; outputs `0` if no \\$x\\$ is found.

Try it online or verify all test cases.

**Explanation:**

```
L        # Push a list of values `x` in the range [1, (implicit) input `m`]
 m       # Take the (implicit) input `a` to the power of each of these `x`
  ¹%     # Take each modulo the first input `m`
    ³k   # Get the 0-based index of the first occurrence of the third input `b`
         # (-1 if there are none)
      >  # And increase it by 1 to make it a 1-based index
         # (after which it is output implicitly as result)

```

# Answer
> 3 votes
# APL (Dyalog Extended), 23 bytes

```
{⍺(∊×⍳⍨)(⍺⍺|⍵×⊢)⌂traj⍵}

```

Try it online!

Dyalog APL can't handle large integers, so a modulo should be performed after each iteration.

### How it works

```
{⍺(∊×⍳⍨)(⍺⍺|⍵×⊢)⌂traj⍵}  ⍝ dop; ⍵ ⍺ ⍺⍺ ← a b m
        (      )⌂traj    ⍝ Collect all iterations until duplicate is found
                     ⍵   ⍝   starting from a:
            ⍵×⊢          ⍝     Multiply a
         ⍺⍺|             ⍝     Modulo m
 ⍺(  ⍳⍨)                 ⍝ Find the 1-based index of b in the result,
   ∊×                    ⍝   changing to 0 if not found

```

# Answer
> 3 votes
# Ruby, 41 bytes

```
->a,b,m,x=0{(a**x+=1)%m==b&&x||x<m&&redo}

```

Try it online!

The logic is straightforward: increment the exponent \\$x\\$ and return it if it satisfies the required equation, otherwise repeat while \\$x\\$ is less than \\$m\\$. Outputs the smallest solution for \\$x\\$, or `false` if no solution exists.

# Answer
> 3 votes
# +gmp, ~~47~~ 46 bytes

Or only 37 bytes by requiring input in the form of `bigz` big integer.

```
function(a,b,m)match(T,as.bigz(a)^(1:m)%%m==b)

```

Try it online!

# Answer
> 3 votes
# MathGolf, 8 bytes

```
_╒k▬\%=)

```

Port of my 05AB1E answer, so also:
Inputs in the order \\$m,a,b\\$; outputs `0` if no \\$x\\$ is found.

Try it online.

**Explanation:**

```
_         # Duplicate the first (implicit) input `m`
 ╒        # Pop one and push a list in the range [1, `m`]
  k       # Push the second input `a`
   ▬      # For each value `x` in the list, take `a` to the power `x`
    \     # Swap so the originally duplicated `m` is at the top of the stack
     %    # Take modulo-`m` on each value in the list
      =   # Get the first 0-based index of the value that equals the third (implicit)
          # input `b` (-1 if there are none)
       )  # And increase it by 1 to make it a 1-based index
          # (after which the entire stack joined together is output implicitly as result)

```

# Answer
> 2 votes
# Java 8, 97 bytes

```
(a,b,m)->{for(int x=0;x++<m;)if(a.modPow(b.valueOf(x),b.valueOf(m)).equals(b))return x;return-1;}

```

\\$a\\$ and \\$b\\$ are both `java.math.BigInteger`; \\$m\\$ and the output \\$x\\$ are both `int`.
Outputs `-1` if no \\$x\\$ is found.

Try it online.

**Explanation:**

```
(a,b,m)->{            // Method with 2 BigInteger & integer parameters and integer return
  for(int x=0;x++<m;) //  Loop `x` in the range (0,m]:
    if(a.modPow(b.valueOf(x),b.valueOf(m))
                      //   If `a` to the power `x`, modulo `m`
       .equals(b))    //   equals `b`:
      return x;       //    Return `x` as result
  return-1;}          //  If the loop has ended without result, return -1 instead

```

# Answer
> 2 votes
# bc, 58 50 bytes

```
define f(a,b,m){for(;x<m;)if(a^++x%m==b)return(x)}

```

Try it online!

This just tries the integers from 1 to `m`, and outputs the first one which satisfies being a discrete log. Otherwise, the function returns `0` (default return value).

# Answer
> 2 votes
# Brachylog, 19 bytes

Takes in a list of `[A,M,B]`, output is either `X` or `false`. The `[3306, 5359, 4124]` test case times out on TIO, but returns the correct result locally. First Brachylog answer, so probably not the best solution. :-)

```
bhM>.>0&h;.^;M%~t?∧

```

Try it online!

### How it works

```
bhM>.>0&h;.^;M%~t?∧
bhM                 set the second item to M
   >.>0             output must be between M and 0
       &h           input's first item (A)
         ;.^        A^output
            ;M%     A^output mod M
               ~t?  must unify with the tail from the input (B)
                  ∧ return the output

```

# Answer
> 2 votes
# Haskell, 42 bytes

```
(a#m)b=last$0:[x|x<-[1..m],mod(a^x-b)m==0]

```

Try it online!

The function `(a # m) b` returns a positive integer `x` such that `a ^ x == b (mod m)`. If no such `x` exists, it returns `0`. This is done by the brute force method.

# Answer
> 1 votes
# , 61 bytes

```
function(a,b,m){for(i in c(1:m,0))if((T=(a*T)%%m)==b)break;i}

```

Try it online!

The base form of R doesn't support arbitrary-precision arithmetic (see my other 'R+gmp' answer for a solution using the 'gmp' library that allows this).
But, pleasingly, the step-by-step calculation of `(a^x)mod m` comes-out at only 14 bytes longer than the brute-force approach, and it's *much* faster.

# Answer
> 1 votes
# Charcoal, 14 bytes

```
ＮθＩ⊕⌕﹪ＸＮ…·¹θθＮ

```

Try it online! Link is to verbose version of code. Takes input in the order `m, a, b` and outputs `0` if there is no solution. Explanation:

```
Ｎθ              Store `m`
        …·¹θ    Range from 1 to `m` inclusive
      ＸＮ        Take powers of `a`
     ﹪      θ   Reduce modulo `m`
    ⌕        Ｎ  Find index of `b`
   ⊕            Convert to 1-indexing
  Ｉ             Cast to string
                Implicitly print

```

# Answer
> 1 votes
# Retina, 84 bytes

```
\d+
*
"$+"{`,(?=(_+))((_+),)+
,$.1*$3$&
)`^(_+),\1+
$1,
L$`.*(,_+)(,_+)+$(?<=\1)
$#2

```

Try it online! Sadly no test suite as this uses `"$+"`, and I can't figure out how to emulate that with multiple sets of inputs (Retina just crashes when I try). Takes input in the order `m, a, b` and produces no output if there is no solution. Explanation:

```
\d+
*

```

Convert to unary.

```
"$+"{`
)`

```

Repeat `m` times...

```
,(?=(_+))((_+),)+
,$.1*$3$&

```

... multiply the second number by the second last number and insert it between the first two numbers...

```
^(_+),\1+
$1,

```

... and reduce it modulo `m`.

```
L$`.*(,_+)(,_+)+$(?<=\1)
$#2

```

Count the position of the power matching `b` starting from the end.

# Answer
> 1 votes
# Io, 57 bytes

```
method(a,b,m,x :=1;for(i,1,m,if((x=x*a%m)==b,return i))0)

```

Try it online!

---
Tags: code-golf, math, number-theory, integer
---


title: How many numbers can we make?

text:
# Question
Title: How many numbers can we make?
You are given a non-empty list of positive integers. Your task is to figure out how many **distinct** numbers can be obtained by applying the following algorithm:

1. Remove either the first or the last item from the list and initialize **N** to the corresponding value.
2. Remove either the first or the last item from the list. Let's call its value **v**.
3. Update **N** to either **N + v** or **N * v**.
4. If the list is empty, stop here and return **N**. Otherwise, resume at step 2.

This is .

## Detailed example

Let's say that the input is:

```
[ 1, 5, 2, 3 ]

```

We can do, for instance:

```
[ 1, 5, 2, 3 ]  - choose 3      ==> n = 3
[ 1, 5, 2 ]     - multiply by 2 ==> n = 6
[ 1, 5 ]        - add 1         ==> n = 7
[ 5 ]           - multiply by 5 ==> n = 35
[]              - done

```

That's the only way of getting 35. But there are many different ways of getting, say, 11:

```
1 +5 +2 +3
3 +2 +1 +5
3 *2 +5 *1
etc.

```

All in all, we can generate 19 distinct numbers with this list. Only one example solution is given below for each of them.

```
10 : 3 +2 +5 *1  |  16 : 3 *1 +5 *2  |  22 : 3 +1 *5 +2  |  31 : 3 *2 *5 +1
11 : 3 *2 +5 *1  |  17 : 3 *1 *5 +2  |  24 : 1 +5 +2 *3  |  35 : 3 *2 +1 *5
12 : 3 *2 +5 +1  |  18 : 3 +1 +5 *2  |  25 : 3 +2 *5 *1  |  36 : 1 +5 *3 *2
13 : 3 +1 *2 +5  |  20 : 1 +5 *3 +2  |  26 : 3 +2 *5 +1  |  40 : 3 +1 *2 *5
15 : 1 +5 *2 +3  |  21 : 1 *5 +2 *3  |  30 : 3 *2 *5 *1  |

```

So, the expected answer for this input is **19**.

Below are two examples of **invalid** solutions:

```
32 : 5 *3 +1 *2  -> 5 can't be chosen at the beginning
32 : 3 *5 +1 *2  -> 5 can't be chosen after 3

```

## Test cases

```
[ 7 ]                    -> 1
[ 1, 1 ]                 -> 2
[ 2, 2 ]                 -> 1
[ 1, 2, 3 ]              -> 5
[ 7, 77, 777 ]           -> 8
[ 1, 5, 2, 3 ]           -> 19
[ 2, 2, 11, 2, 2 ]       -> 16
[ 2, 2, 2, 2, 11 ]       -> 24
[ 21, 5, 19, 10, 8 ]     -> 96
[ 7, 7, 7, 7, 7, 7 ]     -> 32
[ 6, 5, 4, 3, 2, 1 ]     -> 178
[ 1, 3, 5, 7, 5, 3, 1 ]  -> 235
[ 9, 8, 6, 4, 5, 7, 3 ]  -> 989
[ 7, 4, 6, 8, 5, 9, 3 ]  -> 1003

```

# Answer
# Brachylog, 26 bytes

```
{{|{|↔}~c₂l₁ʰ↰ᵗc}{+|×}ˡ}ᶜ¹

```

Try it online! Times out on test cases of length 5 or greater. It can probably be golfed further; the first half feels clunky.

# Explanation

```
{…}ᶜ¹  Count unique outputs for predicate.

{|{|↔}~c₂l₁ʰ↰ᵗc}  First part: permute list by reversing and recursing.
{|             }  Either return input unchanged, or
  {|↔}            possibly reverse it,
      ~c₂         split it into two parts,
         l₁ʰ      check that the first part has length 1,
            ↰ᵗ    call this sub-predicate on the second part,
              c   and plug the first part back.

{+|×}ˡ  Second part:
{   }ˡ  left fold by
 +|×    addition or multiplication (chosen separately for each element).

```
> 8 votes

# Answer
# Python 3, ~~102~~ 99 bytes

```
lambda v:len({*f(v,0)})
f=lambda v,N:v and sum([f(k,N*a)*N+f(k,N+a)for a,*k in(v,v[::-1])],[])or[N]

```

Try it online! Runs out of resources for the larger test cases on TIO.
> 6 votes

# Answer
# , <sup>~~88~~</sup> 71 bytes

```
([:#@~.@,(+`*>@{~])}.@,@,."2/&.:":(,:@{~(+&(|*+/\.-0&<)<:)"1))2#:@i.@^#

```

Try it online!

### How it works

From the permutations of taking the first/last element, we calculate absolute indices. With this we get all possible orders of selecting elements without recursion. Converted to strings and interwoven with `+` or `-`, we can execute them to get all numbers to count the unique.

```
2#:@i.@^#

```

Build up all boolean possibilities up to the length of the input.

```
(+&(|*+/\.-0<])<:)"1)

```

The boolean lists get added from right to left and then multiplied with its absolute value (thus zeroing itself out): `0 1 1 0 0 1 -> 3 3 2 1 1 1 -> 0 3 2 0 0 1`. The same happens with the decremented list, so `_1 0 0 _1 _1 0 -> … -> _3 0 0 _2 _1 0`. If the numbers are positive, we decrement them `-0<]` to account for 0-based indices. We then add both lists up: `_3 2 1 _2 _1 0`. This is the reverse of numbers to pick as J binds right to left.

```
,:@{~

```

Get the numbers at the indices, with `_1` taking the last and so on. Itemize each number.

```
(+`*>@{~])

```

The original boolean lists mapped to operators, `0 -> +, 1 -> *`.

```
}.@,@,."2/&.:":

```

Interpret each number as a string, make a table of all numbers and the operators, dropping the first operator with `}.` (`7 + 777 * 77`). With `&.:` the right operator gets reversed, and thus J interprets this string as a number.

```
[:#@~.@,

```

With the list of possible numbers, remove duplicates and get the length.
> 4 votes

# Answer
# 05AB1E, ~~40~~ 39 bytes

```
„RćD¦‚Ig©ãεvy.Vˆ]¯®ô„+*®<ãðδšδ.ιJ˜€.VÙg

```

Try it online or verify most test cases. (The last three test cases are too large for the test suite due to the `ã` builtin, although can still be verified in the loose TIO.)

**Explanation:**

```
„Rć         # Push string "Rć"
   D        # Duplicate it
    ¦       # Remove the first character: "ć"
     ‚      # Pair them together: ["Rć","ć"]
      Ig    # Get the length of the input-list
        ©   # Store this length in variable `®` (without popping)
         ã  # Get the cartesian power of the ["Rć","ć"] with this length
ε           # For-each over the list of list of strings:
 v          #  Inner loop over each string `y` in the list:
  y.V       #   Evaluate/execute `y` as 05AB1E code on the (implicit) input-list:
            #    `ć` extracts the head; it pops the list and pushes the remainder-list
            #    and first item separated to the stack
            #    `Rć` reverses the list first, before doing the same
     ˆ      #   Pop and store this top value in the global array
]           # Close the nested loops
 ¯          # Push the global array
  ®ô        # Split it into parts equal to the length `®`
„+*         # Push string "+*"
   ®<       # Push length `®` minus 1
     ã      # Get the cartesian power of the "+*" with this length-1
       δ    # For each list in this list of strings:
      ð š   #  Convert the string to a list of characters, and prepend a space character
δ           # Apply on the two lists double-vectorized:
 .ι         #  Interweave the two lists
   J        # Join each list of strings together to a single string
    ˜       # Flatten this list of lists of strings
€           # Map over each string:
 .V         #  And execute/evaluate it as 05AB1E code
Ù           # Then uniquify the list of resulting values
 g          # And take its length to get the amount of unique values
            # (after which it is output implicitly as result)

```

Example input: `[1,5,2,3]`
Example list of strings: `["ć","Rć","Rć","ć"]`
Example operations: `["+","*","+"]`

This will become string `"1 3+5*2+"`, which evaluated/executed as 05AB1E (Reverse Polish notation) results in `22`.
> 4 votes

# Answer
# T-SQL, 228 bytes

Input is a table variable:

```
WITH C as(SELECT v u,1/i+1f,@@rowcount-sign(i-1)t FROM @
WHERE i in(1,@@rowcount)UNION ALL SELECT o,f+SIGN(t-i),t-i/t
FROM c JOIN @ ON i in(f,t)and f<=t
CROSS APPLY(values(v*u),(v+u))p(o))SELECT
count(distinct u)FROM C WHERE f>t

```

**Try it online**
> 3 votes

# Answer
# Charcoal, 56 bytes

```
≔Ｅ³Ｅθ§θ⁺ιμθＦθ¿⊖Ｌι«≔Ｅ²⊟ιηＦ⟦ΣηΠη⟧Ｆ²⊞θ⁺⎇λ⮌ιι⟦κ⟧»Ｆ¬№υι⊞υιＩＬυ

```

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

```
≔Ｅ³Ｅθ§θ⁺ιμθ

```

The first two numbers to be added or multiplied can either be the last two numbers in the list, the last and the first, or the first two. Create three cyclic rotations of the list with each combination ending up at the end of the list.

```
Ｆθ

```

Start a breadth-first search.

```
¿⊖Ｌι«

```

If this entry still has 2 or more numbers, then...

```
≔Ｅ²⊟ιη

```

... remove the last 2 numbers into a separate list, ...

```
Ｆ⟦ΣηΠη⟧

```

... take their sum and product, ...

```
Ｆ²⊞θ⁺⎇λ⮌ιι⟦κ⟧

```

... and append that to both the remaining numbers and their reverse, so that the number at either end gets to be combined on the next iteration.

```
»Ｆ¬№υι

```

Otherwise if this entry hasn't yet been seen, then...

```
⊞υι

```

append it to the list of distinct entries.

```
ＩＬυ

```

Print the length of the final list.
> 2 votes

# Answer
# perl -alp, 176 bytes

```
@t=([@F],[reverse @F]);while(@t){($N,@l)=@{shift@t};@l?push@t,([$N+$l[0],@l[1..$#l]],[$N*$l[0],@l[1..$#l]],[$N+$l[-1],@l[0..$#l-1]],[$N*$l[-1],@l[0..$#l-1]]):$s{$N}++}$_=keys%s

```

Try it online!

This just tries all possibilities (all \\$\frac{2 \cdot (4^n -1)}{3}\\$ of them), where \\$n\\$ is the number of items on the input.
> 2 votes

# Answer
# C++ (gcc), ~~235~~ 232 bytes

```
#include<set>
using I=int;
void g(I n,I*f,I*l,std::set<I>&s){if(f-l){g(n**f,f+1,l,s);g(n+*f,f+1,l,s);g(n*l[-1],f,l-1,s);g(n+l[-1],f,l-1,s);}else s.insert(n);}I f(I*f,I*l){std::set<I>s;g(*f,f+1,l,s);g(l[-1],f,l-1,s);return s.size();}

```

Try it online!

Usage: `int result_count = f((int*) first, (int*) last);` where `first` is a pointer to the first element of an `int` array, and `last` is the pointer to one past the end of the array.

Assumes all results an intermediate values will fit in an `int`.

Explanation: Using a `std::set<int>` to keep track of which results have been found, recursively checks each possible path, then returns the size of the set of results.

Ungolfed:

```
#include <set>
void helper(int N, int *first, int *last, std::set &results){
    if (first != last) {
        helper(n * first[0], &first[1], last, results); // v = beginning; N = N * v
        helper(n + first[0], &first[1], last, results); // v = beginning; N = N + v
        helper(n * last[-1], f, &last[-1], results); // v = end; N = N * v
        helper(n + last[-1], f, &last[-1], results); // v = end; N = N + v
    } else {
        results.insert(N);
    }
}
int f(int *first, int *last){
    std::set results;
    helper(first[0], &first[1], last, results); // N = beginning
    helper(last[-1], first, &last[-1], results); // N = end
    return results.size();
}

```
> 2 votes

# Answer
# Io, 157 bytes

(Sort of) a port of ovs's answer, go upvote them!

```
method(v,f(v,0)size)
f :=method(v,N,if(v size>0,list(v,v reverse)map(i,k :=i slice(1);a :=i at(0);list(if(N>0,f(k,N*a),f(k,N+a)),f(k,N+a)))flatten unique,N))

```

Try it online!

# Io, 272 bytes

First time doing BFS, I'm definitely not good at it anyway.

```
method(x,f(0,x,1))
f :=method(L,x,N,if(x size<1,return N)if(L<1,list(f(L+1,x slice(1),x at(0)),f(L+1,x slice(0,-1),x at(-1)))flatten unique size,list(f(L+1,x slice(1),N*x at(0)),f(L+1,x slice(1),N+x at(0)),f(L+1,x slice(0,-1),N*x at(-1)),f(L+1,x slice(0,-1),N+x at(-1)))))

```

Try it online!
> 1 votes

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


# Question
Title: Shortest python3 code for: Find the difference between a number and a power of two not exceeding a given number
So, this is a task from one very popular educational site in Russia: https://acmp.ru/index.asp?main=task&id\_task=786&ins=1

Mathematically, you need to find the power of two not exceeding the given number, read from the standard input stream, and output their difference in the standard output stream. My **python3** solution takes **41** characters, but the leader’s solution is only **40** characters. Who can shorten the code?

**Newlines, spaces and tabs are not included while counting code length.**

```
x = int(input())
print(x - 2 ** (len(bin(x)) - 3))

```

# Answer
> 6 votes
# Python 3, ~~40~~ 39 bytes (not counting the newline)

First I simplified \\$2^{a-3}\\$ to \\$\frac{2^a}8\\$, then I used the lower-precedence operators `<<` and `^` so that `//` can be replaced by `-` (which saves a byte).

```
x=int(input())
print(1<<len(bin(x))-3^x)

```

Try it online!

# Answer
> 10 votes
# Python 3, 39 bytes

```
print(int('0'+bin(int(input()))[3:],2))

```

Try it online!

Subtracting the largest power of two less than a number is the same as removing the first `1` from its binary representation.

Unfortunately python rather mysteriously errors on trying to convert the empty binary string to an int so we need `'0'+` if we want it to work on zero or one. If we relax the requirements to only require two or more then we can remove 4 bytes.

# Python 3, 35 bytes

```
print(int(bin(int(input()))[3:],2))

```

Try it online!

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


title: Eight days a week

text:
# Question
Title: Eight days a week
Back in 1965, The Beatles released their hit song 'Eight Days a Week'. In this challenge we are going to reimagine dates of the 21st century as if there really were eight days a week.

### Input

A Gregorian calendar date between 1 January 2001 and 31 December 2100 inclusive. You may take input in any convenient format (including built-in date objects).

### Output

The *weekday number*, *week number*, and *week-numbering year* (all defined below) corresponding to the input date. You may use any format (to be specified in your answer) in which all three numbers are unambiguously identifiable.

### Week date system

The week date system, based on the ISO week date system but modified for eight-day weeks, works like this:

* Reckoning of dates begins on 1 January 2001 (Gregorian), which is weekday number 1 of week number 1 of week-numbering year 2001.
* Weeks begin on weekday number 1 and end on weekday number 8. (So 9 January 2001 is weekday number 1 of week number 2 of week-numbering year 2001.)
* Week number 1 of a week-numbering year is the week that contains 4 January.
* Week-numbering years contain exactly 45 or 46 weeks. Thus a week-numbering year begins on weekday number 1 of week number 1 and ends on weekday number 8 of week number 45 or 46.

Given that the number of days in a Gregorian calendar year is never a multiple of 8, the above rules have two important consequences:

* Week number 1 of a week-numbering year may begin in the last four days of December of the previous Gregorian year.
* Week number 46 (if there is one) of a week-numbering year may end in the first three days of January of the next Gregorian year.

### Test cases

Input (Gregorian yyyy-mm-dd) -\> Output (week-numbering year, week number, weekday number)

```
2001-01-01 -> 2001, 1,1
2001-01-08 -> 2001, 1,8
2001-01-09 -> 2001, 2,1
2001-12-31 -> 2001,46,5
2002-01-01 -> 2001,46,6
2002-01-04 -> 2002, 1,1
2002-12-29 -> 2002,45,8
2002-12-30 -> 2003, 1,1
2020-02-29 -> 2020, 8,7
2037-09-13 -> 2037,32,5
2061-04-23 -> 2061,15,4
2100-12-31 -> 2101, 1,4

```

---

Related, but that challenge involves standard 7-day weeks, has finicky I/O requirements, and bans date/time libraries and built-ins.

# Answer
> 5 votes
# JavaScript (ES6),  ~~129 ... 107~~  105 bytes

Expects a Date object. Returns `[year, week, weekday]`.

```
d=>(g=n=>(w=/an 0[^9]/.test(x=new Date(99,24,n))?++y/y:w+1,q=(d-x)/864e5)>3?g(n+8):[y,w,5+q])(-3,w=y=2e3)

```

Try it online!

### How?

We start a few days before January 1, 2001 and progressively advance in the future, adding 8 days at each iteration. We increment the year and reset the week number each time we reach the 4th of January. We stop as soon as the target date is passed.

The most important part in the code is:

```
/an 0[^9]/.test(x = new Date(99, 24, n))

```

When the year argument is less than 100, the `Date()` constructor interprets it as 19xx. So, `new Date(99, 24, n)` means *24 months and n-1 days after January 1, 1999*, or *n-1 days after January 1, 2001*.

When passed to the `.test()` method, the date is implicitly turned into a string. For instance, `new Date(99, 24, 5)` is converted to:

```
"Fri Jan 05 2001 00:00:00 GMT+0000 (Coordinated Universal Time)"

```

January is the only month whose 3-letter abbreviation ends in `-an`. So `/an 0[^9]/` is used to test if the date is between January 1 and January 8 (both included).

What we really want to know is whether we are between January 4 and January 11, but the corresponding regular expression would be significantly longer. It's shorter to do it that way and use an offset of -3 days instead. This is why **n** is initialized to -3.

### Commented

```
d => (                // d = input date
  g = n =>            // g is a recursive function taking a number of days n
    (                 //
      w =             // update w:
        /an 0[^9]/    //   if the following date x is between January 1 and
        .test(        //   January 8 (meaning that x + 3 days is within the
          x =         //   week including the 4th of January)
          new Date(   //     where x is defined as ...
            99, 24, n //       ... n-1 days after January 1, 2001
          )           //       (24 months and n-1 days after January 1, 1999)
        ) ?           //   then:
          ++y / y     //     increment the year y and set w to 1
        :             //   else:
          w + 1,      //     increment w
      q = (d - x)     // if x + 3 days is less than the target date d
          / 864e5     // i.e. the difference in days q between d and x
    ) > 3 ?           // is greater than 3:
      g(n + 8)        //   do a recursive call with n + 8,
                      //   i.e. one '8-day week' later
    :                 // else:
      [               //   return the result array:
        y,            //     year
        w,            //     week number
        5 + q         //     weekday: 8 + (q - 3)
      ]               //   end of array
)(-3, w = y = 2e3)    // initial call to g with n = -3 and y = 2000

```

# Answer
> 4 votes
# T-SQL, ~~83~~ ~~80~~ 76 bytes

Saved 2 bytes by 0-indexing weekday.

Solved without looping

```
SELECT
year(z|7^1),(datepart(y,z|7^1)+7)/8,z%8FROM(SELECT
datediff(d,2,@)z)t

```

**Try it online**

In order to show this method provides the correct results, I have included a link to compare **all test cases** from the question. This link is not 0 indexed to allow easy comparison

# Answer
> 3 votes
# JavaScript (Node.js), 166 bytes

```
d=>{w=(d-978336e6)/r+.5&7
for(D=0,e=new Date(d.getTime()+(7-w)*r);e.getMonth()!=0||e.getDate()!=4;D++)e.setTime(e.getTime()-r)
return[e.getYear(),8+D>>3,w+1]}
r=864e5

```

Takes input as a Javascript date object. Outputs as a 3-element list `[week-year, week number, weekday number]`. The week-numbering year is expressed as a 2-digit year (year minus 1900). If this is not acceptable, change `e.getYear()` to `e.getFullYear()` for +4 bytes.

Try it online!

**Huh?**

```
r=864e5 // milliseconds in a day
d=>{ // Take d as a date object
 w= // w is 1 less than the week number
  (d-978336e6) // milliseconds since Jan 1, 2001
  /r+  // Divide to get days
  .5&7 // Round (up or down) to nearest integer, and take mod 8.
       // This rounding smooths over DST and related variations
       // Variations over 12 hours do not occur, as far as I know
 for(
  D=0,  // D will be the number of days since the last Jan 4
  e=new Date(d.getTime()+(7-w)*r); // Initialize e to be the end of this week
  e.getMonth()!=0||e.getDate()!=4; // While e is not Jan 4 of any year:
   D++  // Increment D
  ) e.setTime(e.getTime()-r)  // Set e to the day before
 return [
  e.getYear(), // The week-numbering year of d is the same as the Gregorian year of the preceding Jan 4
  8+D>>3, // Convert days elapsed into weeks since Jan 4
  w+1 // the week number
 ]
}

```

# Answer
> 3 votes
# Python 3, 181 bytes

```
def c(t):
 y,w,d=2001,1,1;D=type(t);O=D.toordinal
 for o in range(730487,O(t)+1):
  y,w,d=(y,w,d+1)if d<8 else(y,w+1,1)if O(D(y+1,1,4))not in range(o,o+8)else(y+1,1,1)
 return y,w,d

```

Try it online!

My approach counts years, weeks and days for every proleptic Gregorian ordinal between `2001-01-01` and the date. `c` expects a `datetime.date` instance of a date on or after `2001-01-01`.

Every day the day counter is incremented unless a week has passed.
Every week the day counter is reset and the week counter is incremented, unless january 4th of the next year is in the next week.
Every year the week counter is reset and the year counter is incremented.

The magic number `730487` is the ordinal of `2001-01-02`: `730487 == datetime.date(2001, 1, 2).toordinal()`

c returns a tuple of integers containing the year, week number and day of the week in that order. week number and day of the week are `>=1`.

---
Tags: code-golf, date
---


# Question
Title: Solve the Halting Problem for Modilar SNISP
In the spirit of Solve the Halting Problem for Befinge, let's define another 2D language called *Modilar SNISP*. Modilar SNISP has the following six instructions:

* `\` directs the instruction pointer as follows:
    + if approached from the top, go right;
    + if approached from the right, go up;
    + if approached from the bottom, go left;
    + if approached from the left, go down.
* `/` directs the instruction pointer as follows:
    + if approached from the top, go left;
    + if approached from the left, go up;
    + if approached from the bottom, go right;
    + if approached from the right, go down.
* `!` skips over the next instruction.
* `@` pushes the IP location and direction onto the call stack.
* `#` pops an IP location and direction from the call stack and restores them, then skips over the next instruction. If the call stack is empty, execution halts.
* `.` does nothing.

The instruction pointer starts at the top left corner going right. If it ever leaves the playfield, execution halts.

Modilar SNISP cannot be more powerful than a PDA, because its only source of unbounded storage is a stack (the call stack) with a finite alphabet (the set of all IP (location, direction) pairs). The halting problem is decidable for PDAs, so this challenge should always be possible.

## The Challenge

Your goal is to write a program that takes a matrix of characters representing a Modilar SNISP program and returns one of two distinct outputs depending on whether it halts or not.

This is , so the shortest valid program (measured in **bytes**) wins.

## Specifications

* The way you take a matrix of character is flexible: a newline-separated string, array of strings, array of arrays of characters, 2d array of characters, flat array of characters with an integer representing width, etc. are all acceptable. The test cases opt for the first of those choices.
* You can assume that the input matrix will be rectangular (so you don't have to pad short rows) and will be of nonzero length and width.
* You can choose any two distinct outputs, not just truthy/falsy.
* You can assume that the input matrix will consist only of valid commands (`\`, `/`, `!`, `@`, `#`, and `.`).
* When a command is said to "skip the next instruction," you can assume that there will be a next instruction to skip. In particular, it will never be encountered in circumstances where (1) it lies on the playfield's edge and (2) the IP is moving perpendicular to that edge, such that the "next instruction" after it would lie outside the playfield.

## Test Cases

The following snippet can be used to test programs in the language. Note that it is slightly more permissive than the actual specification given here (e.g. it permits characters other than `.` as no-ops).

```
function htmlEscape(t){let i=document.createElement("span");return i.innerText=t,i.innerHTML}function tick(){snisp.tick(),snisp.update()}function run(){runButton.style.display="none",stopButton.style.display="",code.style.display="none",executionArea.style.display="",snisp.initialize(),intervalId=setInterval(tick,INTERVAL_MS)}function stop(){runButton.style.display="",stopButton.style.display="none",code.style.display="",executionArea.style.display="none",clearInterval(intervalId)}let TICKS_PER_SECOND=5,INTERVAL_MS=1e3/TICKS_PER_SECOND,runButton=document.getElementById("run-button"),stopButton=document.getElementById("stop-button"),code=document.getElementById("code"),executionArea=document.getElementById("execution-display"),intervalId,snisp={x:null,y:null,direction:null,callStack:null,stopped:null,playfield:null,padRows:function(){let t=Math.max(...this.playfield.map(t=>t.length));for(let i=0;i<this.playfield.length;i++)this.playfield[i]=this.playfield[i].padEnd(t,".")},initialize:function(){this.x=0,this.y=0,this.direction="right",this.callStack=[],this.stopped=!1,this.playfield=code.value.split("\n"),this.padRows(),this.update()},getCurrentChar:function(){let t=this.playfield[this.y];if(void 0!=t)return t[this.x]},backslashMirror:function(){let t={up:"left",right:"down",down:"right",left:"up"};this.direction=t[this.direction]},slashMirror:function(){let t={up:"right",right:"up",down:"left",left:"down"};this.direction=t[this.direction]},forward:function(){switch(this.direction){case"up":this.y-=1;break;case"down":this.y+=1;break;case"left":this.x-=1;break;case"right":this.x+=1;break;default:throw"direction is invalid"}},pushState:function(){this.callStack.push({x:this.x,y:this.y,direction:this.direction})},restoreState:function(){let t=this.callStack.pop();void 0!=t?(this.x=t.x,this.y=t.y,this.direction=t.direction):this.stopped=!0},tick:function(){if(this.stopped)return;let t=this.getCurrentChar();if(void 0!=t){switch(t){case"\\":this.backslashMirror();break;case"/":this.slashMirror();break;case"!":this.forward();break;case"@":this.pushState();break;case"#":this.restoreState(),this.forward()}this.forward()}else this.stopped=!0},generatePlayfieldHTML:function(t,i){let e=[];for(let n=0;n<this.playfield.length;n++){let s=[],l=this.playfield[n];for(let e=0;e<l.length;e++){let a=htmlEscape(l[e]);e==t&&n==i&&(a='<span class="highlight">'+a+"</span>"),s.push(a)}e.push(s.join(""))}return e.join("<br>")},update:function(){let t=[];for(let i=0;i<this.callStack.length;i++){let e=this.callStack[i];t.push(this.generatePlayfieldHTML(e.x,e.y))}t.push(this.generatePlayfieldHTML(this.x,this.y));let i=t.join("<br><br>");executionArea.innerHTML=i}};
```

```
#code{font-family:monospace;}#execution-display{font-family:monospace;white-space:pre;}.highlight{background-color:yellow;}
```

```
<b>Code:</b><br/><textarea id="code" width="300" height="300"></textarea><br/><button id="run-button" onclick="run()">Run</button><button id="stop-button" onclick="stop()" style="display: none;">Stop</button><br/><div id="execution-display"></div>
```

The ungolfed form can be found here.

### Halting

```
.

```

The smallest program possible. Goes out the right.

---

```
\\
\/

```

Winds around the program and goes out the top.

---

```
.\./.\
.\!/./

```

Goes in a loop. Winds through part of the track in two different directions.

---

```
@\!/#
.\@/#

```

Uses all six commands.

---

```
@.@.@.@.@.@.@.@.@.#

```

This program's execution time is exponential in the number of repetitions of `@.`, but it still halts.

---

### Non-Halting

```
!/\
.\/

```

I believe this is the shortest infinite loop.

---

```
@!\\#/@\!\
//@//.#./.
.\#.!\./\.
#.\!@!\@//
/..@.@\/#!
\.@.#.\/@.

```

---

This winds around the track, spawning stack frames occasionally, before eventually getting caught in a cycle infinitely generating stack frames. Not all commands are actually used.

```
.!/@.@.@.@.@.\
/.@.@.@.@.@.@/
\@.@.@.@.@.@.\
/.@.@.@.@.@.@/
.@\@.@.@.@.@.\
\.@.@.@.@.@.@/

```

Keeps creating stack frames, but none of them ever return.

# Answer
# Python 3, ~~639 bytes~~ ~~630 bytes~~ 593 bytes

```
def e(I):
 m=[(0,-1),(0,1),(1,1),(1,-1)];a=lambda i:(tuple(i[0]),i[1]);b=lambda s,q:s.s==q.s and s.S&q.S==q.S
 class O():i=[[0,0],2];S=[];A={}
 def z():d=m[O.i[1]];O.i[0][d[0]]+=d[1]
 def y():O.i=O.S.pop();z()
 def x():O.i[1]=[3,2,1,0][O.i[1]]
 def w():O.i[1]=[2,3,0,1][O.i[1]]
 def v():O.S+=[[O.i[0][:],O.i[1]]]
 while 1:
  p=O();p.s=a(O.i);p.S={a(i)for i in O.S};l=O.A.setdefault(p.s,[]);c=any((b(p,s)for s in l));l+=[p];e=O.i[0];d=not((0<=e[0]<len(I))and(0<=e[1]<len(I[0])))or((x,w,z,v,lambda:len(O.S)==0 or y(),lambda:0)["\\/!@#.".find(I[e[0]][e[1]])]()==1);z()
  if d!=c:return not c or d

```

Try it online!

I feel like this is more of minified source than golf... I'm sure there's a better way to get there.

Program works as a full interpreter for the language. It stops either when:

1. We exit the program
2. We detect we're in a loop.

Loop detection is somewhat naive (and memory heavy). Before we evaluate each move, we cache off our current Direction, Position, and Stack. If we see we've come to a position we've been to before, moving the same direction, and our current stack is a super set of a previous stack at this position + direction, then we know we're in a loop and the stack is either growing (or staying constant).

Edit 1 - Thanks to Herman L for cutting "pass". Also cut "True".

Edit 2 - Lambda-ified some functions. Reduced number of returns. Returns "True" for terminating and "False" for non-terminating. Leveraged existing O class as tracking object, eliminating the need for N class.
> 5 votes

# Answer
# JavaScript (ES6), ~~258~~ 254 bytes

```
p=>(d=>{for(x=y=r=k=1,s=[],v={};w=[--x,--y,d],c=1<<"\\!@/#".indexOf(q=(p[y]||0)[x]),q&&r&&(e=v[w]?v[w].some(u=>!s.some(t=>u+0==t+0)):1);x+=d>>2,y+=d&3)v[w]=[...s],k=k?c&9?d=c&1?d/4|4*d&12:(d+5)%10:c&4?s.push(w):c&16?(r=s.pop())&&!([x,y,d]=r):c-2:1})(9)|e

```

Expects a non-empty program as an array of strings, where each element represents a line of Modilar SNISP. Outputs `1` if the given program halts, and `0` otherwise.

Same logic as @machina.widmo's answer. A few failed attempts at alternative methods led me to conclude that they'd produce longer code anyway!

Try it online!

## Explanation

Similar to the other answer, this function exits with:

* `1` if the program halts (e.g. the IP moves off the grid or an empty stack is popped)
* `0` if the IP reaches a **position** it has already visited, moving in the same **direction**, and with a **superset** of the stack present in the previous visit.

### Why the same direction?

```
 1
!\/

```

The above program halts, but hits the same position (character 1), with an identical stack, but from a different direction.

### Why a superset and not merely stack size?

```
  ab4
!/@@.\
.\..#/

```

This also halts, and the IP hits character 4 from a consistent direction four times, with the following stack states (`*` indicates the top of the stack):

* size = 2 \[a, b\]\*
* size = 1 \[a\]\*
* size = 1 \[b\]\*
* size = 0 \[\]\*

### How the interpreter works

Instructions (`q`) are translated into binary (`c`) as follows (with all other characters, `.` or otherwise, serving as nops):

```
1 2 4 8 16
\ ! @ / #

```

Direction (`d`) is represented as a bit field:

```
9 -> right : 1001
1 -> left  : 0001
6 -> down  : 0110
4 -> up    : 0100

```

Mirrors (`\/`) transform the direction:

`\`: 6-\>9 9-\>6 4-\>1 1-\>4

`d/4 | 4*d&12`

`/`: 1-\>6 6-\>1 4-\>9 9-\>4

`(d+5) % 10`

New directions transform the position:

`x += d>>2 - 1`

`y += d&3 - 1`

### Other global variables

* `x`, `y`: IP position
* `r`: holds value popped off the stack
* `k`: falsy if skipping the next instruction (e.g. from `!#`)
* `s`: stack
* `v`: caches visited positions, direction, snapshot of stack
* `w`: `[x, y, d]`, the value stored on the stack and used as the key value for `v`
* `e`: falsy if program does not halt due to a cache match

### Ungolfed

```
p => (d => {                                                  // set initial direction and avoid a verbose `return` statement
    for (
        x = y = r = k = 1,
        s = [],
        v = {};
        w = [--x, --y, d],                                    // decrement positions early so that x,y
                                                              // do not require a separate assignment to 0
        c = 1 << "\\!@/#".indexOf(q = (p[y]||0)[x]),          // taking an index of undefined produces an error; using 0 does not
        q && r && (
            e = v[w]
                ? v[w].some(u => !s.some(t => u+0 == t+0))    // in order to compare two arrays, must coerce to strings
                : 1
        );
        x += d>>2,
        y += d&3
    )
        v[w] = [...s],                         // clone stack
        k = k
            ?
                c&9                            // if \ or /
                    ? d = c&1
                        ? d/4 | 4*d&12
                        : (d+5) % 10
                : c&4                          // if @
                    ? s.push(w)
                : c&16                         // if #
                    ? (r = s.pop())
                        && !([x, y, d] = r)    // destructure value in stack if any exists
                : c-2                          // 0 if !
            : 1
})(9) | e

```
> 2 votes

# Answer
# APL (Dyalog Unicode), 93 bytes

```
⍬{~1∊∊⍺⍷¨⊂⍵:(⍺,⊂⍵)∇(1↓⍵),⍨⊃⍬(⊂1⌽⍉g)(⊂⍉⊖⌽1⌽g)(⊂2⌽g)((1⌽g)(2⌽g))(⊂1⌽g)⌷⍨'#\/!@.'⍳⊃⊃g←⊃⍵}⊂1⍪⍨⎕,0

```

Try it online!

Instead of moving the IP around the grid, we move the grid around the IP, so the current IP is always at the top-left with direction pointing right.

Raises an IndexError to indicate halting; no error indicates a non-halting SNISP program.

```
(⊂1⌽g)⌷⍨'#\/!@.'⍳⊃⊃g←⊃⍵}⊂1⍪⍨⍵,0}
⍬{~1∊∊⍺⍷¨⊂⍵:(⍺,⊂⍵)∇(1↓⍵),⍨⊃⍬(⊂1⌽⍉g)(⊂⍉⊖⌽1⌽g)(⊂2⌽g)((1⌽g)(2⌽g))(⊂1⌽g)⌷⍨'#\/!@.'⍳⊃⊃g←⊃⍵}⊂1⍪⍨⎕,0
          ⊂1⍪⍨⎕,0 ⍝ Pass an initial stack: the input padded with 0s on the right and 1s on the bottom
                   ⍝ This lets us treat the program grid as wraparound
                   ⍝ 1 and 0 could be any 2 distinct values not in '#\/!@.'
                   ⍝ They have to be different to differentiate SNISP programs that are symmetric on the main diagonal
⍬                 ⍝ Pass an initial stack history
 {...}            ⍝ Inner function:
 ~1∊∊⍺⍷¨⊂⍵:        ⍝ Only continue if the stack is not a prefix of any member of the stack history
                    ⍝ Prefix because the top of the stack is the first element and gives the current direction/position
 (⍺,⊂⍵)∇           ⍝ Recurse with an appended stack history and an updated stack:
          g←⊃⍵      ⍝ Pop the current grid off the stack
      ⍬...⊂1⌽g      ⍝ A list of all possible stack changes. Will add to the stack:
       ⍬             ⍝ #: nothing, so the next step pops the stack
       ⊂1⌽⍉g         ⍝ \: transposed grid, wrap-rotated right by 1; the new IP is 1 unit down
       ⊂⍉⊖⌽1⌽g       ⍝ /: new grid such that the new IP is at the current bottom-left
       2⌽g           ⍝ !: new grid has IP 2 units to the right
       (1⌽g)(2⌽g)    ⍝ @: push both 1⌽g, which is the same as the '.' instruction,
                      ⍝ and 2⌽g, which is the same as the '!' instruction.
                      ⍝ The 1⌽g will be immediately popped for the next position
       ⊂1⌽g          ⍝ .: Push 1⌽g, which simply moves the IP 1 unit to the right
   ⌷⍨'#\/!@.'⍳⊃⊃g   ⍝ Get the next-grid corresponding to the character under the IP
                     ⍝ If that character is 0 or 1, then the pointer has walked off the edge,
                     ⍝ This causes an IndexError since 7='#\/!@.'⍳1, and the list of
                     ⍝ stack changes has only 6 elements
                     ⍝ If the stack is empty, and there is no current grid,
                     ⍝ then it would also try to get the 7th elements, also raising the IndexError
    (1↓⍵),⍨⊃        ⍝ Add the next grid to the beginning (top) of the popped stack

```
> 2 votes

---
Tags: code-golf, decision-problem, interpreter, halting-problem
---


title: Is it a geometric sequence or not?

text:
# Question
Title: Is it a geometric sequence or not?
Well, last time I asked for an arithmetic sequence, now comes the geometric sequence

# Challenge

In this challenge, the input will be an unordered set of numbers and the program should be able to tell if the set of numbers is a Geometric Sequence.

# Input

* The input will be a set separated by `,`(comma).

# Output

* The Output can be a Boolean (True or False), or a number (1 for True, 0 for False).

# Test cases

```
In: 1,3,9
Out: True

In: 1,4,16
Out: 1

In: 2,6,14
Out: 0

In: 2,8,4
Out: True

In: 4,6,9
Out: 1

```

# Rules

* This is , so the shortest code by bytes wins.
* The minimum length of the input set would be 3 elements.

Best of Luck

# Answer
# , 15 14 13 bytes

```
1=&#&=2%/\/:~

```

Try it online!

*-1 byte thanks to xash*

*-1 byte thanks to Bubbler*

* `1=` Does one equal...
* `&#&=` the length of the uniq of...
* `2%/\` the list created by dividing each element by its right neighbor in the input list...
* `/:~` sorted.
> 4 votes

# Answer
# Jelly, 4 bytes

```
Ṣ÷ƝE

```

Try it online!

Thanks to fireflame241 for pointing out a mistake

## How it works

```
Ṣ÷ƝE - Main monadic link, takes an array as input
     - e.g                            A = [2, 8, 4] or   A = [2, 6, 14]
Ṣ    - Sort                               [2, 4, 8]          [2, 6, 14]
  Ɲ  - Over overlapping pairs [x, y]...   [[2, 4], [4, 8]]   [[2, 6], [6, 14]]
 ÷   - ...divide x by y?                  [0.5, 0.5]         [0.33, 0.43]
   E - Is the list all the same?          1                  0

```
> 7 votes

# Answer
# APL (Dyalog Unicode), ~~25~~ 19 bytes

```
{~∨/⌈(⊣-⊃)2÷/⍵[⍋⍵]}

```

Try it online!

*-6 bytes thanks to @Adám*

```
⍵[⍋⍵]      ⍝ sort ⍵
2÷/        ⍝ Take the quotient of all consecutive pairs
           ⍝ Check if all are equal:
(⊣-⊃)       ⍝ Subtract the first quotient
~∨/⌈        ⍝ Are all 0?

```
> 2 votes

# Answer
# Retina, 56 bytes

```
N`\d+
Lv$`\b\d+,(\d+),(\d+)
;$2**_;$1*$1*
A`(;_+)\1\b
^$

```

Try it online! Link includes test suite. Explanation:

```
N`\d+

```

Sort in ascending order.

```
Lv$`\b\d+,(\d+),(\d+)

```

List all triples of numbers.

```
;$2**_;$1*$1*

```

For each triple `a,b,c` calculate `ca` and .

```
A`(;_+)\1\b

```

Delete all lines where they equal.

```
^$

```

Check that there were no unequal triples.

Note that this runs in unary so it fails on large numbers, but you can use this similar 62-byte program that does the calculations in decimal instead:

```
N`\d+
Lv$`\b\d+,(\d+),(\d+)
;$.($2**);$.($1*$1*
A`(;.+)\1\b
^$

```
> 1 votes

# Answer
# JavaScript (ES6), 47 bytes

Returns a Boolean value.

```
a=>!a.sort((a,b)=>b-a).some(p=n=>a-(a=p/(p=n)))

```

Try it online!
> 1 votes

# Answer
# , 38 bytes

```
function(x)!sd(diff(y<-sort(x))/y[-1])

```

Try it online!

* sort x
* calculate difference between successive elements
* divide by value of each element (except first) = fold-difference
* check if results are all the same (standard deviation = zero)

Fails for negative fold-differences between elements (which seems to be a true geometric sequence, but it isn't clear whether this is required by the challenge). Fixed by sorting x by absolute value, at a cost of +9 bytes:

**47 bytes**

```
function(x)!sd(diff(y<-x[order(abs(x))])/y[-1])

```
> 1 votes

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

Saved a byte thanks to Surculose Sputum!!!

```
lambda l:l.sort()!=len({b/a for a,b in zip(l,l[1:])})<2

```

Try it online!
> 1 votes

# Answer
# APL(NARS), 14 chars, 28 bytes

```
{1=≢∪2÷/⍵[⍒⍵]}

```

it seems 2÷/1 3 9 do 1÷3 3÷9 and 2,/1 3 9 make couples

```
  h←{1=≢∪2÷/⍵[⍒⍵]}
  ⎕fmt {⍵,⊂,h⍵}¨(1 3 9)(1 4 16)(2 6 14)(2 8 4)(4 6 9)
┌5─────────────────────────────────────────────────────────────────┐
│┌4─────────┐ ┌4──────────┐ ┌4──────────┐ ┌4─────────┐ ┌4─────────┐│
││      ┌1─┐│ │       ┌1─┐│ │       ┌1─┐│ │      ┌1─┐│ │      ┌1─┐││
││1 3 9 │ 1││ │1 4 16 │ 1││ │2 6 14 │ 0││ │2 8 4 │ 1││ │4 6 9 │ 1│││
││~ ~ ~ └~─┘2 │~ ~ ~~ └~─┘2 │~ ~ ~~ └~─┘2 │~ ~ ~ └~─┘2 │~ ~ ~ └~─┘2│
│└∊─────────┘ └∊──────────┘ └∊──────────┘ └∊─────────┘ └∊─────────┘3
└∊─────────────────────────────────────────────────────────────────┘

```
> 1 votes

---
Tags: code-golf, math, number, sequence, decision-problem
---


title: Cheat activated

text:
# Question
Title: Cheat activated
## Background

The game Grand Theft Auto: San Andreas went down in history also thanks to its wide selection of cheats. They're almost 90 and anyone who has ever touched this game, no doubt has tried them all!
One cheat is activated (on PC) typing in-game a secret keyword, and then boom, a jet pops out of thin air or perhaps all pedestrians look like Elvis Presley or some other rowdy effect...

*They always come with this confirmation message:*

Rockstar chose to store them hashed, so due to collisions, in addition to the intended ones there are many other strings that trigger each cheat.

Therefore I propose to solve this downside!

## Task

Write a full program that prints `CHEAT ACTIVATED` *if and only if* the last part of a string is a `cheat code`.

## Cheat codes

```
THUGSARMOURY
PROFESSIONALSKIT
NUTTERSTOYS
INEEDSOMEHELP
TURNUPTHEHEAT
TURNDOWNTHEHEAT
PLEASANTLYWARM
TOODAMNHOT
DULLDULLDAY
STAYINANDWATCHTV
CANTSEEWHEREIMGOING
TIMEJUSTFLIESBY
SPEEDITUP
SLOWITDOWN
ROUGHNEIGHBOURHOOD
STOPPICKINGONME
SURROUNDEDBYNUTTERS
TIMETOKICKASS
OLDSPEEDDEMON
DOUGHNUTHANDICAP
NOTFORPUBLICROADS
JUSTTRYANDSTOPME
WHERESTHEFUNERAL
CELEBRITYSTATUS
TRUEGRIME
ALLCARSGOBOOM
WHEELSONLYPLEASE
STICKLIKEGLUE
GOODBYECRUELWORLD
DONTTRYANDSTOPME
ALLDRIVERSARECRIMINALS
PINKISTHENEWCOOL
SOLONGASITSBLACK
FLYINGFISH
WHOATEALLTHEPIES
BUFFMEUP
LEANANDMEAN
BLUESUEDESHOES
ATTACKOFTHEVILLAGEPEOPLE
LIFESABEACH
ONLYHOMIESALLOWED
BETTERSTAYINDOORS
NINJATOWN
LOVECONQUERSALL
EVERYONEISPOOR
EVERYONEISRICH
CHITTYCHITTYBANGBANG
CJPHONEHOME
JUMPJET
IWANTTOHOVER
TOUCHMYCARYOUDIE
SPEEDFREAK
BUBBLECARS
NIGHTPROWLER
DONTBRINGONTHENIGHT
SCOTTISHSUMMER
SANDINMYEARS
KANGAROO
NOONECANHURTME
MANFROMATLANTIS
LETSGOBASEJUMPING
ROCKETMAN
IDOASIPLEASE
BRINGITON
STINGLIKEABEE
IAMNEVERHUNGRY
STATEOFEMERGENCY
CRAZYTOWN
TAKEACHILLPILL
FULLCLIP
IWANNADRIVEBY
GHOSTTOWN
HICKSVILLE
WANNABEINMYGANG
NOONECANSTOPUS
ROCKETMAYHEM
WORSHIPME
HELLOLADIES
ICANGOALLNIGHT
PROFESSIONALKILLER
NATURALTALENT
OHDUDE
FOURWHEELFUN
HITTHEROADJACK
ITSALLBULL
FLYINGTOSTUNT
MONSTERMASH

```

## Input

* A string \\$s\\$ over the alphabet:
`[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z]`

## Output

* Print `CHEAT ACTIVATED` if there exists a `cheat code` \\$c\\$ such that \\$c\\$ is a suffix of \\$s\\$
* Nothing otherwise

This is , so the shortest code wins.

# Answer
> 8 votes
# Python 3,  ~~976~~  965 bytes

*Saved 11 bytes thanks to @user202729*

Nothing fancy here. This is a hand-crafted regular expression which was randomly shuffled to please zlib and save a few more bytes.

```
import zlib,base64,re
if re.search(zlib.decompress(base64.a85decode('''GaqK,9,=TU&D^"aoJ0#fKbc'=7=3*ZC@Sjrb9-nO,G4ij>guO6,*oNLi[tq[ZsOTo,XZG;oZsh/gQt)R:U?gtgs2QpS5&Cl,CM,c4B%`<W5ZEuN=Sb$f!,mP`%@TQ:&Dg(:q8*+N)Y?Q#F9kM'KZ&%\I2W`#7oOUp1-0Ge3]q_o8g@lWflG`*QMr*9[[`i?a`=U:auDF%8=66MDaNUUiPI8J#lO0\l@*E:%PS)VCHdD>/N`=l1`t*hVA<^ON+dhUtN/]3U\\tupZtkD$:DPFh-HW3PZ$AAiEFm(g;<YJ6I4"uMdQX16JBN/W.`>QFrON6O,^B%Jl3Mn<d^IObA<=$[b;g`-:O$Ga?$ch!SrhQNm;`Led6I;8/VCeIra;1&X%b)&*]\XB4+g3`FkTT#fc%HR8*)g95de$99CT;oVaps<Yn\im/BJu&A6-O8L3#Ha0p6]PKP2a7,,T6[K>'rQiC1R,U1_Ko/:-EAfrcS7ik6HfK>2:cMot]rkBY#!9d"ujd=<dn@]JT9h=mClIt.YL?*b"(ImA*!E/(\Gob*ghDs1dJ.;O"]CPGTo!=5g=9e2+caXT43.mu:*o8`ai!KoaLJ5',M&K[V8d'?J=ISEG?GUZMbWXJ[iCde,Mu[(,9nY8%-73jGpPZFWBXSOTGg5:U<P2"/=V(g[PZJodG+cZuag^64TE.>i4i"BRD8=mu,Jga5Ip(0Z34oicZ"d'bi@2Bqe/D6Y*)Cc-#tb7!E4Q']mZ0F2M]&qrpj]qLqg0MLln_4Q7QA[9<@I^3OJAJ)p1?+NpZH)nYYp(.J''*9mJUg?9h.]o72ZKgN)90W>0sIe(IqbdBCsfj<Ma5N''')).decode(),input()):print('CHEAT ACTIVATED')

```

Try it online!

Or See the uncompressed regex

# Answer
> 6 votes
# 05AB1E, 753 bytes

```
.•ćÉÞû9‚2¬ú@iH°<]ĆA~Qò†ø‚”Kƒćž»”‚ŸǝD6øZ\§HÔØΔÚÿþjvĀ¤¼§….[Ωîužć“₅nÕbn`ιwU0›•#`’ÿ¨¥€´y ‡ªsíÃ ÝæÿŠ… i‚Û€ä€Ô ‹‡€¾€€š¢ ‹‡„‹€€š¢ À®ly©Ã …«Â£…ß ÿ‚Ž ‹€€†€ƒ‰Ï…Û ÏÏ€È‚Ã›Î…ì €º‚‰f´‹€‹ ŠÍ€•€¾ ¥€€•„‹ À¸ÿ€´Â° ‹®â¢€‰€á á€€‹Ýæÿ €º€„»áí„ „ÏŠÍ«™n ÿÝæ‡´i¦§ €–€‡‚Æ¶¨ ‚‰‡Ü€ƒ‹®€á ‚Ãs€€¼§ ¨À‡‚ ‰¦ÿ €Ÿˆ™‚œÒÞ ¯š€É‚µ ©ß€èÿ ‚¿Þ¡ÿ‚ï ¬Í‡Ü€ƒ‹®€á €Ÿ¢ž€™žÜs ™Å€ˆ€€€¢îÁ ¸•ÿ®ísƒÏ °ä•Ç €Ðâì€Ÿ€€Èšs Ó´f€á€¾ ÞŸ€ƒ‹ˆ ‡—ÿŠë œÆ€‚€€™¨‚… ‚ìsaˆÁ €É€¨€ˆï¶ …ç‹€¹¶s ÿ‰à „Î¡¤ÿ€Ÿ ŽÇ€ˆ—‹ ŽÇ€ˆ›Í c•»tyc•»ty±»±» cjƒ¿€¨ ïÅ³• iƒ¾€„h‚Š ›ä€¯ƒ´€î—Ç ŠÍÿ Íˆˆ™ †æˆ×ÿ ¬ÍîŸ€‰€€†æ µ±Ž€ ³Ö€†€¯ÖÇ ÿ €¸€µ€©»å€á …Ž€šÿ ´Û‚œŠàëÌ ÕÕ…Ž i€·€œi‚µ îŸ€•€‰ st±µ€èaÍÝ i€Ü‚ÒàŠ ‚‹€‚™‰ ©„‰à ƒ¶acŽÏ¼Ã ‚è¡¹ iÅËˆ¬€‹ ·ä‰à ÿ´™e ÅË€ï€†€¯³£ €¸€µ€©‹®€ª ÕÕ€¿ÿ º°€á Ÿ™£Í i€©‚œ€Ÿ†æ ‡ªÃ½ ˆÃ¼Î ŠçÞ® †ì¦³ˆ¦ •»€€†â—É €ç€ŸÅÍ °ä€„ÿ ±¹mÌ¢’u#Å¿à‘Ç¥Ù‡‘×

```

Try it online or verify all the cheat-codes.

**Explanation:**

```
.•ćÉÞ...U0›•   # Push compressed string "stunt hem hicksv atlantis kangaroo wler freak quer ninja suede nga cruel glue grime dough ters neighb dulldull ters thugs"
 #             # Split it on spaces to a list
  `            # Pop and push all strings separated to the stack
’ÿ¨¥...mÌ¢’    # Push dictionary string "ÿarmoury professionalskit nutÿtoys ineedsomehelp turnuptheheat turndowntheheat pleasantlywarm toodamnhot ÿday stayinandwatchtv cantseewhereimgoing timejustfliesby speeditup slowitdown roughÿourhood stoppickingonme surroundedbynutÿ timetokickass oldspeeddemon ÿnuthandicap notforpublicroads justtryandstopme wheresthefuneral celebritystatus trueÿ allcarsgoboom wheelsonlyplease sticklikeÿ goodbyeÿworld donttryandstopme alldriversarecriminals pinkisthenewcool soloÿsitsblack flyingfish whoateallthepies buffmeup leanandmean blueÿshoes attackofthevillagepeople lifesabeach onlyhomeisallowed betterstayindoors ÿtown loveconÿall everyoneispoor everyoneisrich chittychittybangbang cjphonehome jumpjet iwanttohover touchmycaryoudie speedÿ bubblecars nightproÿ dontbringonthenight scottishsummer sandinmyears ÿ noonecanhurtme manfromÿ letsgobasejumping rocketman idoasiplease bringiton stinglikeabee iamveryhungry stateofemergency crazytown takeachillpill fullclip iwannadriveby ghosttown ÿille wannabeinmygang noonecanstopus rocketmayÿ worshipme helloladies icangoallnight professionalkiller naturaltalent ohdude fourwheelfun hittheroadjack itsallbull flyingtoÿ monstermash",
               # where the `ÿ` are automatically filled with the strings on the stack
 u             # Convert it to uppercase
  #            # Split it on spaces
   Å¿          # Check for each word whether the (implicit) input-string ends with it
               # (1 if truthy; 0 if falsey)
     à         # Check if any are truthy by taking the maximum
      ‘Ç¥Ù‡‘   # Push dictionary string "CHEAT ACTIVATED"
            ×  # Repeat the string the integer amount of times
               # (so once for truthy; and it becomes an empty string for falsey)
               # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*) to understand how compressed string `.•ćÉÞ...U0›•` and dictionary strings `’ÿ¨¥...mÌ¢’` and `‘Ç¥Ù‡‘` work.

# Answer
> 5 votes
# Retina 0.8.2, ~~1094~~ 1082 bytes

```
HE
g
Tg
y
ST
a
GO
b
TT
c
DO
d
IT
e
AS
f
LE
h
IN
i
AN
j
AR
k
LL
l
OU
m
RO
n
ES
o
ON
p
ER
q
ED
r
AT
s
HO
t
IC
u
jD
w
Al
x
ME
z
NIGHT
=
M`(THUGSkMmRY|PnFoSIpAL(SKe|KILhR)|(SURRmNDrBYNUcq|NUcqaOY|TIzTOKuKf|NOTFORPUBLunAD|CEhBReYasU|xDRIVqSkECRIMiAL|BEcqaAYidOR|BUBBhCk|SwiMYEk|MjFnMsLjTI)S|(DUlDUlDA|TIzJUaFLIoB|IAMNEVqHUNGR|asEOFEMqGENC|IWjNADRIVEB)Y|(aOPPuKibN|TRUEGRI|CJPHpEt|WORSHIP)z|(JUaT|dNc)RYwaOPz|NOpECj(aOPUS|HURTz)|iErSOzgLP|T(URN(UP|dWN)ygs|OODAMNtT|mCHMYCkYmDIE|AKEACHIlPIl)|PhfjTLYWkM|aAYiwWsCHTV|CjTSEEWgREIMbiG|S(PEr(FREAK|eUP)|LOWedWN|OLpGfeSBLACK|COcISHSUMMq)|RmGHNEIGHBmRtOD|OLDSPErDEMp|dUGHNUTHwuAP|WgRoyFUNqAL|xCkSbBOOM|(WgELSpLYPhf|auKLIKEGLU|IdfIPhf|aiGLIKEABE|OHDUD)E|bODBYECRUELWORLD|PiKISyNEWCOOL|FLYiG(TOaUNT|FISH)|WtsExyPIo|BUFFzUP|hjwzj|BLUoUroto|AcACKOFyVIlAGEPEOPh|LIFoABEACH|pLYtMIoxOWr|LOVECpQUqSx|EVqYpEIS(POOR|RuH)|(CHIcY){2}BjGBjG|JUMPJET|IWjcOtVq|=PnWhR|dNTBRibNy=|KjGkOO|hTSbBfEJUMPiG|nCKETM(j|AYgM)|BRiGep|(Gta|CRAZY)TOWN|NiJsOWN|FUlCLIP|HuKSVILh|WjNABEiMYGjG|glOLADIo|ujbx=|NsURALTAhNT|FmRWgELFUN|HeynADJACK|eSxBUl|MpaqMfH)$
0

1
CHEAT ACTIVATED

```

Try it online!

Verify all matches

This solution is based on the observation that many letter pairs repeat several times in different cheat codes. We can replace those common pairs with lowercase letters (since the input will be in all uppercase) before executing the main regex.

Common letter pairs were generated using this program

# Answer
> 2 votes
# Stax, 744 bytes

```
ú↓╒E╢≤3░ü(⌡▬α▲Kw~Eæ║aù≡╕↓╠ækîª♥J╠⌂ÿb╞╝ø└╫£φ├╡▌ê╔ê;y9¿¿¢Ö⌡D◘MB╡ú:¢▌BÇ!ÜÅ?╫-◙¥·╘hM┌ûoƒPå¢¿δ╓x╓7╤½{α█hè▄ΔZ∙╙d≥♀'ô▼╘[πCò"┬╦•ù,╫▀╚╟TεÿRD°ß£{♠╕~>G╧ÜG⌠é~F~⌐?Iê→LA╟αa°♦V╔xhU∟δ¶╧▀Dïîc╫►τ8üîÄ╠⌂○╣*i☻▌ƒç╥¿ÇàM H─▬½÷`bû>miWπ∞*ü\σ¶REuü╚∙╠K┌ΦîΣ╫←▒╜A+░Ñ@)nφ₧∞'i╤Su@↑⌂¥ynΓv█e-0y╧Å§∟8φ·k½▌↑ëK╡7╛ƒ └¥τ─~↕τ╫^sh<▀Ö¥4╟╔«▼»0┌▌ûÆ↨1ñFf┘ê▒}[d↔ätf,▀⌂qt‼≈Xⁿ←ìhà⌂ÇΦXDÿs═JéΔ♠ö╙═[═4○tºyBoz?e╔§▐Ñ│δ`♣m♠°⌐ñ▐b╙|I₧◙Çq╧WNÿ:hYⁿ╝Ö┤ Ö╟╗φW@‼¡Δ¥♥£<Mÿt·╛~Ö◘U3∞P♂πΩ○U÷₧ï↨75-]├╢▒║3#│‼8^7.♦▼2↨8├Fⁿ♥>º√√─Ö¥┌Æ☼;∙Δ;+ï♪≥àΔñö╢íhåhò╤7e╣D┼┌τ·▐\½N⌂se0░╖1NmQQChs╕ë╒┌≈Å■╓{]&§╦π◄▲┘#?◙èáK?A▲≤û}╥5V#(¢⌠ü,∟δ$:åΓ↑╟ΘΘ±○«╠j┐≈o,v♦ì9╜æ-K│↑♀fwß☻δA┐┼à◄?║H√╖¿Æ↨á░Ö╗╣ΩÄú╢Mé=Ä▌↔→a°◘^j►╡┐t'◄wΔh←▬╜δt♫¡ïù«○├α7♣G▼K]H┬>♥á»φ9öù|╜Δ╥Éï¬¡.╚øKôªRø─Ç╞╗}₧4◙|`▓íâM ╥╨uⁿYéΔß☻¶∟ëæ┤,á╔∞₧Hæ}♪↑ßvâúy[>lu7▌z╒sóÄO:L▬╦íDq§φiIΔ═ûδ▓^ff▒

```

Run and debug it

It relies heavily on compressed string literals, and there's not too much interesting about it.

# Answer
> 2 votes
# JavaScript, 1200 bytes

`s=>/(ALL(CARSGOBOOM|DRIVERSARECRIMINALS)|ATTACKOFTHEVILLAGEPEOPLE|BETTERSTAYINDOORS|BLUESUEDESHOES|BRINGITON|BUFFMEUP|CELEBRITYSTATUS|DOUGHNUTHANDICAP|DULLDULLDAY|EVERYONEIS(POOR|RICH)|FLYING(FISH|TOSTUNT)|FOURWHEELFUN|FULLCLIP|GOODBYECRUELWORLD|HELLOLADIES|HICKSVILLE|IAMNEVERHUNGRY|INEEDSOMEHELP|ITSALLBULL|IWAN(NADRIVEBY|TTOHOVER)|JUMPJET|KANGAROO|LEANANDMEAN|LIFESABEACH|LOVECONQUERSALL|MANFROMATLANTIS|MONSTERMASH|NATURALTALENT|NIGHTPROWLER|NOONECAN(HURTME|STOPUS)|NOTFORPUBLICROADS|NUTTERSTOYS|OHDUDE|OLDSPEEDDEMON|ONLYHOMIESALLOWED|PINKISTHENEWCOOL|PLEASANTLYWARM|PROFESSIONAL(KILLER|SKIT)|ROCKETMA(N|YHEM)|ROUGHNEIGHBOURHOOD|SCOTTISHSUMMER|SLOWITDOWN|SPEED(FREAK|ITUP)|STA(TEOFEMERGENCY|YINANDWATCHTV)|STI(CKLIKEGLUE|NGLIKEABEE)|SURROUNDEDBYNUTTERS|TAKEACHILLPILL|THUGSARMOURY|TIME(JUSTFLIESBY|TOKICKASS)|TOODAMNHOT|TOUCHMYCARYOUDIE|TURN(DOWN|UP)THEHEAT|WHERESTHEFUNERAL|WHOATEALLTHEPIES|(HITTHEROADJ|SOLONGASITSBL)ACK|((CHITTY){2}BANGB|WANNABEINMYG)ANG|(BUBBLEC|SANDINMYE)ARS|(CANTSEEWHEREIMGO|LETSGOBASEJUMP)ING|(CJPHONEHO|(DON|JUS)TTRYANDSTOP|STOPPICKINGON|TRUEGRI|WORSHIP)ME|(DONTBRINGONTHE|ICANGOALL)NIGHT|(IDOASI|WHEELSONLY)PLEASE|(CRAZY|GHOST|NINJA)TOWN)$/.test(s)?'CHEAT ACTIVATED':''`

Try it online!

# Answer
> 2 votes
# JavaScript (Node.js), 996 bytes

```
a=0n;process.argv[2].match(require(`zlib`).unzipSync(Buffer("\"T93)OC8m{J84WLB/+&GTui0kf`VU#jJp;3(nOUQ))1b/-^*.t&O'V58#/0;D$- /te\"l_)RiO<j]tu=ck_:{b,bL^?Gm'^`%I5M;I{g\\GA-\\kud?RvYIH8=nvGq|{S l-zt5?.(zt9thR%m.v=[|hJZW7^/1RYRTJ8+)_>V-k!)[c2y1Ra5];'BM+#+!n-2\\nl;libQ7NmmYjG*0$n=S;=<W)dm/(vF=Q'zuYjfx2p,OBrqGc%upq28Y65rxj`@+]P6@s^O#A9G==H*bCz3G'rNADJOFs{8k~8#8.&Y|1=soo(JS>iVRy?Gj})\"?t NCjVmoUUDo*B98e-`xYyA#X#El;vqDjJwNb8cE|~@N).v3TT{?Kk*M1zw`y:}{$\\DPj\\GVv0lgP;5satf1\"K}4G:Jc1xt]OXCu^$#u&4?NA:Od)v+!+'1=TrUBx2vfh'~HFyXZ1BzK4(Dh_-_';/A}:SxM` !3\"4qXIjrCu$]]r+$P,6_+PqH#IU9,><UJ4U#[wEb`<,f%X*dr<#2V_U\"BjiPA]En0Ls\\yt61u #m@3rm6e]NMBR_\\La.7|9^)uh/$Ef.w^7{mn;~ug\\w`3MDQPb$IR}_2A3qkc:V>rC9|xC/0g:_A'nuV<Q ugVj|`1<(]*a~.jFlp$'Mw[gDF<E]5I$tbg\\10'xvwUBeWBk8g2( XjBhu*Y(KK}Yzu}(,YY6.5TcF)u9'=M[Lb4^ /g#<P$$3*>i}.Y4]m$2e1@c\\>dAW?O`DdexO=jB$7!bJ'/|O:X,}]|qQ%zs;xVStjz[4~8?>\"m \"yR5 L+5)\\&(jZD6$<-<mb>^;j2<").map(n=>[a=a*95n+BigInt(n-32)]).map(n=>[(a>>=8n)%256n])))&&console.log('CHEAT ACTIVATED')

```

Try it online!

```
a=0n;                                   // Init
process.argv[2]                         // Take Input
.match(                                 // Check
  require(`zlib`).unzipSync(            // Uncompress
    Buffer("...")                       // For each char
    .map(n=>[a=a*95n+BigInt(n-32)])     // Add info to a
    .map(n=>[(a>>=8n)%256n])       // and take bytes out
  )                       // [] convert BigInt to Number
)&&console.log('CHEAT ACTIVATED')       //Output

```

First time using Node for full program

# Answer
> 1 votes
# C (Linux GCC)

## Count: 1584

```
void f(char*s){char c[][30]={"THUGSARMOURY","PROFESSIONALSKIT","NUTTERSTOYS","INEEDSOMEHELP","TURNUPTHEHEAT","TURNDOWNTHEHEAT","PLEASANTLYWARM","TOODAMNHOT","DULLDULLDAY","STAYINANDWATCHTV","CANTSEEWHEREIMGOING","TIMEJUSTFLIESBY","SPEEDITUP","SLOWITDOWN","ROUGHNEIGHBOURHOOD","STOPPICKINGONME","SURROUNDEDBYNUTTERS","TIMETOKICKASS","OLDSPEEDDEMON","DOUGHNUTHANDICAP","NOTFORPUBLICROADS","JUSTTRYANDSTOPME","WHERESTHEFUNERAL","CELEBRITYSTATUS","TRUEGRIME","ALLCARSGOBOOM","WHEELSONLYPLEASE","STICKLIKEGLUE","GOODBYECRUELWORLD","DONTTRYANDSTOPME","ALLDRIVERSARECRIMINALS","PINKISTHENEWCOOL","SOLONGASITSBLACK","FLYINGFISH","WHOATEALLTHEPIES","BUFFMEUP","LEANANDMEAN","BLUESUEDESHOES","ATTACKOFTHEVILLAGEPEOPLE","LIFESABEACH","ONLYHOMIESALLOWED","BETTERSTAYINDOORS","NINJATOWN","LOVECONQUERSALL","EVERYONEISPOOR","EVERYONEISRICH","CHITTYCHITTYBANGBANG","CJPHONEHOME","JUMPJET","IWANTTOHOVER","TOUCHMYCARYOUDIE","SPEEDFREAK","BUBBLECARS","NIGHTPROWLER","DONTBRINGONTHENIGHT","SCOTTISHSUMMER","SANDINMYEARS","KANGAROO","NOONECANHURTME","MANFROMATLANTIS","LETSGOBASEJUMPING","ROCKETMAN","IDOASIPLEASE","BRINGITON","STINGLIKEABEE","IAMNEVERHUNGRY","STATEOFEMERGENCY","CRAZYTOWN","TAKEACHILLPILL","FULLCLIP","IWANNADRIVEBY","GHOSTTOWN","HICKSVILLE","WANNABEINMYGANG","NOONECANSTOPUS","ROCKETMAYHEM","WORSHIPME","HELLOLADIES","ICANGOALLNIGHT","PROFESSIONALKILLER","NATURALTALENT","OHDUDE","FOURWHEELFUN","HITTHEROADJACK","ITSALLBULL","FLYINGTOSTUNT","MONSTERMASH"};for(int i=0,j=0,k=0;i<87;i++){j=strlen(c[i]);k=strlen(s);if(k<j||strncmp(s+(k-j),c[i],j))continue;printf("CHEAT ACTIVATED\n");}}

```

## Count w/out cheats themselves: 143

```
void f(char*s){for(int i=0,j=0,k=0;i<87;i++){j=strlen(c[i]);k=strlen(s);if(k<j||strncmp(s+(k-j),c[i],j))continue;printf("CHEAT ACTIVATED\n");}}

```

So if I wanted to improve mine, I'd need to find a better way to represent that data

# Answer
> 1 votes
# Japt, 823 bytes

```
`Ö„t aå¡ê*`pUè`(kÂžo|â‘(adjack|(g—¡|cŸzy|nˆja)Èu|fÒàg(‘Ð|t|f‰h)|Ü…hnÔAÌap|Ü‹(ç°GÊght|â2Øop´)|ÂlckÆøevÅNgepeop¤|¦fƒa¼a®|i(°n(nÃqveby|t‘—v€)|amšv€Ë¡ry|ÖÁoa¥night|tÑ¡ÞÑ|ã””lp)|æˆrQtÓƒ‰|n(å
…ys|otfŽèFŠÞads|ÇÊ¯n(Ë†´|¡op«)|Âxà¤¤|ightpžw¤r)|ÊµsvÅH|àP‰(Îr|poŽ)|è	wal(kÅHr|skŠ)|s(Ö-‰hsum´r|å€dbynÔjrs|áÊ‰kts½ack|pe‚(fœak|Ä¿)|t(…ee´rgcy|Ãà„d°t®tv|Åikeglue|Äikea¼e|áâ¶¨g´)|ÓqtÜµ|ÂnÛŒrs)|Î…hšighÞ€—od|goodbyecruelwŽld|b(ub½eÖÜ|Áªã §€ÇÔ|ãˆ
E|luàÂoƒ|uff´up)|jÔÍã€…p´|fŒrØ‡Óô|c(jpÊÊÊà|Ê•yÖ’tyßAßA|e¤ßŠyÐa«|„t eØ€e‹goˆg)|è0b$ew¬ol|t(ruegÎX|‹e(j«tf¦ƒby|‘kick†s)|oo»mn—t|aê‚ZUpi¥|Ë¯‡Ú€y|Æ2myÖÝŒ¹e|¨n(Üµ|up)eÊ!)|ž×Fµ(n|y”m)|Ò „dÚ |§Êãà!»d|fªlc¦p|è "Ã§°rm|ÚŽ’rÚR|jumpjet|oldspe‚¸¶n|w(Æ¢ip´|„na¼ˆmyg„g|—ÂT¥epiƒ|â€ fÕal)|love¬nquÀ&¥|ohdu¸|Ê)oÓ©ƒ|(iº†i|Ø‡ls§)pÒ"e|a¥(ÖÜgoÞ¼|dãŽ€›e×Ëˆals)|ç9é»y|¤tsgoßPjuÛpg)$`u¹u

```

Try it online!

## Explanation

```
`...`pUè`...`u¹u
`...`          u  // Compressed version of "CHEAT ACTIVATED"
     p            // Repeat the string
      Uè          // Number of matches of the regex on the input
        `...`u    // Compressed version of regex from the python solution

```

The regex is from this python solution

# Answer
> 0 votes
# JavaScript, no compression, ~~1356~~ 1351 bytes

`a=T=>~"THUGSARMOURY,PROFESSIONALSKIT,NUTTERSTOYS,INEEDSOMEHELP,TURNUPTHEHEAT,TURNDOWNTHEHEAT,PLEASANTLYWARM,TOODAMNHOT,DULLDULLDAY,STAYINANDWATCHTV,CANTSEEWHEREIMGOING,TIMEJUSTFLIESBY,SPEEDITUP,SLOWITDOWN,ROUGHNEIGHBOURHOOD,STOPPICKINGONME,SURROUNDEDBYNUTTERS,TIMETOKICKASS,OLDSPEEDDEMON,DOUGHNUTHANDICAP,NOTFORPUBLICROADS,JUSTTRYANDSTOPME,WHERESTHEFUNERAL,CELEBRITYSTATUS,TRUEGRIME,ALLCARSGOBOOM,WHEELSONLYPLEASE,STICKLIKEGLUE,GOODBYECRUELWORLD,DONTTRYANDSTOPME,ALLDRIVERSARECRIMINALS,PINKISTHENEWCOOL,SOLONGASITSBLACK,FLYINGFISH,WHOATEALLTHEPIES,BUFFMEUP,LEANANDMEAN,BLUESUEDESHOES,ATTACKOFTHEVILLAGEPEOPLE,LIFESABEACH,ONLYHOMIESALLOWED,BETTERSTAYINDOORS,NINJATOWN,LOVECONQUERSALL,EVERYONEISPOOR,EVERYONEISRICH,CHITTYCHITTYBANGBANG,CJPHONEHOME,JUMPJET,IWANTTOHOVER,TOUCHMYCARYOUDIE,SPEEDFREAK,BUBBLECARS,NIGHTPROWLER,DONTBRINGONTHENIGHT,SCOTTISHSUMMER,SANDINMYEARS,KANGAROO,NOONECANHURTME,MANFROMATLANTIS,LETSGOBASEJUMPING,ROCKETMAN,IDOASIPLEASE,BRINGITON,STINGLIKEABEE,IAMNEVERHUNGRY,STATEOFEMERGENCY,CRAZYTOWN,TAKEACHILLPILL,FULLCLIP,IWANNADRIVEBY,GHOSTTOWN,HICKSVILLE,WANNABEINMYGANG,NOONECANSTOPUS,ROCKETMAYHEM,WORSHIPME,HELLOLADIES,ICANGOALLNIGHT,PROFESSIONALKILLER,NATURALTALENT,OHDUDE,FOURWHEELFUN,HITTHEROADJACK,ITSALLBULL,FLYINGTOSTUNT,MONSTERMASH".split`,`.findIndex(E=>0<=T.indexOf(E)&T.indexOf(E)>=T.length-E.length)?"CHEAT ACTIVATED":""`

Attempted using `min<var<max` in the array callback, but that resulted fale positives.

Pretty straightforward otherwise; I preferred not to use compression; can't be shorter that way.

---

5 bytes spared by @KevinCruijssen and my reading to JS golfing.

# Answer
> 0 votes
# Erlang (escript), 1322 bytes

```
a(X)->lists:any(fun(I)->lists:suffix(I,X)end,string:split("THUGSARMOURY
PROFESSIONALSKIT
NUTTERSTOYS
INEEDSOMEHELP
TURNUPTHEHEAT
TURNDOWNTHEHEAT
PLEASANTLYWARM
TOODAMNHOT
DULLDULLDAY
STAYINANDWATCHTV
CANTSEEWHEREIMGOING
TIMEJUSTFLIESBY
SPEEDITUP
SLOWITDOWN
ROUGHNEIGHBOURHOOD
STOPPICKINGONME
SURROUNDEDBYNUTTERS
TIMETOKICKASS
OLDSPEEDDEMON
DOUGHNUTHANDICAP
NOTFORPUBLICROADS
JUSTTRYANDSTOPME
WHERESTHEFUNERAL
CELEBRITYSTATUS
TRUEGRIME
ALLCARSGOBOOM
WHEELSONLYPLEASE
STICKLIKEGLUE
GOODBYECRUELWORLD
DONTTRYANDSTOPME
ALLDRIVERSARECRIMINALS
PINKISTHENEWCOOL
SOLONGASITSBLACK
FLYINGFISH
WHOATEALLTHEPIES
BUFFMEUP
LEANANDMEAN
BLUESUEDESHOES
ATTACKOFTHEVILLAGEPEOPLE
LIFESABEACH
ONLYHOMIESALLOWED
BETTERSTAYINDOORS
NINJATOWN
LOVECONQUERSALL
EVERYONEISPOOR
EVERYONEISRICH
CHITTYCHITTYBANGBANG
CJPHONEHOME
JUMPJET
IWANTTOHOVER
TOUCHMYCARYOUDIE
SPEEDFREAK
BUBBLECARS
NIGHTPROWLER
DONTBRINGONTHENIGHT
SCOTTISHSUMMER
SANDINMYEARS
KANGAROO
NOONECANHURTME
MANFROMATLANTIS
LETSGOBASEJUMPING
ROCKETMAN
IDOASIPLEASE
BRINGITON
STINGLIKEABEE
IAMNEVERHUNGRY
STATEOFEMERGENCY
CRAZYTOWN
TAKEACHILLPILL
FULLCLIP
IWANNADRIVEBY
GHOSTTOWN
HICKSVILLE
WANNABEINMYGANG
NOONECANSTOPUS
ROCKETMAYHEM
WORSHIPME
HELLOLADIES
ICANGOALLNIGHT
PROFESSIONALKILLER
NATURALTALENT
OHDUDE
FOURWHEELFUN
HITTHEROADJACK
ITSALLBULL
FLYINGTOSTUNT
MONSTERMASH","
",all)).

```

Try it online!

---
Tags: code-golf, string, decision-problem, compression
---