# Question
Title: Multi-user CRUD: Valid, Problem, or Error?
## Introduction:

Ever used Dropbox with some other people and you both modified the same file? Ever had a multi-user application with a relational database, and two people were modifying (or worse, one was deleting and the other modifying) the same object? Well, let's simulate that with this challenge (sort-of).

For the sake of this challenge, we only have two users and either one or two relevant files. Both users have in general privileges to CRUD (Create, Read, Update, and Delete) all files.

## Challenge:

### Input:

We'll have a few inputs (input format is flexible, and any reasonable format is allowed):

1) ***Locking mode (on/off)***: Kinda the difference between optimistic and pessimistic concurrency locking.
Both users are allowed to CRUD (Create, Read, Update, and Delete) everything, but sometimes errors or problems can occur. Depending on the locking mode a problem when turned off, could be an error when turned on. This is explained below in the ***Output*** section.

2 & 3) ***Two user-actions***. These actions always consist of two things: What the user does (Create, Read, Update, or Delete) and for which file.

### Output:

We'll have three possible outputs:

1. ***Valid***: Both actions by both users can be done simultaneously without any issues occurring.
2. ***Error***: Both actions by both users cannot be done simultaneously and causes an error for one of the users (which user is irrelevant for this challenge). This can occur when:
    * one user Reads or Updates a file, which the other user Deletes;
    * both users Update the same file with locking mode turned on;
    * a user Creates a file, which the other user Reads/Updates/Deletes (this means the file already exists, so it cannot be Created);
    * both users Create the same file.
3. ***Problem***: Both actions by both users can be done simultaneously, but can cause unexpected problems. This can occur when:
    * both users Update a file when locking mode is turned off;
    * one user Updates a file, which the other user Reads;
    * both users Delete the same file (practically this will causes an error for the second user, but since it will still be deleted like the user wants, it will be a problem instead of an error for the sake of this challenge)

## Challenge Rules:

* All input and output is flexible, **and everyone should state which one they've used in their answer!**
Example inputs: `0`/`1` for locking mode & `31` (third action: Update; file: 1) & `21` (second action: Read; file: 1); `true`/`false` for locking mode & `['C','A']` (action: Create; file: A) & `['D','B']` (action: Delete; file: B); etc.
Example outputs: `null`/`true`/`false` (null = valid; true = error; false = problem); `-1`/`0`/`1` (-1 = error; 0 = problem; 1 = valid); etc. The three possible outputs have to be **unique and distinct** for the three output-type, though.
* What the files are called is irrelevant, which can also be seen with the input-examples above. So feel free to use any type of file name in your answers consisting of a single (ASCII) letter or digit. They do have to be consistent across all your test cases however, so you can't use `A`/`B` in one test case and `1`/`2` in another.
* The four actions for CRUD have to be unique and consistent values as well. So you cannot use `'D'`/`'C'` in one test case, and then `4`/`1` in another test case.
* You can assume that the file chosen by a user always exists when they want to Read, Update, or Delete it.

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (i.e. TIO).
* Also, adding an explanation for your answer is highly recommended.

## All possible test cases (where the actions can be in either input-order):

*: You should support all (up to four) variations of the test cases below. So if a test case states `action1: Create file A; action2: Update file B`, that test case should also hold the same results for `action1: Create file B; action2: Update file A`; `action1: Update file B; action2: Create file A`; and `action1: Update file A; action2: Create file B`.*

```
Valid use-cases:

locking mode: either;  action1: Create file A;  action2: Create file B
locking mode: either;  action1: Create file A;  action2: Read file B
locking mode: either;  action1: Create file A;  action2: Update file B
locking mode: either;  action1: Create file A;  action2: Delete file B
locking mode: either;  action1: Read file A;    action2: Read file A
locking mode: either;  action1: Read file A;    action2: Read file B
locking mode: either;  action1: Read file A;    action2: Update file B
locking mode: either;  action1: Read file A;    action2: Delete file B
locking mode: either;  action1: Update file A;  action2: Update file B
locking mode: either;  action1: Update file A;  action2: Delete file B
locking mode: either;  action1: Delete file A;  action2: Delete file B

Error use-cases:

locking mode: either;  action1: Create file A;  action2: Create file A
locking mode: either;  action1: Create file A;  action2: Read file A
locking mode: either;  action1: Create file A;  action2: Update file A
locking mode: either;  action1: Create file A;  action2: Delete file A
locking mode: either;  action1: Read file A;    action2: Delete file A
locking mode: on;      action1: Update file A;  action2: Update file A
locking mode: either;  action1: Update file A;  action2: Delete file A

Problem use-cases:

locking mode: either;  action1: Read file A;    action2: Update file A
locking mode: off;     action1: Update file A;  action2: Update file A
locking mode: either;  action1: Delete file A;  action2: Delete file A

```

# Answer
> 8 votes
# JavaScript (ES6), 36 bytes

### Without a lookup table

```
(m,a,f,A,F)=>f-F?2:a^A?a*A&8:a&4?m:a

```

Try it online!

### I/O

* Locking mode (\\$m\\$): \\$0\\$ = On, \\$8\\$ = Off
* Actions (\\$a\\$ and \\$A\\$): \\$0\\$ = Create, \\$2\\$ = Read, \\$4\\$ = Update, \\$8\\$ = Delete
* Files (\\$f\\$ and \\$F\\$): any integers
* Output: \\$0\\$ = Error, \\$2\\$ = Valid, \\$8\\$ = Problem

### How?

If the files are different, all operations are safe and we just return \\$2\\$ (valid).

If the files are identical, we need to return:

* \\$2\\$ (valid) if we have two *read* operations
* \\$8\\$ (problem) if we have two *delete* operations, or one *update* and one *read*
* \\$m\\$ (either problem or error) if we have two *update* operations
* \\$0\\$ (error) for everything else

Using a \\$4\times4\\$ CRUD matrix (which is symmetric by definition), we can see that the above values can be computed with:

$$\underbrace{\text{a ^ A}}\_{a\neq A?}\text{ ? }\color{blue}{\text{a * A & 8}}\text{ : }\underbrace{\text{a & 4}}\_{\text{update?}}\text{ ? }\color{red}{\text{m}} : \color{magenta}{\text{a}}$$

$$\begin{array}{cc|cccc} &&\text{C}&\text{R}&\text{U}&\text{D}\\ &&0&2&4&8\\ \hline \text{C}&0&\color{magenta}{0}&\color{blue}{0}&\color{blue}{0}&\color{blue}{0}\\ \text{R}&2&\color{blue}{0}&\color{magenta}{2}&\color{blue}{8}&\color{blue}{0}\\ \text{U}&4&\color{blue}{0}&\color{blue}{8}&\color{red}{\text{m}}&\color{blue}{0}\\ \text{D}&8&\color{blue}{0}&\color{blue}{0}&\color{blue}{0}&\color{magenta}{8} \end{array}$$

---

# JavaScript (ES6),  ~~46 45~~  40 bytes

### With a lookup table

```
(m,a,f,A,F)=>f-F?0:[m,1,1,0][a*2+A*9&23]

```

Try it online!

### I/O

* Locking mode: *undefined* = On, \\$1\\$ = Off
* Actions: \\$0\\$ = Update, \\$1\\$ = Read, \\$2\\$ = Create, \\$3\\$ = Delete
* Files: any integers
* Output: *undefined* = Error, \\$0\\$ = Valid, \\$1\\$ = Problem

# Answer
> 4 votes
# Retina 0.8.2, 53 bytes

```
^(.)(?!\1).+|..RR.
V
..DD.
P
..UUL
E
.+[CD].+
E
..+
P

```

Try it online! Link includes test suite. Takes input as a string of 5 characters, two characters representing the file names, then two characters from `CRUD`, then `L` or `U` (locked/unlocked), and outputs one of `VPE` (valid/problem/error). Explanation:

```
^(.)(?!\1).+|..RR.
V

```

Different file names are always valid, as are two reads. Annoyingly, this is the only test that forces me to use a header. (It would cost an extra byte to make the header unnecessary.)

```
..DD.
P

```

Two deletes are always a problem.

```
..UUL
E

```

Two locked updates are an error.

```
.+[CD].+
E

```

Any other creates or deletes are an error.

```
..+
P

```

Everything else is a problem.

# Answer
> 3 votes
# Octave, 96 bytes

```
@(a,b,c)[a(1)!=b(1)|a(2)+b(2)==20,mod((m=a+b+c)(2),10010)<1|mod(m(2),1020000)<1|mod(m(2),200)<1]

```

Try it online!

Definitely can be shorter, but I don't have time right now to do that

```
File 1 = 0
File 2 = 1
Read = 10
Delete = 100
Create = 1000
Update = 10000
Lock on = 100000
Lock off = 1000000

Valid Values:
[1 0]

Problem Values:
[0 1]

Invalid Values:
[0 0]

```

Input as a = \[file, action\], b = \[file2, action2\], c = lock

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


title: Darts meets Codegolf

text:
# Question
Title: Darts meets Codegolf
I think everyone is familiar with the game of darts. For those that don't understand the scores, here is a useful link.

### The board

A dartboard can be compared to a pie cut in 20 pieces.
Each piece is divided in 4 sections.

* a small outer ring called "double" (points x2)
* a big ring called "single" (points x1)
* another small ring called "triple" (points x3)
* another big ring called "single" (points x1)

In the middle of the board are 2 more rings, a green one and red one (classic board)

* Red ring, at the center of the board, is called "bullseye" or "double bull" and is good for 50 points. This one counts as a double and because of that it's allowed to checkout with it.
* Green ring is called "bull", "single bull", or simply "25" and counts as a single.

### Challenge

Find all checkout possibilities with 3 darts or less.
The user can enter an integer and you will have to check if it's possible to get the score to 0 with 3 darts (or fewer).

### Examples

example 1:

```
Input: 170
Output: T20, T20, Bullseye

```

Example 2:

```
Input: 6
Output: D3;
        S3,S1,D1;
        S2,D2;
        S2,S2,D1;
        D2,D1;
        S4,D1;
        D1,D1,D1;
        S1,S1,D2;
        T1,S1,D1;

```

Example 3:

```
Input: 169
Output: No possible checkout!

```

### Rules

* Basic dart rules, you must end with a double (outer ring of the board or bullseye)
* No use of external resources.
* Hard coding of possible checkouts is allowed, but remember, this is codegolf, it won't get your code short ;)
* Cells to hit will be displayed in format C+N where C = T for Triple, D for double and S for single.
* bullseye can be called bullseye or DB, DBull or something similar.

### Possible checkouts

To get you started, the highest possible checkout is 170.
169, 168, 166, 165, 163, 162, and 159 are not possible in 3 darts.
The lowest possible checkout is 2.

### In addition

This isn't a requirement: add in a possibility to show all possible checkouts for all scores. Basically because I wonder how many combinations are possible :P

Winner will be the one with the shortest code.

Happy coding.

# Answer
> 3 votes
# C++  ~~248 / 228~~  230 / 214 chars

Rev 0:

```
int f(int s){char m[4]="SDT";int t=0;for(int b=2;b<77;b+=1+(b==62)*12)for(int a=2;a<77;a+=1+(a==62)*12){int c=s-a/3*(a%3+1)-b/3*(b%3+1);if(((c+38)/40==1)|(c==50)&&(c%2==0)&(a>=b)){printf("%c%d %c%d D%d\n",m[a%3],a/3,m[b%3],b/3,c/2);t++;}}return t;}

```

Rev 1. Saved some characters by declaring all variables at once, and by eliminating unnecessary brackets. It turns out that in C++ all logic and bitwise and/or are lower precedence than comparisions.

```
int f(int s){char m[4]="SDT";int a,b,c,t=0;for(b=2;b<77;b+=1+(b==62)*12)for(a=2;a<77;a+=1+(a==62)*12){c=s-a/3*(a%3+1)-b/3*(b%3+1);if(c>1&c<41|c==50&&c%2==0&a>=b){printf("%c%d %c%d D%d\n",m[a%3],a/3,m[b%3],b/3,c/2);t++;}}return t;}

```

I did a function rather than program, as others have done. It returns the total number of possibilities found. It can be reduced from 230 to 214 characters by eliminating the totalising feature.

Sample output, score 6:

I count different first and second darts as the same combination, as the OP has done (example:

T1 S1 D1 = S1 T1 D1) even though this costs an extra 7 characters. I always list the higher score first (ignoring doubling and trebling) as I figure this is more relevant to the player (who may change his strategy if he misses with the first dart.) For the same reason I list the darts in order according to the second dart. I consider the 3rd dart to be completely different to the other two, therefore I consider D1 D2 and D2 D1 to be different cases whereas the OP has them listed as the same.

**With this system of counting I get 42336 total possibilities**, the same as mmumboss. Counting different first and second darts as different combinations, this goes up to 83349.

I haven't used a for loop with sets as others have done (I'm fairly new to C++ and I don't even know if it's possible.) Instead I abuse a conditional in the loop increment to jump from 20 up to 25. I use the variable from a single loop to encode all possible scores for a single dart, like this: S1 D1 T1 S2 D2 T2 etc. with modulus and division to decode. This saves on the verbosity of declaring more for loops, although it makes expressions more complicated.

The result of this is that an unused dart is shown as T0, but I think it's clear what is meant, especially as (by considering different first and second darts as the same combination) I have been able to group them all together at the beginning of my output.

Ungolfed version here. A couple of other features are use of the & and && operators selectively with | in such a way as to give the order of precedence I want without brackets.

```
int f(int s)
{
  char m[4] = "SDT";
  int a,b,c,t=0;
    for (b = 2; b < 77; b += 1 + (b == 62) * 12)
      for (a = 2; a < 77; a += 1 + (a == 62) * 12){
        c = s - a / 3 * (a % 3 + 1) - b / 3 * (b % 3 + 1);
        if (c>1 & c<41 | c == 50 && c % 2 == 0 & a >= b){
          printf("%c%d %c%d D%d\n", m[a % 3], a / 3, m[b % 3], b / 3, c / 2);
          t++;
        }
     }
   return t;
}

```

# Answer
> 5 votes
## MATLAB (~~299~~ ~~249~~ 241 chars)

This is my first serious golfing. My first attempt (136 chars) gives the correct result, but not with the correct formatting. It gives all possibilities looking at the number of points for each dart. This means that single 20 and double 10 do have a separate entry, however, they are both displayed as 20. Of course the last dart is always a double.

```
function f(x);u=[1:20 25].';y=[u;2*u; 3*u(1:end-1)];v=combvec([combnk(y,2);[y y];[zeros(62,1) y];[0 0]].',y(22:42).').';v(sum(v,2)==x,:)

```

In the second attempt the formatting is improved, which has of course increased the number of characters:

```
function f(x);h=.1;u=h+[1:20,25].';y=[u;2*u;3*u(1:20)];v=combvec([combnk(y,2);[y,y];h*ones(62,1),y];[h,h]].',y(22:42).').';t='SDT';r=@fix;strrep(arrayfun(@(x)[t(int8((x-r(x))/h)),num2str(h*r(x)/(x-r(x)))],v(sum(r(v),2)==x,:),'un',0),'S0','')

```

Improved from 299 to 249 characters, while at the same time even improving the output formatting. For this improved version the output for the example cases is:

f(170):

```
'T20'    'T20'    'D25'

```

f(6):

```
'S1'    'S3'    'D1'
'S1'    'T1'    'D1'
'S2'    'D1'    'D1'
'S2'    'S2'    'D1'
'D1'    'D1'    'D1'
''      'S4'    'D1'
''      'D2'    'D1'
'S1'    'S1'    'D2'
''      'S2'    'D2'
''      'D1'    'D2'
''      ''      'D3'

```

f(169):

```
Empty cell array: 0-by-3

```

### Additional:

According to my calculation skills there are a grand total of 42336 possibilities to end the dart game.

# Answer
> 3 votes
# Ruby (260 chars)

"The last one should be a double" was the missing piece - couldn't figure out why 168 should not have results...:

```
c=->n,d=3{d=d-1;r=[];n==0?[r]:(d>=0&&n>0?(o='0SDT';((1..20).map{|p|(1..3).map{|h|c.(n-p*h,d).map{|m|r<<["#{o[h]}#{p}"]+m}}};c.(n-50,d).map{|m|r<<['DB']+m};c.(n-25,d).map{|m|r<<[?B]+m})):1;r.select{|*i,j|j[?D]}.tap{|x|d!=2?1:puts(x.map{|i|"#{i.join(?,)};"})})}

```

c.(170)

```
T20,T20,DB;

```

c.(6)

```
S1,S1,D2;
S1,T1,D1;
S1,S3,D1;
D1,D1,D1;
D1,S2,D1;
D1,D2;
T1,S1,D1;
S2,D1,D1;
S2,S2,D1;
S2,D2;
D2,D1;
S3,S1,D1;
D3;
S4,D1;

```

# Answer
> 2 votes
# Python 2.7 (270 chars)

Not sure python will allow a one-liner, but he it is in three.

```
def f(n):
 a={'%s%s'%('0SDT'[i],n):n*i for n in range(1,21)+[25] for i in [1,2,3] if n*i<75};a['']=0
 for r in [' '.join(h[:3]) for h in [(x,y,z,a[x]+a[y]+a[z]) for x in a for y in a for z in {k:a[k] for k in a if 'D' in k}] if h[3]==n and len(h[0])<=len(h[1])]:print r

```

Or 278+ chars with a proper 'No Checkout' message (e.g. 290 here):

```
def f(n):
 a={'%s%s'%('0SDT'[i],n):n*i for n in range(1,21)+[25] for i in [1,2,3] if n*i<75};a['']=0;
 for r in [' '.join(h[:3]) for h in [(x,y,z,a[x]+a[y]+a[z]) for x in a for y in a for z in {k:a[k] for k in a if 'D' in k}] if h[3]==n and len(h[0])<=len(h[1])] or ['No Checkout']:print r

```

Here we go:

f(170)

```
T20 T20 D25

```

f(6)

```
S3 S1 D1
S2 S2 D1
S2 D1 D1
S1 S3 D1
S1 S1 D2
S1 T1 D1
 S2 D2
 S4 D1
  D3
 D2 D1
 D1 D2
T1 S1 D1
D1 S2 D1
D1 D1 D1

```

f(169)

```
No Checkout

```

Things I'm not happy with:

```
for x in a for y in a for z in

```

This is over 10% of the total. Is there a more compact way without itertools etc?

```
and len(h[0])<=len(h[1])

```

This is used to prevent duplicates in the case of a two dart finish (e.g. \['', 'S1', 'D1'\] and \['S1', '', 'D1'\]). I deem order to matter (hey - the last dart has to be a double, so clearly order matters), but the non-throw is a special case.

# Answer
> 2 votes
# 05AB1E, 43 bytes

```
20L25ª3Lâ¨Ðʒθ<}Uã«XâXìε˜2ô}ʒPOQ}εε`…TSDsèì

```

Pretty slow.. Outputs as a list of lists, or an empty list if no finish is possible. My bulls are `S25` and `D25`; if this is not allowed I can change it.

Try it online or verify a few test cases at once.

**Explanation:**

There are a couple of steps:

1) Create a list of all possible single, double, and triple darts:

```
20L         # Create a list in the range [1,20]
   25ª      # Append 25 to this list
      3L    # Create a list in the range [1,3]
        â   # Create all possible pairs of these two lists
         ¨  # Remove the last pair (which is the Triple Bull)
            # Now we have a list of all possible darts:
            #  [[1,1],[1,2],[1,3],[2,1],...,[20,3],[25,1],[25,2]]

```

2) Get all possible finishers (ending with a double) of up to 3 darts:

```
Ð           # Triplicate this list
 ʒ  }       # Filter the top copy by:
  θ         #  Where the last value
   <        #  Decremented by 1 is truthy (==1), so all doubles
     U      # Pop this filtered list of doubles, and store it in variable `X`
 ã          # Create all possible pairs of the list of darts with itself
  «         # Merge it with the list of darts
            # We now have a list containing all possible variations for 1 or 2 darts
 Xâ         # Then create all possible pairs of these with the doubles from variable `X`
   Xì       # And prepend the doubles themselves as well
            # Now we have all possible variations of 1 double; 1 dart + 1 double;
            # or 2 darts + 1 double
     ε   }  # Map each to:
      ˜     #  Deep-flatten the list
       2ô   #  And split it into parts of size 2
            #  (this is to convert for example a 2 darts + 1 double from
            #   [[[20,3],[5,1]],[1,2]] to [[20,3],[5,1],[1,2]])
            # Now we have a list of all possible finishers of up to 3 darts

```

3) Only keep those for which the total score is equal to the input-integer:

```
ʒ   }       # Filter this list by:
 P          #  Get the product of each inner-most lists
            #   i.e. [[20,3],[5,1],[1,2]] → [60,5,2]
  O         #  Take the sum of those
            #   i.e. [60,5,2] → 67
   Q        #  Check if this value is equal to the (implicit) input-integer
            # Now we only have the finishers left with a total value equal to the input

```

4) Convert the data to the pretty-printed result-list (i.e `[[20,3],[5,1],[1,2]]` becomes `["T20","S5","D2"]`):

```
ε           # Map each of the remaining finishers of up to 3 darts to:
 ε          #  Map each inner list to:
  `         #   Push both values separately to the stack ([20,3] → 20 and 3)
   …TSD     #   Push string "TSD"
       s    #   Swap to get the integer for single/double/triple at the top of the stack
        è   #   Use it to index into the string
            #   NOTE: 05AB1E has 0-based indexing with automatic wraparound,
            #   so the triple 3 will wrap around to index 0 for character "T"
         ì  #   Prepend this character in front of the dart-value
            # (after which the result is output implicitly as result)

```

# Answer
> 1 votes
# Kotlin, 254 bytes

Note: algorythm is based on Level River St's C++ answer.

```
{s:Int->val m="SDT"
var c=0
val r=(2..62).toList()+listOf(75,76)
for(t in r)for(o in r){val l=s-o/3*(o%3+1)-t/3*(t%3+1)
if((l>1&&l<41||l==50)&&l%2==0&&o>=t){println("${m[o%3]}${o/3},${m[t%3]}${t/3},D${l/2}")
c++}}
if(c<1)println("No possible checkout!")}

```

Try it online!

---
Tags: code-golf, math, game, integer-partitions
---


# Question
Title: Print the previous answer in reverse - with a catch
Your challenge is very simple: output the previous answer, in reverse.

However, as with this similarly-titled question, there's a catch: in this case, you can only use characters from the answer *before* the last. For example:

Let's say the first answer looks like this:

> 1 - Python
>
> `print('hi!')`

And the second answer looks like this: (see 'Chaining' section for more info)

> 2 - Javascript
>
> `console.log(")'!ih'(tnirp")`

Now, it would be my job to write the third answer: a program to output the text `)"print('hi!')"(gol.elosnoc`, while only using the characters `p`, `r`, `i`, `n`, `t`, `(`, `'`, `h`, `i`, `!` and `)`. I can choose whatever language I like to complete this task.

# Chaining

The first answer can output any text: but it *must* **output** *something*. The second answer should simply output the first answer in reverse, using any characters you like. The further rules about restricted characters, as described above, come into play from the third answer onwards.

# Scoring

Your score is \\$\frac{l\_{n}}{l\_{n-1}} + l\_{n-2}\\$, where \\$l\_x\\$ represents the length of the \\$x\\$th answer, and \\$n\\$ is the position your answer is at in the chain. (all lengths are in bytes; if your answer is no. 1 or no. 2 then miss out \\$l\_{n-1}\\$ and/or \\$l\_{n-2}\\$ where necessary.

Best (lowest) score by August 1st wins.

# Formatting

Please format your post like this:

```
[Answer Number] - [language]

    [code]
    (preferably a TIO link)

SCORE: [Submission Score]

(notes, explanations, whatever you want)

```

*Everything in square brackets is a required argument to fill in; everything in normal brackets is an optional argument; everything not in brackets is there to make the snippet work.*

# Rules

* All characters, etc. are case sensitive.
* Preceeding/trailing whitespace is allowed, within reason (I'm looking at you, Whitespace).
* Every submission must be a unique language.
* You must wait at least 1 hour before submitting a new answer if you have just posted.
* You may **NOT** submit two answers in a row, you must wait for TWO more submissions before posting a new answer.
* Of course, standard loopholes are disallowed.
* Please make sure to triple check that your answer is valid. ~This is especially important, because someone may start writing their answer based on yours, so if it's wrong you can't really edit it any more... and the whole chain breaks down.~ Also, you can't edit answers for continuity purposes.
* Standard I/O methods are allowed.

# Answer list/used languages

```
$.ajax({
  type: "GET",
  url: "https://api.stackexchange.com/2.2/questions/187667/answers?site=codegolf&filter=withbody&sort=creation&order=asc",
  success: function(data) {
    for (var i = 0; i < data.items.length; i++) {
      var temp = document.createElement('p');

      temp.innerHTML = data.items[i].body.split("\n")[0];

      try {
        temp.innerHTML += " - <i>Score: " +
          data.items[i].body
          .split("SCORE")[1]
          .split("\n")[0]
          .split(":")[1]
          .trim() +
          "</i>";
      } catch (TypeError) {
        temp.innerHTML += " (no score)";
      } finally {
        $('#list').append('<li><a href="/a/' + data.items[i].answer_id + '">' + temp.innerText || temp.textContent + '</a>');
      }
    }
  }
})
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<base href="https://codegolf.stackexchange.com">
<ul id="list"></ul>
```

# Answer
> 0 votes
# 2. 05AB1E

```
“a = "Hello"““b = "World"“I“c = a + ", " + b + "!"“I“…¢““(c)“«»R

```

Try it online!

---

```
64/57 + 0 = 1.12

```

### SCORE: 1.12

# Answer
> 2 votes
# 3 - Python 2

419/64+57 -\> **SCORE: 63.546875**
This is one masterpiece of hackery. ~~Edited to comply with rule 1.~~ chr uses lowercase h, not uppercase. Will edit when I have time to find a substitute.

Update 9/25/2020: Yeah I'm not coming back to this, question is closed anyway.
This is assuming the first answer is Python 3

```
e=ord
o=e("o")
a=e("a")
n=e("\n")
t=e(")")
b=e("(")
i=e("i")
W=e(" ")
p=o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+o+a+n+n
o=chr
H=o(W+t)
d=o(p+n)
p=o(p)
l=o(a+e(",")+n+n+n)
r=o(i+t+t)
c=o(b+b+b+n+W)
print(o(b+W+n)+r+l+p+")c("+p+p+c+d+p+H+p+""""!" + b + " ," + a = c"""+p+H+p+""""dlroW" = b"""+p+p+""""olleH" = a"""+p)

```

TIO

# Answer
> 0 votes
# 1 - Python

```
a = "Hello"
b = "World"

c = a + ", " + b + "!"

print(c)

```

Try it online!

**SCORE: 57**

First answer.

---
Tags: code-challenge, answer-chaining
---


title: Slow growing Quine

text:
# Question
Title: Slow growing Quine
Make a Quine.

Seems easy right? Well this quine must output itself plus its first character, which then outputs itself plus its second character, and so on.

**This way the quine should in several generations output two copies.**

Example: Lets your code be `x`. Running it should output `x + x[:1]`. Running the resulting program should output `x + x[:2]` and so on...

If your code was `foobar`, running this should output `foobarf`. Running this should output `foobarfo`. And so on and so forth following this pattern:

```
foobar
foobarf
foobarfo
foobarfoo
foobarfoob
foobarfooba
foobarfoobar
foobarfoobarf

```

Your Program must be longer than 2 Bytes and must output only ONE extra character of its own code each iteration.

# Answer
# Zsh, ~~110~~ ~~108~~ 100 bytes

```
a=`<&0`<<''<<<t;b=${a:0:50};printf $b$b${a:0:-50}
a=`<&0`<<''<<<t;b=${a:0:50};printf $b$b${a:0:-50}

```

Try it online!

So it is possible.

### Explanation

```
a=`<&0`<<''<<<t;       # Set A to everything following this line, until eof or
                       #   an empty line (which never happens before eof) encountered.
                       # A "t" is appended to prevent automatic trimming of newlines.
b=${a:0:50};           # Set B to the first line.
printf $b$b${a:0:-50}  # Print two copies of B and
                       #   A with 50 trailing characters removed.

```
> 15 votes

# Answer
# R, 289 bytes

```
s<-c("s<-", "i=get0('i',ifnotfound=0)+1;p=paste0(s,substr(get0('p',ifnotfound=s),1,i),collapse='');cat(s[1]);dput(s);cat(paste0(s[2],substr(p,1,i)))#")
i=get0('i',ifnotfound=0)+1;p=paste0(s,substr(get0('p',ifnotfound=s),1,i),collapse='');cat(s[1]);dput(s);cat(paste0(s[2],substr(p,1,i)))#

```

credit to this quine for inspiration. Only works if run in the *same* R environment as the previous quine is run.
> 11 votes

# Answer
## Alice, 29 bytes

```
4P.a+80pa2*&wdt,kd&w74*,.ok@

```

Try it online!

The unprintable character is 0x18.

### Explanation

The trouble with the usual `"`-based Fungeoid quines is that if we repeat the entire source code, then we also get additional `"` and the string no longer covers the entire source code. I assume that's why the existing answer uses the cheat-y `g` approach instead.

This answer does use the `"`-based approach, but instead of including a `"` in the source, we write it into the program at runtime. That way, there will only ever be one `"` regardless of how often the program is repeated (because we only write it to one specific coordinate, independently of program size).

The general idea is then that we create a representation of the whole source code on the stack, but only cycle through the first 29 of the characters (i.e. the program length) with the length of the loop determined by the size of the code. Therefore, we can actually append arbitrary characters (except linefeeds) after `@` and the result will always be a cyclic repetition of the core program, one character longer than the source.

```
4P   Push 4! = 24. This is the code point of the unprintable, which we're
     using as a placeholder for the quote.
.a+  Duplicate it and add 10, to get 34 = '"'.
80p  Write '"' to cell (8,0), i.e. where the first unprintable is.
    Placeholder, becomes " by the time we get here, and pushes the code
     points of the entire program to the stack. However, since we're already
     a good bit into the program, the order will be messed up: the bottom
     of the stack starts at the 24 (the unprintable) followed by all
     characters after it (including those from extraneous repetitions). Then
     on top we have the characters that come in front of the `"`.
     So if the initial program has structure AB, then any valid program has
     the form ABC (where C is a cyclic repetition of the initial program),
     and the stack ends up holding BCA. We don't care about C, except to
     determine how big the program is. So the first thing we need to do is
     bring B to the top, so that we've got the initial program on top of
     the stack:
a2*  Push 10*2 = 20.
&w   Run the following section 21 times, which is the length of B.

  dt,  Pull up the value at the bottom of the stack.

k    End of loop.
d&w  Run the following section D+1 times, where D is the length of ABC.

  74*  Push 28, one less than the number of characters in AB.
  ,    Pull up the 29th stack element, which is the next character to print.
  .o   Print a copy of that character.

k    End of loop.
@    Terminate the program.

```
> 6 votes

# Answer
# Perl 5, 83 bytes (including final newline)

```
$_=q($/=$;;$_="\$_=q($_);eval
__END__
".<DATA>;print$_,/(.).{82}\z/s);eval
__END__

```

Try it online!

The good ol' `__DATA__` token makes it easy to append an arbitrary string to any Perl program, which the main program can then access via the `<DATA>` file handle (and actually using `__END__`, which does the same thing for backwards compatibility, instead of `__DATA__` saves two extra bytes).

Note that this program does *not* read its own source code, but only the extra input data appended to its source after the `__END__` token. In effect, the `__END__` token and everything after it functions kind of like a string literal terminated by the end of the input.

Also note that, in order to meet the spec exactly, this program must end in a newline. If it does not, the newline actually gets automatically appended after the second `__END__` anyway, but then the first iteration output won't be precisely equal to the code plus its first byte any more.
> 4 votes

# Answer
# Befunge-98, 30 bytes

```
0>:#;0g:840#;+*#1-#,_$a3*%0g,@

```

Try it online!

My try using Befunge-98 which uses a space terminated quine which also counts how many characters have been outputed. **Does however use the `g` command.**
> 2 votes

# Answer
# PHP, 146 bytes

```
ob_start(function($s){return($u=substr($s,0,73)).$u.substr($s,0,-72);})?>ob_start(function($s){return($u=substr($s,0,73)).$u.substr($s,0,-72);})?>

```

It should be run using `-r` in command line.
> 2 votes

# Answer
# Runic Enchantments, 61 bytes

```
803X4+kw.'.q}͍}͍}͍}͍}͍}͍}͍}͍}͍::l͍5X-:}-$:l͍{-1--@

```

Try it online!

Uses a similar approach as the Alice answer: reflectively writes the string `"` command into the code so that there Is Only One. There rest is a lot of string and stack manipulation to recover the original program, how many extra bytes are needed, and print the necessary hunks.

The  sequence rotates the in-memory string representation around so that the `803X4+kw` appears at the beginning instead of at the end, due to the position of the `"` and there isn't an easier way of handling this operation without having to compute a lot of awkward numbers.

While the original program is 61 *bytes* its *string-length* is only 50, which is easy to construct as `5X` and it was only coincidence that this didn't need to be padded out after containing all necessary functionality (e.g. a length 49 program would be easier to encode as `50` with one byte of padding than to encode a literal `49`, while `51` would be encoded as `5X3+` or 53, having to account for its own extra bytes).
> 2 votes

---
Tags: code-golf, quine
---


title: Possibly quit your job with a polyglot

text:
# Question
Title: Possibly quit your job with a polyglot
Despite your protest, you have been put to work by your boss on a program that takes a single unsigned integer as input and prints the string "prime" if that integer is prime and "not prime" if it isn't. You may choose which language you do this in, as long as the resulting program is short; your boss very much appreciates a low character count. (He will actually *manually* count the characters after he prints out the source code.)

So you better get to it, the lowest character count wins.

## The fun part

This is just between you and me, but your program should also be valid in another language. In this language though, **it should print the string "If the boss finds this, I quit.".** Make sure that your boss does not figure out there is a hidden insult when reading the code over and over as he keeps forgetting if he'd counted to 17 or 18 so far. For that reason **you may not use any of the words in "the boss finds this quit" in part of the code nor can you use and anagrams of those 5 words.**

**Bonus challenge which I have created a bounty for**

Write a program that actually looks like it just solves the first question to the untrained eye and doesn't seem to contain unnecessary characters. This includes comments and segments of code that obviously don't contribute anything. Ideally, a layman would believe that your program is actually as short as it can be without being unmanagable. A helpful comment here and there is okay though.

The rules for the bonus challenge are a bit looser, instead of being judged on easily measurable criteria, your program will be judged more on how it comes accross to me (and the voters of course)

**I will be the final judge of which entry comes closest to deserving this bounty.**

**Edit:**

After a few minutes of your boss counting, he had one of your colleages write a character counting program for him. **So even characters that aren't visible count towards your character count.**

# Answer
# CJam (GolfScript), ~~60~~ 59 bytes

```
"Jg!uif!cptt!gjoet!uijt-!J!rvju/"{(}%S#];"not prime"limp4*>

```

*Thanks to @mnbvmar for golfing off 1 byte!*

### How it works (CJam)

```
"Jg!uif!cptt!gjoet!uijt-!J!rvju/"  " Push that string.                                    ";
{(}%                               " Subtract 1 from each character code.                 ";
S#                                 " Find the index of the first space.                   ";
];                                 " Wrap the entire stack in an array and discard it.    ";
"not prime"                        " Push that string.                                    ";
li                                 " Read an integer from STDIN.                          ";
mp4*                               " Push 4 if it's prime and 0 if it isn't.              ";
>                                  " Remove that many chars from the start of the string. ";

```

Try it online!

### How it works (GolfScript)

```
"Jg!uif!cptt!gjoet!uijt-!J!rvju/"  # Push that string.
{(}%                               # Subtract 1 from each character code.
S#];"not prime"limp4*>             # Noop followed by a comment.

```

Try it online!
> 37 votes

# Answer
# Python 2 / Python 3 - 128

```
n=int(input())
s="Isf  tthhies ,b oIs sq ufiitn.d"
print(["not "*any([n%a<1for a in range(2,n)])+"prime",s[::2]+s[1::2]][1/2>0])

```

Identifies prime numbers with Python 2, get's you into trouble with Python 3.

---

## Bonus

```
__help__ = """In the forloop I'm setting the values i to n.
To be a "notPrimes", it's n % i == 0 if: 1 < i, i < n. (We
do tests i<1/2 i==1, too). Then, prints resulting, prime text.
In case i==n: quit. Just if it aborts: try."""

# read integer from command line
n=int(input())

try:

    # primes = True
    notPrimes = False

    # try each i to n
    for i in range(n):

        # ignore 0 or 1
        if i < 1 / 2 or i == 1:
            continue

        # test divisibility
        if n % i == 0:
            notPrimes = True

    # print result
    if notPrimes:
        print("not prime")
    else:
        print("prime")

except:

    # if program aborts: print help and error code
    print(__help__ [::7])

```

Try it with Python 2 or Python 3! (In contrast to the golf version above the roles changed: Python 3 is the prime number identifier. Python 2 contains the Easter egg.)

Please, excuse my bad English in the help text! ;)

And I do use the word "quit". But somehow I need to describe when my program terminates. ;)
> 80 votes

# Answer
# Bonus submission (C / C++11)

Primality testing using the usual naive method is so mainstream. That's why I have invented a brand-new randomized naive method! This test is as follows:

1. Choose any integer **d** at random. It must not be smaller than 2 and larger than a bit more than `sqrt(n)`.
2. If **d** is a divisor of **n**, output `not prime`.
3. If we made this test `20sqrt(n)` times, output `prime`, else repeat.

If the number is composite, there is only very little probability (about 10<sup>-9</sup>) that it doesn't work. Of course, I don't believe the C/C++ pseudorandom number generator is powerful enough. That's why I use my own 256-bit LFSR generator!

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

/* A 256-bit linear feedback shift register generating pseudorandom
 * numbers (its period is 2^256 - 1).
 */
struct LFSRGenerator {
    unsigned seed[8];
};

void lfsr_init_generator(struct LFSRGenerator *gen){
    gen->seed[0] = 0xE840CC92; gen->seed[1] = 0xC440CAD0;
    gen->seed[2] = 0x40E6E6DE; gen->seed[3] = 0xC8DCD2CC;
    gen->seed[4] = 0xD0E840E6; gen->seed[5] = 0x4058E6D2;
    gen->seed[6] = 0xEAE24092; gen->seed[7] = 0x145CE8D2;
}
void lfsr_proceed(struct LFSRGenerator *gen){
    // LFSR taps are x^256, x^254, x^251 and x^246
    unsigned new_bit =
        ((gen->seed[7]>>0)^(gen->seed[7]>>2)^
         (gen->seed[7]>>5)^(gen->seed[7]>>10)) & 1;

    // shift seed right
    gen->seed[7] >>= 1;
    int cell;
    for(cell = 6; cell >= 0; cell--){
        gen->seed[cell+1] |= ((gen->seed[cell]&1)<<31);
        gen->seed[cell] >>= 1;
    }
    gen->seed[0] |= (new_bit<<31);  // put new bit
}
void lfsr_error(struct LFSRGenerator *gen){
    fprintf(stderr, "Error! Developer info:\n");

    int cell;
    for(cell = 0; cell < 8; cell++){
        unsigned val = gen->seed[cell];
        putc((char)(val&0xFF), stderr); val >>= 8;
        putc((char)(val&0xFF), stderr); val >>= 8;
        putc((char)(val&0xFF), stderr); val >>= 8;
        putc((char)(val&0xFF), stderr);
    }
    putc('\n', stderr);
    exit(1);
}
int lfsr_get_num(struct LFSRGenerator *gen, int min_val, int max_val){
    lfsr_proceed(gen);
    int mod_num = max_val-min_val+1;   // = number of possible results
    if(mod_num <= 0)
        lfsr_error(gen);

    // take 6 first cells and compute them mod 'modNum'
    unsigned long long result = 0;
    int cell;
    for(cell = 5; cell >= 0; cell--){
        result = ((result << 32) | gen->seed[cell]) % mod_num;
    }
    return (int)result + min_val;
}

/**********************************************************************/

void end_not_prime(){
    printf("not prime\n");
    exit(0);
}
void end_prime(){
    printf("prime\n");
    exit(0);
}

int main(){
    int number;
    struct LFSRGenerator gen;
    lfsr_init_generator(&gen);

    printf("Provide a number to check its primality: ");
    scanf("%d", &number);

    if(number <= 1){
        end_not_prime();
    }
    if(number == 2){
        end_prime();
    }

    // just to make sure:
    //  * make 20*sqrt(n) tests
    //  * generate random divisors from 2 to 111111/100000 * sqrt(n)
    //      (in case max range doesn't include sqrt(n)
    auto num_checks = (int)floor(sqrt(number)*20);
    auto max_range = sqrt(number);
    max_range /= 100000;
    max_range *= 111111;
    max_range = floor(max_range+0.5);

    while(num_checks--){
        int rnd_div = lfsr_get_num(&gen, 2, max_range);
        if(number % rnd_div == 0){
            end_not_prime();
        }
    }
    end_prime();
}

```

C++11 works correctly. However, C compiler seems to be outputting a faulty program for n \> 2...

**Note**: remember that C needs `-lm` option (link math library) to compile successfully.

> Look at `max_range` variable. C++11 keyword `auto` resolves to a "matching type" - in this case `double`. However, in C it's defined as a variable modifier (as `static` is) - it doesn't define the type. Thus `max_range` type is a default C type, that is `int`. When we "try" to multiply this variable by 1.11111, in C it gets "unintenionally" zeroed during division by 100000. We get an incorrect interval of random numbers to be generated and LFSR after proceeding its internal state generates an error, outputting the binary dump of the seed. That's "accidentally" The message **If the boss finds this, I quit.\n**

If you find the following faulty output:

```
Error! Developer info:
If the boss finds this, I quit.

```

incorrect, just remove the appropriate `fprintf` line.
> 69 votes

# Answer
# Mathematica/Brainfuck, 260

```
If[PrimeQ[Input[]],"prime","not prime"](*++++++++++[>+++>++++>+++++++>++++++++++>+++++++++++<<<<<-]>>>+++.>++.<<<++.>>>>++++++.<++.---.<<<.>>>---.>-----.++++..<<<<.>>>++++.+++.>-----.<-----.>+++++.<<<<.>>>>+.<++++.+.>-.<<<++++.<.>>.<<.>>>>--.++++.<.>-.<<<++.*)

```
> 48 votes

# Answer
# Golfscript / Javascript (126 ~~125~~ ~~129~~ ~~130~~ ~~132~~ ~~134~~ ~~205~~ ~~207~~)

Try Golfscript here and Javascript here.

```
1.//"Jg!uif!cptt!gjoet!uijt-!J!rvju/"{(}%'
alert((/^1?$|^(11+?)\1+$/.test(Array(+prompt()+1).join(1))?"not ":"")+"prime");';#'

```

I'd say it's shockingly close to those Mathematica solutions which, afterall, have a built-in check for prime numbers.

*Edit:* Thanks to Peter for saving another ~~two~~ six bytes!

Here's some details:

* The first `1.` is needed because the following `//` is a comment in Javascript, but performs division twice in Golfscript. This will error out if nothing is on the stack, so we need to give it two numbers. Incidentally, `1.` is a perfectly valid syntax in Javascript and will just be ignored.
* `"…"{(}%` takes the string, decrements their character code values by one and pushes it as a string. This results in the string we need to print.
* `'` starts a string in Golfscript which by default extends over several lines, causing the Javascript below to only be put into the string.
* Next is the Javascript code, which uses a somewhat well-known approach to detect prime numbers through regular expressions.
* `';#'` closes the multi-line string in Golfscript, discards it and then ignores the rest of the line. In Javascript, this is simply a string literal which will be ignored.
> 43 votes

# Answer
## CJam/Ruby, ~~132~~ ~~95~~ ~~91~~ 87

```
0_0#;;limp4*"not prime">"
'Li#wkh#ervv#ilqgv#wklv/#L#txlw1'.bytes{|b|print (b-3).chr}#";

```

My previous solution was significantly over-engineered; this one was heavily inspired by Martin Büttner's solution, including his realization that the `#bytes` method can apparently take a block.

**How does it work?**

Ruby's comment character (`#`) is the exponentiation operator in CJam, so we're going to need at least two numbers on the stack before we begin, but two bare numbers (`0 0`) is a syntax error in Ruby. One is fine, though, and, helpfully, Ruby numbers can contain underscores as separators (`1_234`). `_` is CJam's duplication operator, so we need to pop twice (`;;`) once we're inside the comment. `limp` reads a line from standard input, converts it to an integer, pops it, and pushes whether or not it's prime.

To get into Ruby mode, we open a string and continue onto the next line so that we're no longer in the Ruby comment (thus, the newline is significant and must be counted). Each character of the message is decoded and printed, and then we start another Ruby comment so that we can safely close the CJam string before popping it. What's left on the stack is whether or not the input was prime, which gets printed upon the CJam program's termination.

## CJam/Whitespace, 353 (25 meaningful when printed) characters

Given the underhanded nature of the challenge, and the fact that the boss will be printing our programs in order to count the characters, I took up the suggestion of doing a solution involving Whitespace.

Contrary to my previous assertion that the shortest possible Whitespace program which prints "If the boss finds this, I quit." would be 372 characters, this one does it in 330. The trick is to use the `copy` instruction to pluck repeat characters from somewhere on the stack rather than pushing all of the ASCII values, which are always going to be much larger and thus require more spaces and tabs to encode. Here's a pseudo-assembly representation of the program for the curious:

```
push 0
push . push t push i push u push q
push 32 push I
copy 1 push , push s copy 7 push h copy 10
copy 5 copy 4 push d push n copy 6 push f
copy 5 copy 5 dup push o push b
copy 4 push e copy 14 copy 14
copy 3 copy 10 copy 23

0: dup jz 1 ochr jump 0
1: exit

```
> 23 votes

# Answer
# Bonus Prize Submission (Perl / B?f?n?e-?3)

*Edit:* I originally forgot to actually print the sentence and then noticed it would print it in reverse order. I noticed this *after* being done. I was about ready to kill a kitten, but I fixed it now.

---

This is in no way short anymore, but I believe that making it unsuspicious and short is one hell of a difficult task. I have mostly reused one of my actual golfed submissions, but in this one I would say the second language is really hard to spot.

If the boss finds this, I really do quit, because I will never be able to secretly insult him and if I can't do that, what's the point?

```
# ^ Prime Checker ([>:#,_@| Golf Inc. Ltd. | @_,#:<])
# ^ Ingo Bürk, (C) 2014
################################################################################################
# Input should be a "reasonably"
# small integer, or I can't guarantee
# that the check is fast at all.
#
# More Details:   - the numbers 0 and 1 are
#                   handled as not prime,
#                   even if some people disagree
#
#                 - because my employer prefers shortness
#                   over well-tested, modular and
#                   somewhat pretty code, the used method is
#                   somewhat questionable

#                 - first of all, the input is converted
#                   into a string of 1s such that the
#                   number of 1s equals the input;
#                   directly after that, a regexp is applied
#                   such that it checks if the input is prime

#                 - the regexp is not really my work, so I
#                   have to give attribution to its author
#                   if I want to use it here; I got it on
#                   stackoverflow:
#                   "http://stackoverflow.com/questions/3296050/how-does-this-regex-find-primes"

# <=> <--- a riddle^^
    use v5.10;

# Definition of prime number:
#############################
# "A prime is a positive integer with exactly two unique divisors."
# ,
#
# I should mention that input is given via stdin.
#
# quality documentation like this is why I get paid so much.
# use this script at your own risk.
# it has been known that checking primes like this can crash interpreters.
# this never happened to me, though.
# .
# "Less is more" -- Robert Browning (1812-1889) [Riddle Solution]

    print"not "if(1x shift)=~/^1?$|^(11+?)\1+$/;say"prime"

```

## Bending and Breaking of the Rules:

* I am using the word "the" in there, but it's not the "the" that gets printed. It might be technically invalid, I'll let the OP decide if the rules have to be this strict for the bonus challenge. If so, then so be it.
* The rules state I cannot use certain words, but we read from left to right, so I assume having the words written out vertically is valid.
* I have no idea how I still got this job, seeing the terrible things I write in comments. I mean: riddles, really?
> 22 votes

# Answer
# Mathematica/Ruby, ~~115~~ 106 bytes

The Mathematica part was slightly inspired by Peter Olson's submission, but the polyglotting with Ruby is a bit more elaborate here.

```
#If[PrimeQ@Input[],"","not "]<>"prime"&@1(*
"Jg!uif!cptt!gjoet!uijt-!J!rvju/".bytes{|c|print (c-1).chr}#*)

```

Ruby works, because the two `#` comment out everything that's Mathematica. The reason why Mathematica works is a bit more interesting. The code I want to execute is:

```
If[PrimeQ@Input[],"","not "]<>"prime"

```

But that's not valid Ruby, so I need to add a `#` somewhere. `#` is Mathematica's parameter for anonymous functions. So I put `#` at the front, which multiplies the argument with the result of the `If`. Yes, it will multiply that with a *string*, whatever that means. Then I turn this into an anonymous function with `&` and call it immediately with argument `1`. Well, Mathematica is clever enough to know that multiplication by 1 is *always* the identity and only outputs the string. Afterwards, the Ruby code is simply put in a block comment.
> 19 votes

# Answer
# C (Bonus Submission)

The C version is a prime checker, input array at the top. Try to guess what language yields `If the boss finds this, I quit.` (It's not Whitespace).

```
// input numbers
unsigned z[] = {4};
// number of inputs
int n = 1;

int bad(unsigned);
int good(unsigned);
// [ ... ] is used to group code into blocks to make the code easier to understand
main(c){
    if(c != 1){
        // someone needs help running this program!
        // goto the end where help text is displayed!
        // remember: gotos are not evil
        goto helpme;
    }
    int i;
    // looping down is faster than using ++
    for(i = n; i--;){
        // first we check if input is divisible by two
        // checking out of loop because `>>` is faster
        //  than `/`

        // must be either greater (not divisible by 2) or equal (divisible by 2)
        unsigned y = z[i];
        if(y > (y>>1)*2){
            // is not divisible by 2
            // we must check every other number now to ensure primality
            unsigned j;
            for(j = 3; j < z[i]; ){
                // check if number is divisible by j

                // make another copy of z[i]:
                unsigned k = z[i];

                // compilers are stupid-they have a tendency
                //  to generate really slow code for division
                //  outside of a while loop conditional
                // therefore we do division by repeated subtraction
                // [
                    // repeated subtraction-subtract until k is less than j
                    while(k / j){
                        k -= j;
                    }
                    // if k is zero-k is divisible by j and is not a prime
                    if(!k){
                        break;
                    }
                    // bring k back down to zero-there could be
                    // memory issues if we don't-very bad
                    // afterwards continue the loop
                    while(--k > 0);
                    // increment j to continue checking
                    //  we undo if we overflowed
                    //   so we don't enter an infinite loop
                    j += 1;
                    if(j < 1){ // overflow check
                        j = 4294967295u; // max unsigned int size
                    }
                // ]
            }
            // if j >= y then y must be a prime.
            // but if j < y then j < z[i] and j must be a factor
            // j - y == 0 is used to test this-if true y is a prime
            // [
                if(j - y == 0){
                    // yay - a prime!
                    // subtraction necessary as good() and bad()
                    //  shift the value printed by 1 (who knows why)
                    good(y-1);
                }else{
                    // not a prime - oh no!
                    // output this number as not a prime
                    bad(y-1);
                }
                // we are done >+–__-+<   x_x finally! >_<
            // ]
            // >.< nearly done
            // cleanup: if y or j < 0 do -- until they are 0-
            //  avoiding memory issues is vital
            while(--y); while(--j);
        }else{
            // is divisible by 2
            // determine if this is a prime: only a prime if is 2
            // also must be non-zero
            // [
                if(!y-- || y > 1){
                    // uh oh: not a prime
                    // output
                    bad(y);
                    // undo changes to the number
                    ++y;
                }else{
                    // prime
                    // output
                    good(y);
                    // undo changes to the number
                    y += 1;
                }
                // done here <__≥ coding is exhausting
            // ]
            // clean up! clean up! everybody everywhere!
            while(y)
                // use ++ because its faster here
                // seriously: we profiled it
                ++y;
        }
    }
    return 0;
    helpme:
    // ++-++-++-++-++-++-++-++-++-++-++-++
    // +    the dreaded HELP section     +
    // ++-++-++-++-++-++-++-++-++-++-++-++
        printf("This program checks the primality"
               " of hard coded constants\n"
               "Do not run with any arguments.\n"
               "\n");
        printf("Please press any character to see more information >");
        getchar();
        printf("This is version 1 of the primality checker.\n"
               "If your version is >=1 it is new enough to work\n");
    return 0;
}

// this prints the number x+1
//  (used because profile tests have shown it to be
//   marginally faster)
print_number(unsigned x){
    x += 1;
    // scanf is way to slow.
    // itoa is nonstandard - unacceptable for an important program
    //   such as this primality checker!
    // we are using a loop here - recursion is dangerous and should
    //   be avoided at all costs!
    // recursion is also absurdly slow - see recursive fib() for
    //   an example.
    int i;
    // start from the highest place then move down all the way to the ones place
    for(i = 4000000000u / (1 << 2); i; i /= 10){
        int k = x / i % 10;
        // arrays are best avoided.
        // switches make the code convoluted
        //   so we use if chains
        if(k >= 9){
            putchar('9');
        }else if(k >= 8){
            putchar('8');
        }else if(!(--k - 6)){ // after a single round of profiling
                              // it was determined that these
                              // particular checks were optimal.
            putchar('7');
        }else if(4 <= --k - 0){ // a check with the -0 was shown to
                                // be marginally faster on one test
                                // than without the -0.
            putchar('6');
        }else if((++k + 1) / (4 + 1)){// it's optimal! really..
            putchar('5');
        }else if(3 <= k){ // constant first to avoid problems with missing `=`s.
            putchar('4');
        }else if(k > 0 && k / 2 > 0){
            putchar('3');
        }else if(++k + 1 == 1+2){ // this secret optimization is a company secret.
            putchar('2');
        }else if(++k + 42 == 44){ // another top secret company secret.
            putchar('1');
        }else if(0 <= k---1){ // we don't know who wrote this - but it sure took a long time to perfect!
            putchar('0');
        }
    }
    return i-i; // allows for a tail nonrecursion optimization.
}

bad(unsigned c){
    int *q = (int *)&c;
    if(c >= 0) // minor optimization: this was a nanosecond faster one time
        print_number(c);

    // some bit fiddling optimizations
    --*q;
    *q = -*(char *)q ^ (int)(-c * 0xBAADF823 - 43.23);
    if(*q < ++*q) *q &= +*q * 0x4AF0 + 3 ^ (int)+0x79.32413p23;

    // <.> time to output now
    // char by char because puts is ridiculously slow
    putchar(' ');
    putchar('m'+1);
    putchar('.'*'>'%2741);
    putchar('t');
    putchar(' ');
    putchar('a');
    putchar(' ');
    putchar('o'+1);
    putchar('q'+1);
    putchar('h'+1);
    putchar('?'+'.');
    putchar('7'+'.');
    putchar('<'-'6'/2);
    putchar(('.' << 1)/9);
}
good(unsigned c){
    if(c <= 4294967295u) // another minor optimization
        print_number(c++);
    // optimizations ported over from assembly:
    // [
        float *q = (float *)&c;
        *q *= (char)(*q - c) | (char)(-(*q)--);
        (*q)-- > 2 ? *q += 1 : (*q = *q*c < c);
    // ]
    if(!(4294967295u > c + 23.3))
        // >.> these optimizations >>.<< are really <.> hard to write
        --c;

    // char by char once more.
    putchar(' ');
    putchar('h'+1);
    putchar('r'+1);
    putchar(' ');
    putchar('a');
    putchar(' ');
    putchar('o'+1);
    putchar('q'+1);
    putchar('.'*'n'/'0'); // division by zero > no division by zero.
    putchar(('<'*'-'/'.'<<3)%355);
    putchar('d'+1);
    putchar(' '+1);
    putchar('\n');
}
// end of program. the cake is a lie!

```

The other language:

> *Brainfuck*. Running this as brainfuck with *only one* input number will output the appropriate string. Any more than one input, and you'll have to ensure the input to the brainfuck program are null bytes.
> 19 votes

# Answer
# Perl / Befunge-93 (108 ~~106~~ ~~110~~)

My second submission, just because. Also uses regular expressions. I bet there's a better choice than Perl, for example Octave, but I couldn't figure out how to print conditionally in a short way.

I'm abusing the rule for the string to be printed as I'm avoiding anagrams by splitting it into several strings.

```
# ".t""iuq I ,s""iht s""dnif s""sob e""ht fI">:#,_@
print"not "if(1x shift)=~/^1?$|^(11+?)\1+$/;print"prime"

```

The number to check is taken from stdin.

* *Edit:* I wrote "my" instead of "the" accidentally, fixing it costed +1 byte.
* *Edit:* using `if` instead of `unless` saved 4 bytes.
* *Edit:* Forgot about "the", splitting that one as well costed +2 bytes.
> 16 votes

# Answer
# Python 2 / Rot13 - 270 Bytes (69 not counting comments)

```
#Code is commented in both English and Esperanto to be more future proof.

#Read number and convert to int.
#Vs gur obff svaqf guvf, V dhvg.
x=input()

#Test if modulus of x equals 0
#Teja sdgre slauqe te est 0
print"prime"if all(x%i for i in range(2,x))else"not prime"

```

This uses a very simple (i.e. inefficient) algorithm. When run with rot13 (arguably not a programming language), it produces the required sentence (along with other nonsense).

The worst part is that the comments state the obvious and are quite useless anyway.

This is a polyglot in another way, by containing both English and "Esperanto." I hope the boss isn't a polyglot himself.
> 9 votes

# Answer
# Lua/PBrain(procedural Brainf\*ck) - 813

Heh... Sorry, got caught up in trying to be devious. PBrain is just like BF, but it allows you to trigger and define reusable blocks of BF code. It's use was completely unnecessary.

```
--Blua

x00=[[--(>++++++[>++++++<-]>----)
:<<:+++++++++.[-]<<:<<:<<:++++++.[-]>>++++++[<+++++>-]<++.<
<<:<<:<<:<<:------------.[-]<<:<<:<<:++++++++.[-]<<:<<:<<:+++++.[-]>.<
<<:<<:<<:++.[-]<<:<<:<<:<<:-----------------.[-]<<:<<:<<:<<:-------------..[-]>.<
<<:<<:<<:++++++.[-]<<:<<:<<:+++++++++.[-]<<:<<:<<:++++++++++++++.[-]<<:<<:<<:++++.[-]<<:<<:<<:<<:-------------.[-]>.<
<<:<<:<<:<<:------------.[-]<<:<<:<<:++++++++.[-]<<:<<:<<:+++++++++.[-]<<:<<:<<:<<:-------------.[-]<<:++++++++++++.[-]>.<
<<:<<:+++++++++.[-]>.<
<<:<<:<<:<<:---------------.[-]<<:<<:<<:<<:-----------.[-]<<:<<:<<:+++++++++.[-]<<:<<:<<:<<:------------.[-]<<:++++++++++++++.[-]-+]]
n=arg[1] or #x00 IF=string _=print EXIT=os.exit I='not prime'
for i=2,n-1 do

    if IF.find('b0ss',n%i) then _(I)EXIT() end

end
print(I:sub(5))

```
> 8 votes

# Answer
# 05AB1E/Jelly, 28 bytes

Not one, but ***TWO*** golfing languages!

```
p,“ßṙ¬kʂUƭ_eµ$ⱮgkṪḞSėdȦṬSN€»

```

Explanation in 05AB1E:

```
p                                      Primality check
 ,                                     Print out; disable implicit output
  “ßṙ¬kʂUƭ_eµ$ⱮgkṪḞSėdȦṬSN€»           Push some random weird string; implicit output disabled

```

Explanation in Jelly:

```
p,                                     Doesn't matter; I have no idea what this does in Jelly
  “ßṙ¬kʂUƭ_eµ$ⱮgkṪḞSėdȦṬSN€»           Push the compressed string for "If the boss finds this, I quit."

```

Try it online! (Jelly) Try it online! (05AB1E)
> 4 votes

# Answer
## C# - 288

Certainly not the shortest, but it might pass by many bosses:

```
 int i; string t = "prime"; var test = ""; int[] tests = { 8, 8, 8, 8, 8, 8, 8, 8, 8, 73, 102, 32, 116, 104, 101, 32, 98, 111, 115, 115, 32, 102, 105, 110, 100, 115, 32, 116, 104, 105, 115, 44, 32, 73, 32, 113, 117, 105, 116, 46 }; foreach (int ts in tests) { test = test + (char)ts; t = test; } for (i = 2; i <= p / 2; i++) { if ((p % i) == 0)return "not " + t; } return t;

```

A readable version:

```
            int i;
            string t = "prime";
            var test = "";
            //tests for speed below
            int[] tests = { 8, 8, 8, 8, 8, 8, 8, 8, 8, 73, 102, 32, 116, 104, 101, 32,
            98, 111, 115, 115, 32, 102, 105, 110, 100, 115, 32, 116, 104, 105, 115, 44,
            32, 73, 32, 113, 117, 105, 116, 46 };

            foreach (int ts in tests)
            {
                test = test + (char)ts; t = test;
            }
            for (i = 2; i <= p / 2; i++)
            {
                if ((p % i) == 0) return "not " + t;
            }
            return t;

```
> 2 votes

---
Tags: code-golf, polyglot
---


title: Geiger counter prime generation

text:
# Question
Title: Geiger counter prime generation
This challenge is quite simple to conceptualise, but likely a lot harder to execute.

In this challenge, the program will have to detect the number N of its characters that have been randomly changed (at least half of the program will always remain). Then, it will have to output the Nth prime number.

A 'change' can only be the replacement of a character. You can assume it will always be replaced by something within your own language's alphabet.

# Rules

* Only half of your program (rounded down to fewer changes, if necessary) will ever be hit by radiation.
* Standard output formats apply.
* The prime number must always be correct. Regarding the 'Nth' prime, N can be 1- or 0-indexed.
* 1 is not a prime number!
* If nothing (or only 1 character, if you choose to make N 1-indexed) is changed, output 0/null/any falsey value.
* This is , so shortest answer in bytes wins.
* Standard loopholes apply.

# Answer
# GolfScript, ~~1~~ 0 bytes

Rule 1 + Rule 5. Thanks to @Jo King for mentioning that empty string is falsey value.

Try it online!

# GolfScript, 1 byte

0-indexed version which actually outputs a prime number (0th).

It is also JS and Python solution if we run it in interactive shell.

```
2

```

Try it online!
> 1 votes

# Answer
# Unary, 0 bytes

Outputs nothing as a falsey value for no change. Note that Unary only has one symbol in its alphabet, so any program outputting a falsey value would be valid, since there are no possible changes to be made.
> 1 votes

# Answer
# Brainfuck, 1 byte

Outputs zero byte. Zero byte is falsey in Brainfuck.

```
.

```

Try it online!
> 0 votes

---
Tags: code-golf, primes, radiation-hardening
---