title: Reuse your code!

text:
# Question
Title: Reuse your code!
In this challenge we try to solve two important problems at once. They are:

1. Given integers \\$a\\$ and \\$b\\$, tell if \\$a^b-1\\$ is a prime number.
2. Given integers \\$a\\$ and \\$b\\$, return \\$a\choose b\\$.

Specifically, you must write two programs, one that does the first task and one that does the other. As we want to solve both problems at once, it is encouraged to use a same piece of code in both programs.

## Scoring

The score of an answer is the Levenshtein distance between the two programs. Lower score is better. In case of a tie, the answer with the shortest combined code of the two programs wins. You can use this script to calculate the score of your solution.

## Rules

1. You must write two programs in the same language that solve the tasks described above. You can use any I/O methods you want. For task 1, you can return a truthy/falsy value or choose two values to mean true and false and return them accordingly. Eg. you can choose that `"prime"` means true and `"not prime"` means false.
2. The algorithms you use must work for all possible inputs, but it is OK if the code fails for large numbers due to limitations of the used number type. You can assume that the input is valid.
3. No subset of the program must solve the problem, ie. the code must not work if any character(s) are removed. For example, the following code is not valid, because it is possible to remove the unused else-block without breaking the program:

```
 if (1) { /* change to 0 to get the second program*/
     ...
 } else {
     ...
 }

```
4. Standard loopholes are not allowed.

## Test cases

### \\$a^b-1\\$ is prime?

```
a b
1 1 false
2 3 true
5 2 false
2 5 true
4 3 false
2 7 true

```

### \\$a\choose b\\$

```
a b nCr(a,b)
1 1 1
5 2 10
4 3 4
10 7 120
12 5 792

```

# Answer
# Ruby, Distance 1, Combined Length 194

**Prime check:**

```
->a,b{s='[(a**b-1).prime?,(1..b).inject(1){|m,i|(a+1-i)/i*m}][0]';require'math'<<s.size*2;eval s}

```

Try it online!

**nCr:**

```
->a,b{s='[(a**b-1).prime?,(1..b).inject(1){|m,i|(a+1-i)/i*m}][1]';require'math'<<s.size*2;eval s}

```

Try it online!

As predicted in the comments, some jerk always has to go against the spirit of the problem. It was fun finding a way to work around it, though! Here's how it works: We have two separate solutions to the problems. We run both, put them into an array, and then either choose the 0th element or the 1st, for an edit distance of 1. This would ordinarily be illegal, since you could just delete everything but the calculation you wanted and it would still work. However, each code snippet is written to rely on the loading of the same standard library, `'mathn'`:

* The first uses its builtin `prime?`
* The second relies on `mathn` changing how division works--before loading it, `3/4` evaluates to `0`, while afterwards it evaluates to the fraction `(3/4)`. Since the intermediate result of `(a+1-i)/i` is not always a whole number, the overall result is wrong without the library.

Now we just need to make loading the library contingent on the rest of the code being unmodified. We do this by generating the name mathn using the character length of the rest of the main code: the combined calculation has length 55, which doubled to 110 is the ASCII value of 'n'. So concatenating this onto the string 'math' gives the desired library.

As a bonus, introducing the library dependencies also makes the code run in a reasonable amount of time. In particular, the naive approach to nCr wouldn't generate fractional intermediate results.
> 8 votes

# Answer
# MATLAB, distance 10

**Primality:**

```
function x=f(a,b);x=isprime(a^b-1);

```

**nCr:**

```
function x=f(a,b);x=nchoosek(a,b);

```
> 7 votes

# Answer
# PHP, distance 29

`a^b-1` prints 0 for true and any integer value \> 0 for false

```
[,$a,$b]=$argv;for($c=-$i=1;$i<=$d=$a**$b-1;$d%++$i?:$c++);echo$c;

```

`nCr(a,b)`

```
[,$a,$b]=$argv;for($c=$i=1;$i<=$a;$c*=$i**(1-($i<=$a-$b)-($i<=$b)),$i++);echo$c;

```

## PHP, distance 36

`a^b-1` prints 1 for true nothing for false

```
[,$a,$b]=$argv;for($c=-1,$i=1;$i<=$d=-1+$a**$b;)$d%++$i?:$c++;echo$c<1;

```

`nCr(a,b)`

```
[,$a,$b]=$argv;for($c=$d=$i=1;$i<=$a;$c*=$i++)$d*=$i**(($i<=$a-$b)+($i<=$b));echo$c/$d;

```
> 7 votes

# Answer
# 05AB1E, distance 3

**nCr**

```
sc

```

Try it online!

**isPrime(a^b-1)**

```
m<p

```

Try it online!
> 5 votes

# Answer
# Stacked, distance 13

```
[([@.!]$/{%y!x y-!*})fork!]
[^#-:([]1/$%{!n 1-!})fork!=]

```

Try it online! The first calculates nCr, the second primality, using Wilson's theorem.

`(f g h) fork!` pops `N` args from the stack (call them `a0 ... aN`) and applies `a0 ... aN f a0 ... aN h g`.

For the first program:

```
[([@.!]$/{%y!x y-!*})fork!]
[(                  )fork!]  apply the fork of:
  [@.!]                      equiv. { x y : x ! } => `x!`
       $/                    divided by
         {%        }         two-arg function
           y!                y!
             x y-                 (x - y)!
                 *              *

```

And for the second:

```
[^#-:([]1/$%{!n 1-!})fork!=]
[^                         ]  exponentiate  (a^b)
  #-                          decrement     (a^b-1)
    :                         duplicate     (a^b-1 a^b-1)
     (              )fork!    apply the fork to:
      []1/                    1-arg identity function
          $%                  modulus by
            {!     }          1-arg with `n`:
              n 1-             (n-1)
                  !                 !
                          =   check for equality

```
> 4 votes

# Answer
# Python 2, distance 15, length 172

### Task 1

```
D=lambda k:max(k-1,1)
P=lambda n,k=0:n<k or P(n-1,k)*n/k
lambda a,b:P(a**b-2)**2%D(a**b)

```

### Task 2

```
D=lambda k:max(k-1,1)
P=lambda n,k=1:n<k or P(n-1,D(k))*n/k
lambda a,b:P(a,b)/P(a-b)

```

Try it online!
> 4 votes

# Answer
# Mathematica, distance 10

Task 1: `PrimeQ[#2^#-1]&`

Task 2: `Binomial[#2,#]&`

Both functions take the inputs in the order `b,a`.
> 3 votes

# Answer
# Javascript ES7, distance 14

Thanks @Conor O'Brien for reducing the distance by 7

**Primality:**

```
f=x=>y=>{t=x**y-1;s=1;for(i=2;i<t;i++){if(!t%i)s=i-i}return s}

```

Returns 1 if prime returns 0 if not prime.

Incredibly inefficient prime check, checks the number modulo every number smaller than it and greater than 1...

**nCr:**

```
f=x=>y=>{t=x+1;s=1;for(i=1;i<t;i++){if(y<i)s*=i/(i-y)}return s}

```

Multiplies 1 by each number from y+1 to x and divides by each number from 1 to x-y (x!/y!)/(x-y)!
> 3 votes

# Answer
# Octave, distance ~~17~~ ~~16~~ 15

### nCr

```
a=input("");b=input("");f=@(x)factorial(x);printf("%d",f(a)/f(b)/f(a-b))

```

Try it online!

### `isprime(a^b-1)`

```
a=input("");b=input("");f=@(x)isprime(x);printf("%d",f(a^b-f(8-6)))

```

Try it online!

I am not very fluent in Octave, so I don't know if there is a builtin to calculate nCr.
> 2 votes

# Answer
# MATL, distance 4, length 6

### Tell if `a^b-1` is prime:

```
^qZq

```

Try it online!

### Compute `nCr(a,b)`:

```
Xn

```

Try it online!

## How it works

### Tell if `a^b-1` is prime:

```
^      % Power with implicit inputs
q      % Subtract 1
Zq     % Is prime? Implicit display

```

### Compute `nCr(a,b)`:

```
Xn     % nchoosek with implicit inputs. Implicit display

```
> 1 votes

# Answer
# Pyth, distance 4, total length 8

## Primality of `a^b-1`

```
P_t^F

```

Try it online!

## nCr(a, b)

```
.cF

```

Try it online!

Both take input as tuples/lists of integers (e.g. `(1,2)`).
> 1 votes

# Answer
# PHP, distance 14

Writing a program with two functions and only calling one of them would lead to a distance of 1, but it´d be too lame.

Prime Test, 100 bytes:

```
[,$a,$b]=$argv;function f($n){for($i=$n;--$i>0&&$n%$i;);return$i==1;}echo f($a**$b*-1)*(1|f($a-$b));

```

nCr, 98 bytes:

```
[,$a,$b]=$argv;function f($n){for($i=$n;--$i>0&&$n*=$i;);return$n*=1;}echo f($a)/(f($b)*f($a-$b));

```
> 1 votes

# Answer
# Jelly, distance 4, length 5

### Task 1

```
*’ÆP

```

### Task 2

```
c

```

Try it online!

## How it works

### Task 1

```
*’ÆP  Main link. Argument: a, b

*     Yield a**b.
 ’    Decrement; yield a**b-1.
  ÆP  Test the result for primality.

```

### Task 2

```
c     nCr atom

```
> 0 votes

# Answer
# JavaScript, Score:1, Length:~~144~~ ~~142~~ ~~126~~ 117

```
function(a,b){s="a=Math.pow(a,b)-t;for(b=2;a%b++;);b>a1for(;b;)t=t*a--/b--";t=s.length-56;return eval(s.split(1)[0])}

```

~~function(a,b){s="a=Math.pow(a,b)-s.length+79;for(b=2;a%b++;);b\>a1for(t=s.length-79;b;)t=t\*a--/b--";return eval(s.split(1)\[1\])}~~

~~```
function A(a,b){a=Math.pow(a,b)-(B+0).length+63;for(b=2;a%b++;);return b>a;}
function B(a,b){for(t=(A+0).length-76;b;)t=t*a--/b--;return t;}
F=A

```~~

~~Both subroutines use the other one's length to calculate its own constant, so no char can be removed~~
> 0 votes

---
Tags: code-challenge, number-theory, primes, combinatorics, source-layout
---


title: Programming with a Sporadic Shift Key

text:
# Question
Title: Programming with a Sporadic Shift Key
There's something wrong with your keyboard. The `Shift` key has a mind of its own. Every time you type a character you have no idea whether it will come out shifted or not (though it is 50-50). Besides the standard character keys, nothing on the keyboard is functional. There is no mouse or other means of input.

Somehow you know the only way to fix things is to write a program that outputs `Dear Computer, please stop giving me shift!` to stdout. Luckily your IDE is open and you are capable of running a program, but of course as you type it you won't know which characters will be shifted.

*What sequence of key-presses would you use to write a program that has the best possible chance of working on the first try?*

# Details

You are using a standard QWERTY keyboard, so there are 50 character keys you can press.

Unshifted versions (47 only):

```
`1234567890-=qwertyuiop[]\asdfghjkl;'zxcvbnm,./

```

Shifted versions (47 only):

```
~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:"ZXCVBNM<>?

```

The last 3 keys are `Enter`, `Tab`, and `Space`, which are the same shifted and unshifted.

A sequence of N of these characters has 2N - (whitespace char count) ways it might have been output if you had typed them with your faulty keyboard. For example, typing `A` `Space` `m` might have yielded `a m` or `A m` or `a M` or `A M`.

Write a program these characters and look at all of its 2N - (whitespace char count) possible shift combinations. The more combinations that output `Dear Computer, please stop giving me shift!` the better. Your score is the number of working combinations (valid programs) divided by the total number of combinations. The highest score wins.

# Notes

* For valid programs, printing precisely `Dear Computer, please stop giving me shift!` and nothing else to stdout should be the only side effect.
* Valid programs should not take input.
* Invalid programs can do anything whatsoever.
* Comments may be used anywhere.
* Whitespace answers cannot win because getting a 100% score is (relatively) trivial. You may still submit a Whitespace solution for fun.
* Your program must be at most 1024 characters long.

***Update:* Changed `Stop giving me shift!` to `Dear Computer, please stop giving me shift!` to allow for more complex answers. Existing answers may stay the way they are if desired.**

# Answer
> 47 votes
# Applescript, 20 (100%)

I believe I can claim a perfect score here:

* The Applescript Editor (my IDE) automatically converts all keywords to lower case upon compiling/running
* Furthermore, defined variable and handler names are case insensitive - For example if a handler `myFunc` is defined, then the IDE will automatically convert `MYFUNC`, `myfunc`, `MyFuNc`, etc references to `myFunc`
* I have only used alphabetic characters, spaces and newlines, so I don't need to worry about shifted numbers and punctuation characters.

Here is is:

```
global f
on j at a
set end of a to j
end
on c at a
j at a
j at a
end
on k at a
repeat with q in system info
j at a
end
end
on w at a
set d to count a
j at a
return string id d
end
on z at a
set end of f to a
end
set h to space
set y to h as list
k at y
k at y
set x to w at y
c at y
c at y
c at y
c at y
c at y
set q to w at y
k at y
c at y
c at y
copy y to b
c at y
set s to w at y
set d to w at y
set f to d as list
k at b
k at b
set a to w at b
c at b
j at b
set e to w at b
set y to w at b
set g to w at b
set d to w at b
set i to w at b
c at b
set l to w at b
set m to w at b
set n to w at b
set o to w at b
set p to w at b
j at b
set r to w at b
z at e
z at a
z at r
z at h
z at s
set s to w at b
set t to w at b
set u to w at b
set v to w at b
z at o
z at m
z at p
z at u
z at t
z at e
z at r
z at q
z at h
z at p
z at l
z at e
z at a
z at s
z at e
z at h
z at s
z at t
z at o
z at p
z at h
z at g
z at i
z at v
z at i
z at n
z at g
z at h
z at m
z at e
z at h
z at s
z at d
z at i
z at y
z at t
z at x
f as text

```

Thanks to the help of @kernigh and @paradigmsort, this is now 1020 bytes, just squeaking in under the 1024 byte limit!

### Explanation:

* The characters for output string are generated using `string id <n>`, which returns the character corresponding to the ascii value `n`
* Because we are avoiding digits, each `n` has has to be generated by more fundamental means. Specifically we generate each `n` by counting a list, and then adding another item to that list. The `repeat with q in system info` allows us to do this 16 times, as `system info` always returns a 16-item list.
* Using a similar technique, we add each character of the final string in turn to a list.
* Finally that last list is coerced to `text` and printed.

### Output:

Using the `osascript` interpreter, but the Applescript Editor works just as well:

```
$ # Interpret as-is:
$ osascript dearcase.scpt
Dear Computer, please stop giving me shift!
$
$ # Interpret all lower case:
$ tr A-Z a-z < dearcase.scpt | osascript
Dear Computer, please stop giving me shift!
$
$ # Interpret all upper case:
$ tr a-z A-Z < dearcase.scpt | osascript
Dear Computer, please stop giving me shift!
$
$ # Interpret random case for each letter:
$ while read; do for ((i=0;i<${#REPLY};i++)); do c="${REPLY:i:1}"; if ((RANDOM%2)); then printf "%s" "$(tr a-z A-Z <<< "$c")"; else printf "%s" "$(tr A-Z a-z <<< "$c")"; fi; done; echo; done < dearcase.scpt | osascript
Dear Computer, please stop giving me shift!
$

```

# Answer
> 16 votes
# PHP, 2^-12

```
echo ucwords(strtolower('Dear Computer, ')).strtolower('please stop giving me shift!');

```

PHP being PHP, capitalization of `echo`, `ucwords`, and `strtolower` don't matter. The calls to `ucwords` and `strtolower` ensure that the case of the strings won't change the output.

Therefore, the only characters that can't be changed are `((,)).(!);` (10 characters).

Each pair of quotes also has a 50% chance of being valid (`''` and `""` are valid, but `'"` and `"'` are not), therefore each adding another power of two.

# Answer
> 4 votes
# CJam, 2-7 2-12 chance

```
'D"ear Komputer, please stop giving me shift!"el4'Ct

```

It has similar idea as Quincunx's first answer, but in CJam.

# Answer
> 4 votes
# Whitespace (645 bytes, 2^0 probability)

Since this program *only* uses tabs, spaces and newlines (which are all unaffected by shifting), it gives a 100% success rate.

```

```

Program run

# Answer
> 3 votes
# Python 2, 2-20 chance

```
print'S'+'top giving me shift!'.lower()

```

`print`, `S`, `+`, `!`, and `.lower()` must all be the correct version; that's 18 chars. The two quotes for the strings must also align, that makes two more powers of two.

For any of the `top giving me shift`, if it is converted to the capital version, we convert it to lowercase and it works properly.

Sadly, I can't make use of Python's nifty `capitalize()`, because that takes one more character.

# Answer
> 3 votes
# CJam, 2-9 chance, 739 bytes

```
"
(lines of space characters)
                                        "N/2fb:c

```

base64:

```
IiAJICAgIAkgCQkgICAJICAKICAgCSAJCSAgIAkJCQkgCQoJCQkJIAkgIAkJIAkJICAJCiAJICAg
IAkgCQkgICAgCSAKICAgCSAJCSAgCSAgICAgIAogCQkJCSAJICAJCSAJIAkJCgkJCSAJICAJCSAJ
CSAJCQkKIAkgCQkgIAkgICAgIAkgCQoJIAkJICAJICAgIAkgICAgCgkgIAkJIAkJCQkgIAkJIAkK
CQkgCSAgCQkgCQkJIAkgIAogICAJIAkJICAgCQkJCSAJCiAJICAgIAkgCQkgICAgCSAKIAkJCQkg
CSAgCQkgCQkgIAogICAJIAkJICAJICAgICAgCgkgCQkgIAkgICAgCSAgICAKCSAgCSAgICAJIAkg
CQkgIAogICAJIAkJICAgCQkJCSAJCgkJCQkgCSAgCQkgCQkgIAkKICAgIAkgCQkgICAJCSAJCQog
ICAJIAkJICAgCQkJCSAJCiAgIAkgCQkgIAkgICAgICAKICAgIAkgCQkgICAJCSAJCQoJCSAJICAJ
CSAJCQkgCSAgCgkJCSAJICAJCSAJCSAJCQkKCSAJCSAgCSAgICAJICAgIAogICAJIAkJICAJICAg
ICAgCgkgCSAgCQkgCQkJIAkJCQkKICAJCSAJCQkJIAkgICAgCQogCQkgIAkgICAgCSAgCQkgCiAg
CQkgCQkJCSAJICAgIAkKICAJICAgIAkgCSAJCQkJIAoJIAkgIAkJIAkJCSAJCQkJCiAgIAkgCQkg
IAkgICAgICAKIAkgCQkgIAkgICAgIAkgCQogICAJIAkJICAgCQkJCSAJCiAgIAkgCQkgIAkgICAg
ICAKICAgIAkgCQkgICAJCSAJCQogCQkgCQkJCSAJICAJICAgCiAgCQkgCQkJCSAJICAgIAkKCQkg
CQkJCSAJICAJIAkJIAoJCSAJICAJCSAJCQkgCSAgCgkJIAkJCQkgCSAgCQkgIAkiTi8yZmI6Yw==

```

Based on the idea of Optimizer and Quincunx's answer.

# Answer
> 2 votes
# VisualBasic.net 2^-18

Critical chars: .("DearC"+",!".())

```
Sub Main
  console.write("Dear C"+"omputer, please stop giving me shift!".tolower())
End Sub

```

Tested in LINQPad, Language = "VB Program"

# Answer
> 1 votes
# Pyth, 2\**-15

```
+"S"$"top giving me shift!".lower()

```

I can't seem to find Pyth's version of `lower()`, so I'll borrow from Python. The characters that can't be swapped are `+"S"$`, `!`, and `.lower()`, for a total of 14 chars. The quotes after the `$` must match, adding another power of 2.

# Answer
> 1 votes
## CJam, 2-13 chance

As per the updated string (696 bytes).

```
"

             "N/:,2/Kfb:c

```

Only `""N/:,2/Kfb:c` are at risk right now.

Try it online here and since this text editor is eating up all the spaces, here is the gist with the correct code.

# Answer
> 1 votes
# Rant, 2-21

```
[caps:first][?[caps:word][?[caps:lower]Dear Computer][caps:lower], please stop giving me shift!]

```

A series of metapatterns and `caps` calls force proper formatting. Function names and arguments are case insensitive.

Online version

# Answer
> 1 votes
## VB.NET, ~~2^-12~~ 2^-11

**2-12**

```
Module All
  Sub Main
    Console.WriteLine StrConv("Dear Computer, ", vbTuesday) & "please stop giving me shift!".ToLower
  End Sub
End Module

```

**2-11**

```
Imports System.Console

Module All
  Sub Main
    Write StrConv("Dear Computer, ", vbTuesday)
    WriteLine "please stop giving me shift!".ToLower
  End Sub
End Module
```

# Answer
> 0 votes
I thought about my answer before getting to the '50 characters including only Enter, Tab, Space' rule. So mine is not valid.

Seems having case insensitive programming languages is the key here. Alternatively, if you could use a Real standard QWERTY keyboard (including Caps Lock, the other Shift, Backspace, and the Numpad Period) there would only be 2 necessary 50% chances which would only result in 2 additional key presses per failure. My invalid answer for a C# Console Application pointing out actual key presses:

```
HoldShift(C CpsLockOn onsole)

NumPadPeriod

HoldShift(
CpsLockOff W CpsLockOn rite("
CpsLockOff D CpsLockOn ear space
CpsLockOff C CpsLockOn omputer
)

, (repeat with Backspace until correct)

HoldShift( please stop giving me shift!"))

; (repeat with Backspace until correct)

```

---

76 minimum presses with only 2 necessary 50% chances

# Answer
> 0 votes
# Excel, 2-11

```
=PROPER("Dear Computer, ")&LOWER("please stop giving me shift!")

```

Case of `PROPER` and `LOWER` don't matter. Entering a formula starting with `+` automatically inserts required `=`. So only `(`, `"`, `,`, `)`, `&`, `!` can break.

---
Tags: code-challenge, restricted-source
---


title: Wir hassen Umlaute! (We hate umlauts!)

text:
# Question
Title: Wir hassen Umlaute! (We hate umlauts!)
# Introduction

As you all know, German has umlauts. They're these things: `¨`

However, most keyboards don't have an umlaut key. That's fine, though, because you can write `ö`, `ä`, and `ü` as `oe`, `ae`, and `ue`.

# Challenge

* Your job is to to replace `ö`, `ä`, and `ü` with `oe`, `ae`, and `ue` (and likewise for their capital versions).
* You have to deal with both the combining diacritical mark and single characters. (Thank you @ETHProductions for pointing this out.)
* Capitalization of the base letter stays intact.
* Capitalization of the `e` depends on the capitalization of the surrounding letters after replacement. You should write it as `e` unless it's adjacent to a capital letter on both sides, in which case write it as `E`. (End of line and space are not capital letters.)
* Standard loopholes and I/O rules apply.
* This is code-golf, so shortest code in **UTF-8** bytes wins!

# Example Input and Output

**Test cases using precomposed characters**

```
ü = ue
üb = ueb
üB = ueB
Ü = Ue
Üb = Ueb
ÜB = UEB

```

**Test cases using combining diacritics**

```
ö = oe
öb = oeb
öB = oeB
Ö = Oe
Öb = Oeb
ÖB = OEB

```

# Answer
# Perl 5 (`-pC -MUnicode::Normalize -Mutf8 -MList::Util=max`), ~~63~~, ~~58~~, 53 bytes

```
$_=NFD$_;s/([oau])\K̈(?=(.?))/max($1,$2)lt a?E:e/gei

```

try it online
> 0 votes

# Answer
# QuadR, 112 bytes

```
[öäüÖÄÜ].?
.̈.?
1(819⌶⍣(2=+/M≠819⌶M))(∊'oauOAU'M)['öäüÖÄÜ'⍳⊃M]'e',⍵p↓1↓M←⍵M

```

Try it online!

*Replace…*

`[öäüÖÄÜ].?` any umlaut'ed character, optionally followed by a character

*… or…*

`.̈.?` any character and a combining umlaut, optionally followed by a character

*… with the result of the following function:*

`⍵M` the **M**atch
`M←` store in `M`
`1↓` drop one character from the left
`⍵p↓` drop one character if match had combing umlaut (`⍵p` is 0-indexed pattern number)
…`'e',` prepend the following character and an **e**:
`(``)[``]` index using:
`⊃M` the first character of the **M**atch
`'öäüÖÄÜ'⍳` …'s index in the list of umlaut'ed characters
… into:
`'oauOAU'M` the two-element list of the de-umlaut'ed characters and the **M**atch
**e**nlisted (flattened)
`1(``)` apply the following derived function with 1 as left argument:
`819⌶⍣(``)` casefold (to uppercase, because left argument would be 1) if:
`819⌶M` the lowercased **M**atch
`M≠` Boolean where the **M**atch differs from that (i.e. is uppercase)
`+/` sum that
`2=` 2 is equal to that

Equivalent to the tacit Dyalog APL function:

```
'[öäüÖÄÜ].?' '.̈.?'⎕R{1(819⌶⍣(2=+/M≠819⌶M))(∊'oauOAU'M)['öäüÖÄÜ'⍳⊃M]'e',⍵.PatternNum↓1↓M←⍵.Match}

```
> 2 votes

---
Tags: code-golf, text-processing
---


title: I'm thinking of a number (Cop's Thread)

text:
# Question
Title: I'm thinking of a number (Cop's Thread)
> Robber's Thread here

In this challenge cops will think of a positive integer. They will then write a program or function that outputs one value when provided the number as input and another value for all other positive integer inputs. Cops will then reveal the program in an answer keeping the number a secret. Robbers can crack an answer by finding the number.

Here's the catch: this is *not* , instead your score will be the secret number with a lower score being better. Obviously you cannot reveal your score while robbers are still trying to find it. An answer that has not been cracked one week after its posting may have its score revealed and be marked safe. Safe answers cannot be cracked.

It probably goes without saying but you should be able to score your answer. That is you should know exactly what value is accepted by your decision machine. Simply knowing that there is one is not enough.

## Use of Cryptographic functions

Unlike most cops and robbers challenge which ask you not to use cryptographic functions, this challenge not only entirely allows them but encourages them. You are free to create answers in any way as long as you are trying to win. That being said, answers using other methods are also welcome here. The goal of the challenge is to win, and as long as you don't cheat nothing is off the table.

# Answer
> 10 votes
# Tampio, Cracked

```
m:n tulos on luvun funktio tulostettuna m:ään, missä luku on x:n kerrottuna kahdella seuraaja, kun x on luku m:stä luettuna
x:n funktio on luku sadalla kerrottuna sadalla salattuna, missä luku on x alempana sadan seuraajaa tai nolla
x:n seuraajan edeltäjä on x
x:n negatiivisena edeltäjä on x:n seuraaja negatiivisena
nollan edeltäjä on yksi negatiivisena
x salattuna y:llä on örkin edeltäjä, missä örkki on x:n seuraajan seuraaja jaettuna y:llä korotettuna kahteen
sata on kiven kolo, missä kivi on kallio katkaistuna maanjäristyksestä
kallio on yhteenlasku sovellettuna mannerlaatan jäseniin ja tulivuoren jäseniin
tulivuori on nolla lisättynä kallioon
mannerlaatta on yksi lisättynä mannerlaattaan
maanjäristys on kallion törmäys
a:n lisättynä b:hen kolo on yhteenlasku kutsuttuna a:lla ja b:n kololla
tyhjyyden kolo on nolla
x:n törmäys on x tutkittuna kahdellatoista, missä kaksitoista on 15 ynnä 6
x ynnä y on y vähennettynä x:stä

```

Run with:

```
python3 suomi.py file.suomi --io

```

The instructions for installing the interpreter are included in the Github page. Please tell if you have any difficulties running this.

> The program in pseudocode. The program performs very slowly because my interpreter is super inefficient. Also, I didn't use any opt-in optimizations available, which can reduce the evaluation time from several minutes to about 10 seconds.

# Answer
> 5 votes
# Perl 6Cracked!

In a strict sense, this isn't an acceptable submission because it doesn't try very hard to win. Instead, it hopes to offer a pleasant puzzle.

It is a "pure math" program which is intended to be cracked by contemplation. I'm sure that you could bruteforce the solution (after cleaning up some sloppy programming I've purposefully committed), but for "full credit" (:--)), you should be able to explain what it does on the math grounds.

```
sub postfix:<!>(Int $n where $n >= 0)
{
	[*] 1 .. $n;
}

sub series($x)
{
	[+] (0 .. 107).map({ (i*($x % (8*π))) ** $_ / $_! });
}

sub prefix:<∫>(Callable $f)
{
	my $n = 87931;
	([+] (0 .. $n).map({
		π/$n * ($_ == 0 || $_ == $n ?? 1 !! 2) * $f(2*π * $_/$n)
	})).round(.01);
}

sub f(Int $in where $in >= 0)
{
	∫ { series($_)**11 / series($in * $_) }
}

```

You are supposed to crack the function f(). (That's the function that takes one natural number and returns one of the two results.) **Warning:** As shown by @Nitrodon, the program actually behaves wrongly and "accepts" an *infinite* number of inputs. Since I have no idea of how to fix it, I just remark for the future solvers that *the number I had in mind is less than 70000*.

If you try to run this in TIO, it **will** time out. This is intentional. (Since it's not supposed to be run at all!)

Finally, I tried to write some reasonably clear code. You should be mostly able to read it fluently even if you're not familiar with the language. Only two remarks: the square brackets \[*op*\] mean reducing ("folding", in Haskell lingo) a list with the operator *op*; and the sub called `postfix:<!>` actually defines a postfix operator named ! (i. e. used like `5!` -- it does exactly what you would expect). Similarly for the `prefix:<∫>` one.

I hope that somebody enjoys this one, but I'm not sure if I got the difficulty right. Feel free to bash me in the comments :—).

Try it online!

# Answer
> 4 votes
# JavaScript, Cracked

I've obfuscated this as much as I can, to the point where it can't fit within this answer.

Try it here! Click Run, then type in console `guess(n)`

Returns undefined if you get the wrong answer, returns true otherwise.

Edit: Somehow I overlooked the part about my score being the number. Oh well, my number is very very big. Good luck solving it anyways.

# Answer
> 3 votes
# Jelly, score: ...1 (cracked)

```
5ȷ2_c⁼“ḍtṚøWoḂRf¦ẓ)ṿẒƓSÑÞ=v7&ðþạẆ®GȯżʠṬƑḋɓḋ⁼Ụ9ḌṢE¹’

```

Try it online!

1Really expected me to reveal it? Come on! Oh well, it has a score of 134. There, I said it!

# Answer
> 3 votes
# Haskell, cracked

This is purely based on arithmetic. Note that `myfun` is the actual function, while `h` is just a helper function.

```
h k = sum $ map (\x -> (x*x)**(-1) - 1/(x**(2-1/(fromIntegral k)))) [1..2*3*3*47*14593]
myfun inp | inp == (last $ filter (\k -> h k < (-7.8015e-5)  )[1..37*333667-1]) = 1
          | otherwise = 0

main = print $ show $ myfun 42 -- replace 42 with your input

```

Try it online!

# Answer
> 3 votes
# Python 2 (cracked)

I wouldn't suggest brute force. Hope you like generators!

```
print~~[all([c[1](c[0](l))==h and c[0](l)[p]==c[0](p^q) for c in [(str,len)] for o in [2] for h in [(o*o*o+o/o)**o] for p,q in [(60,59),(40,44),(19,20),(63,58),(61,53),(12,10),(43,42),(1,3),(35,33),(37,45),(17,18),(32,35),(20,16),(22,30),(45,43),(48,53),(58,59),(79,75),(68,77)]] + [{i+1 for i in f(r[5])}=={j(i) for j in [q[3]] for i in l} for q in [(range,zip,str,int)] for r in [[3,1,4,1,5,9]] for g in [q[1]] for s in [[p(l)[i:i+r[5]] for p in [q[2]] for i in [r[5]*u for f in [q[0]] for u in f(r[5])]]] for l in s + g(*s) + [[z for y in [s[i+a][j:j+r[0]] for g in [q[0]] for a in g(r[0])] for z in y] for k in [[w*r[0] for i in [q[0]] for w in i(r[0])]] for i in k for j in k] for f in [q[0]]]) for l in [int(raw_input())]][0]

```

Try it online!

Outputs `1` for the correct number, `0` otherwise.

# Answer
> 2 votes
# Java, Cracked by Nitrodon

```
import java.math.BigDecimal;

public class Main {
    private static final BigDecimal A = BigDecimal.valueOf(4);
    private static final BigDecimal B = BigDecimal.valueOf(5, 1);
    private static final BigDecimal C = BigDecimal.valueOf(-191222921, 9);
    private static BigDecimal a;
    private static BigDecimal b;
    private static int c;

    private static boolean f(BigDecimal i, BigDecimal j, BigDecimal k, BigDecimal l, BigDecimal m) {
        return i.compareTo(j) == 0 && k.compareTo(l) >= 0 && k.compareTo(m) <= 0;
    }

    private static boolean g(int i, int j, BigDecimal k) {
        c = (c + i) % 4;
        if (j == 0) {
            BigDecimal l = a; BigDecimal m = b;
            switch (c) {
                case 0: a = a.add(k); return f(C, b, B, l, a);
                case 1: b = b.add(k); return f(B, a, C, m, b);
                case 2: a = a.subtract(k); return f(C, b, B, a, l);
                case 3: b = b.subtract(k); return f(B, a, C, b, m);
                default: return false;
            }
        } else {
            --j;
            k = k.divide(A);
            return g(0, j, k) || g(1, j, k) || g(3, j, k) || g(3, j, k) || g(0, j, k) || g(1, j, k) || g(1, j, k) || g(3, j, k);
        }
    }

    private static boolean h(int i) {
        a = BigDecimal.ZERO; b = BigDecimal.ZERO; c = 0;
        return g(0, i, BigDecimal.ONE);
    }

    public static void main(String[] args) {
        int i = Integer.valueOf(args[0]);
        System.out.println(!h(i) && h(i - 1) ? 1 : 0);
    }
}

```

I wanted to try something different than the usual hash and random functions. You can pass the number as a command line argument. Outputs `1` if the correct number is given and `0` otherwise. For small numbers you can also try it online.

**Hint:**

> The main part of the program implements a *variant* of a very well known algorithm. Once you know what it does, you will be able to optimize the given program to calculate the secret number.

**Explanation:**

> This program implements the traversal of the quadratic variant (type 2) of the well known Koch curve (image from Wikipedia):
> The secret number is the first iteration which doesn't pass through the point (B, C). As correctly recognized by Nitrodon, except of the first iteration we can safely ignore the recursion of all parts of the curve, which don't pass through the given point. By changing a line in the original program accordingly, we can check the correct number even in the online interpreter.

# Answer
> 2 votes
# PHP, safe, score:

> 60256

```
<?php

$a = $argv[1];

$b ='0123456789abcdefghijklmnopqrstuvwxyz';

$c = strlen($b);

$d = '';
$e = $a;
while ($e) {
    $d .= $b[$e % $c];
    $e = floor($e / $c);
}

echo ((function_exists($d) && $d($a) === '731f62943ddf6733f493a812fc7aeb7ec07d97b6') ? 1 : 0) . "\n";

```

Outputs 1 if correct, 0 otherwise.

Edit: I don't think anyone even tried to crack this because:

> it would be easy to brute force.

Explanation:

> I take the input and convert it to "base 36", but I don't reverse the remainders to produce the final number. The number 60256 is "1ahs" in base 36. Unreversed, that is "sha1", which is a function in PHP. The final check is that sha1(60256) equals the hash.

# Answer
> 1 votes
# Pyth, Cracked by Erik the Outgolfer*

I tried to obfuscate this as much as possible.

```
hqQl+r@G7hZ@c." y|çEC#nZÙ¦Y;åê½9{ü/ãÑª#¤
ØìjX\"¦Hó¤Ê#§T£®úåâ«B'3£zÞz~Ð£ë"\,a67Cr@G7hZ

```

**Try it here!**

> \*The number was 9.

# Answer
> 1 votes
# Octave, score: ???

It's pretty much guaranteed that no other number will have the exact same 20 random numbers in the end of the list of `1e8` of numbers.

```
function val = cnr(num)
rand("seed", num);
randomints = randi(flintmax-1,1e4,1e4);
val = isequal(randomints(end+(-20:0))(:), ...
 [7918995738984448
  7706857103687680
  1846690847916032
  6527244872712192
  5318889109979136
  7877935851634688
  3899749505695744
  4256732691824640
  2803292404973568
  1410614496854016
  2592550976225280
  4221573015797760
  5165372483305472
  7184095696125952
  6588467484033024
  6670217354674176
  4537379545153536
  3669953454538752
  5365211942879232
  1471052739772416
  5355814017564672](:));
end

```

Outputs `1` for the secret number, `0` otherwise.

I ran this in Octave 4.2.0.

---

*"Sleeps and other slowdowns can be removed when bruteforcing."*

Good luck with that :)

# Answer
> 1 votes
# Ly, score 239, cracked

```
(1014750)1sp[l1+sp1-]28^RrnI24^=u;

```

Try it online!

I'm banking on nobody knowing Ly here, although I know how easily that could change... *sweats*

Explanation:

```
(1014750)1sp[l1+sp1-]              # meaningless code that counts up to 1014750 and discards the result
                     28^Rr         # range from 255 to 0
                          nI       # get the index from the range equal to the input
                            24^=   # check if it's 16
                                u; # print the result

```

# Answer
> 1 votes
# Brain-Flak, score 1574 (cracked)

```
<>(((((((((((((((((((([([(((()()()){}){}){}])]){})))){}{}{}{}()){}){})){}{})){}{})){}((((((((()()){}){}){}){}[()]){}){}){}){}())){})){}){}{}{}){})(((((((((((((((((((()()){}){}()){}){}){}()){}){}()){}){})){}{}())){}{})){}{}){}){}){})(((((((((((((((()()){}()){}()){}){}){}()){}){}){}()){}){}){}()){}()){}()){})<>{({}[()])<>({}({})<({}({})<({}({})<({}({}))>)>)>)<>}({}<>(){[()](<{}>)}<>)

```

Try it online!

# Answer
> 1 votes
# dc

```
#!/bin/dc
[[yes]P] sy [[no]P] sn [ly sp] sq [ln sp] sr [lp ss] st [ln ss] su
?  sa
119560046169484541198922343958138057249252666454948744274520813687698868044973597713429463135512055466078366508770799591124879298416357795802621986464667571278338128259356758545026669650713817588084391470449324204624551285340087267973444310321615325862852648829135607602791474437312218673178016667591286378293
la %
d 0 r 0
=q !=r
10 154 ^ 10 153 ^ +
d la r la
<t !<u
1 la 1 la
>s !>n

```

Try it online!

---

**Note:** This submission has been modified since it was submitted. The original submission (below) was invalid and cracked by Sleafar in the comments below. (An input of `1` gives rise to the output `yes`, but there is one other number that gives the same result.)

```
#!/bin/dc
[[yes]P] sy [[no]P] sn [ly sp] sq [ln sp] sr
?  sa
119560046169484541198922343958138057249252666454948744274520813687698868044973597713429463135512055466078366508770799591124879298416357795802621986464667571278338128259356758545026669650713817588084391470449324204624551285340087267973444310321615325862852648829135607602791474437312218673178016667591286378293
la %
d 0 r 0
=q !=r
10 154 ^ 10 153 ^ +
d la r la
<p !<n

```

Try it online!

# Answer
> 1 votes
# Ruby, safe, score:

> 63105425988599693916

```
#!ruby -lnaF|
if /^#{eval [$F,0]*"**#{~/$/}+"}$/ && $_.to_i.to_s(36)=~/joe|tim/
  p true
else
  p false
end

```

Try it online!

Explanation:

> The first conditional checks the input number for narcissism. The thread I originally wrote for was coincidentally bumped around the same time I posted this, but I guess nobody noticed. The second converts the number to base 36, which uses letters as digits, and checks if the string contains "joe" or "tim". It can be proven (through exhaustion) that there is only one narcissistic number named either Joe or Tim (Joe), because the narcissistic numbers are finite. Proof that they're finite: the result of taking an n-digit number, raising each digit to the nth power, and summing is bounded above by `n*9^n`, while the value of an n-digit number is bounded below by n^10. The ratio between these terms is n\*(9/10)^n, which eventually decreases monotonically as n increases. Once it falls below 1, there can be no n-digit narcissistic numbers.

# Answer
> 0 votes
# Swift 3 (53 bytes) - Cracked

```
func f(n:Int){print(n==1+Int(.pi*123456.0) ?222:212)}

```

How to run this? – `f(n:1)`.

**Test Here.**

# Answer
> 0 votes
# Python 3, score 1 (safe)

Not a very interesting solution, but better a safe cop than a dead cop.

```
import hashlib

def sha(x):
    return hashlib.sha256(x).digest()

x = input().encode()
original = x

for _ in range(1000000000):
    x = sha(x)

print(int(x==b'3\xdf\x11\x81\xd4\xfd\x1b\xab19\xbd\xc0\xc3|Y~}\xea83\xaf\xa5\xb4]\xae\x15wN*!\xbe\xd5' and int(original.decode())<1000))

```

Outputs `1` for the target number, `0` otherwise. Input is taken from stdin. The last part (`and int(original.decode())<1000`) exists only to ensure only one answer, otherwise there would obviously be infinitely many answers.

# Answer
> 0 votes
# TI-BASIC, ~~score: 196164532~~ non-competing

Returns 1 for secret number, 0 otherwise.

```
Ans→rand
rand=1

```

Refer to the note on this page on the `rand` command for more info.

# Answer
> 0 votes
# Java, score: 3141592 (Cracked)

```
\u0070\u0075\u0062\u006c\u0069\u0063\u0020\u0063\u006c\u0061\u0073\u0073\u0020\u004d\u0061\u006e\u0067\u006f\u0020\u007b
\u0073\u0074\u0061\u0074\u0069\u0063\u0020\u0076\u006f\u0069\u0064\u0020\u0063\u006f\u006e\u0076\u0065\u0072\u0074\u0028\u0053\u0074\u0072\u0069\u006e\u0067\u0020\u0073\u0029\u007b\u0066\u006f\u0072\u0028\u0063\u0068\u0061\u0072\u0020\u0063\u0020\u003a\u0020\u0073\u002e\u0074\u006f\u0043\u0068\u0061\u0072\u0041\u0072\u0072\u0061\u0079\u0028\u0029\u0029\u007b\u0020\u0053\u0079\u0073\u0074\u0065\u006d\u002e\u006f\u0075\u0074\u002e\u0070\u0072\u0069\u006e\u0074\u0028\u0022\u005c\u005c\u0075\u0030\u0030\u0022\u002b\u0049\u006e\u0074\u0065\u0067\u0065\u0072\u002e\u0074\u006f\u0048\u0065\u0078\u0053\u0074\u0072\u0069\u006e\u0067\u0028\u0063\u0029\u0029\u003b\u007d\u007d
\u0070\u0075\u0062\u006c\u0069\u0063\u0020\u0073\u0074\u0061\u0074\u0069\u0063\u0020\u0076\u006f\u0069\u0064\u0020\u006d\u0061\u0069\u006e\u0028\u0053\u0074\u0072\u0069\u006e\u0067\u005b\u005d\u0020\u0061\u0072\u0067\u0073\u0029\u0020\u007b\u0069\u006e\u0074\u0020\u0078\u0020\u0020\u003d\u0020\u0049\u006e\u0074\u0065\u0067\u0065\u0072\u002e\u0070\u0061\u0072\u0073\u0065\u0049\u006e\u0074\u0028\u0061\u0072\u0067\u0073\u005b\u0030\u005d\u0029\u003b
\u0064\u006f\u0075\u0062\u006c\u0065\u0020\u0061\u003d\u0020\u0078\u002f\u0038\u002e\u002d\u0033\u0039\u0032\u0036\u0039\u0039\u003b\u0064\u006f\u0075\u0062\u006c\u0065\u0020\u0062\u0020\u003d\u0020\u004d\u0061\u0074\u0068\u002e\u006c\u006f\u0067\u0031\u0030\u0028\u0028\u0069\u006e\u0074\u0029\u0020\u0028\u0078\u002f\u004d\u0061\u0074\u0068\u002e\u0050\u0049\u002b\u0031\u0029\u0029\u002d\u0036\u003b
\u0053\u0079\u0073\u0074\u0065\u006d\u002e\u006f\u0075\u0074\u002e\u0070\u0072\u0069\u006e\u0074\u006c\u006e\u0028\u0028\u0061\u002f\u0062\u003d\u003d\u0061\u002f\u0062\u003f\u0022\u0046\u0061\u0069\u006c\u0022\u003a\u0022\u004f\u004b\u0022\u0020\u0029\u0029\u003b
\u007d\u007d

```

# Answer
> 0 votes
# Java, 164517378918, safe

```
import java.math.*;import java.util.*;
public class T{
    static boolean f(BigInteger i){if(i.compareTo(BigInteger.valueOf(2).pow(38))>0)return false;if(i.longValue()==0)return false;if(i.compareTo(BigInteger.ONE)<0)return false;int j=i.multiply(i).hashCode();for(int k=3^3;k<2000;k+=Math.abs(j%300+1)){j+=1+(short)k+i.hashCode()%(k+1);}return i.remainder(BigInteger.valueOf(5*(125+(i.hashCode()<<11))-7)).equals(BigInteger.valueOf(0));}
    @SuppressWarnings("resource")
    public static void main(String[]a){long l=new Scanner(System.in).nextLong();boolean b=false;for(long j=1;j<10;j++){b|=f(BigInteger.valueOf(l-j));}System.out.println(f(BigInteger.valueOf(l))&&b);}
}

```

# Answer
> 0 votes
# C (gcc), score ???

```
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <wmmintrin.h>

#include <openssl/bio.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>

union State
{
    uint8_t u8[128];
    __m128i i128[8];
} state;

void encrypt()
{
    BIO *key = BIO_new_mem_buf
    (
        "-----BEGIN PUBLIC KEY-----\n"
        "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5CBa50oQ3gOPHNt0TLxp96t+6\n"
        "i2KvOp0CedPHdJ+T/wr/ATo7Rz+K/hzC7kQvsrEcr0Zkx7Ll/0tpFxekEk/9PaDt\n"
        "wyFyEntgz8SGUl4aPJkPCgHuJhFMyUflDTywpke3KkSv3V/VjRosn+yRu5mbA/9G\n"
        "mnOvSVBFn3P2rAOTbwIDAQAB\n"
        "-----END PUBLIC KEY-----\n",
        -1
    );

    RSA *rsa = PEM_read_bio_RSA_PUBKEY(key, &rsa, NULL, NULL);

    uint8_t ciphertext[128];

    RSA_public_encrypt(128, state.u8, ciphertext, rsa, RSA_NO_PADDING);
    memcpy(state.u8, ciphertext, 128);
}

void verify()
{
    if (memcmp
    (
        "\x93\xfd\x38\xf6\x22\xf8\xaa\x2f\x7c\x74\xef\x38\x01\xec\x44\x19"
        "\x76\x56\x27\x7e\xc6\x6d\xe9\xaf\x60\x2e\x68\xc7\x62\xfd\x2a\xd8"
        "\xb7\x3c\xc9\x78\xc9\x0f\x6b\xf0\x7c\xf8\xe5\x3c\x4f\x1c\x39\x6e"
        "\xc8\xa8\x99\x91\x3b\x73\x7a\xb8\x56\xf9\x28\xe7\x2e\xb2\x82\x5c"
        "\xb8\x36\x24\xfb\x26\x96\x32\x91\xe5\xee\x9f\x98\xdf\x44\x49\x7b"
        "\xbc\x6c\xdf\xe9\xe7\xdd\x26\x37\xe5\x3c\xe7\xc0\x2d\x60\xa5\x2e"
        "\xb8\x1f\x7e\xfd\x4f\xe0\x83\x38\x20\x48\x47\x49\x78\x18\xfb\xd8"
        "\x62\xaf\x0a\xfb\x5f\x64\xd1\x3a\xfd\xaf\x4b\xaf\x93\x23\xf4\x36",
        state.u8,
        128
    ))
        exit(0);
}

static inline void quarterround(int offset)
{
    int dest = (offset + 1) % 8, src = offset % 8;

    state.i128[dest] = _mm_aesenc_si128(state.i128[src], state.i128[dest]);
}

int main(int argc, char *argv[])
{
    if (argc != 2)
        exit(0);

    uint64_t input = strtoull(argv[1], NULL, 0);

    state.i128[0] = _mm_set_epi32(0, 0, input >> 32, input);

    for (uint64_t round = 0; round < 0x1p45; round += 2)
    {
        quarterround(0);
        quarterround(2);
        quarterround(4);
        quarterround(6);

        quarterround(7);
        quarterround(1);
        quarterround(3);
        quarterround(5);
    }

    encrypt();
    verify();
    puts("something");
}

```

Since cryptographic solutions are encouraged, here. Exactly one positive integer will print **something**, all others will print nothing. This takes a *long* time, so it cannot be tested online.

# Answer
> 0 votes
# Python 3, score unknown, Cracked by Bubbler

```
def check(x):
    if x < 0 or x >= 5754820589765829850934909 or pow(x, 18446744073709551616, 5754820589765829850934909) != 2093489574700401569580277 or x % 4 != 1:
        return "No way ;-("
    return "Cool B-)"

```

Try it online!

Simple, but may take some time to brute-force ;-) Looking forward to a fast crack ;-)

Footnote: the first two and the last conditions make the answer unique.

BTW how the score is calculated?

Hint 1

> You may expect there will be 264 answers within `0 <= x < [the 25-digit prime]`, but actually there are only 4, and the last condition eliminates the other 3. If you can crack this, then you will also know the other 3 solutions.

# Answer
> 0 votes
# Aceto, safe

```
  P'*o*7-9JxriM'lo7*9Yxx.P',xe*ikCKxlI.D+∑\a€'#o*84/si5s:i»I9Ji8:i+∑€isi.s1+.i2\H/iQxsUxsxxsxiss*i1dJi/3d2*Ji-d*id*IILCh98*2JixM'e9hxBNRb!p

```

Outputs TrueFalse if correct, FalseFalse otherwise

The number was

> 15752963

Try it online!

---
Tags: code-challenge, decision-problem, cops-and-robbers
---


title: In which number set do I belong?

text:
# Question
Title: In which number set do I belong?
# Introduction

Mathematicians often work with number sets. These are groups of numbers that share common properties. These are number sets are, in order from most specific to most broad:

```
Natural numbers   (symbol N): These are the counting numbers: 1, 2, 3, ...
Integers          (symbol Z): These are all the numbers without a fractional part: ..., -3, -2, -1, 0, 1, 2, 3, ...
Rational numbers  (symbol Q): These numbers are the quotients of two integers, such as: 1.1 (11/10), 5.67 (567/100), or 0.333333333... (1/3)
-----The following two numbers sets are equally specific in describing numbers-----
Real numbers      (symbol R): These are positive, zero, and negative numbers, such as: π (3.1415926...), e (2.7182818...), or √2 (1.4142135...)
Imaginary numbers (symbol I): Numbers that give negative values when squared; for this reason they aren't very useful in everyday life.
                              These numbers contain the letter i in them, with i representing the √-1.
                              Examples: 2i, -1.5i 78i, 9i, -3.1415i, i
-----------------------------------------------------------------------------------
Complex numbers   (symbol C): The sum of a real and an imaginary number in the form a + bi, examples: 2 + 7i, 3 + 3i, 1 - i, -8 + i

```

Note that when there is only a single `i`, it is not written `1i`.

# Challenge

Given a number from one of these number sets, print the symbol for the most specific number set that could describe it.

# Test cases

```
Input              Output
73.0            -> N
4/2             -> N
-73             -> Z
-1/3            -> Q
0.56            -> Q
0.555...        -> Q
0.123123123...  -> Q
3.1415926535... -> R
-1.37i          -> I
7892/5 + 23/4i  -> C

```

# Other info

* Natural numbers and integers may be given with a decimal point followed by a string of zeros
* To add on to the previous point, any input that can be converted into a simpler form shall have its output corresponding to the simplified input
* Rational numbers may be given with a `/` to represent a fraction, or a sequence of numbers occurring 3 or more times followed by `...`
* Numbers ending with `...` represent repeated decimals or un-terminated decimal real numbers
* Any number sets less specific than `Q` can also have inputs be given as a fraction
* You do not need to handle repeated decimals or un-terminated decimals for number sets other than Q and R
* Any error caused by lack of precision in floating point numbers will not invalidate a submission

This is code golf, so shortest code wins. If there is something unclear, let me know in the comments' section or edit the question.

# Answer
# JavaScript (ES6), ~~121~~ 110 bytes

```
s=>[...'QRCI'].find((_,i)=>[/(.+)\1\1\.\./,/\.\./,/.+[+-].*i/,/i/][i].test(s))||'QNZ'[k=eval(s),k%1?0:k>0?1:2]

```

### Test cases

```
let f =

s=>[...'QRCI'].find((_,i)=>[/(.+)\1\1\.\./,/\.\./,/.+[+-].*i/,/i/][i].test(s))||'QNZ'[k=eval(s),k%1?0:k>0?1:2]

console.log(f('73.0'           )) // -> N
console.log(f('4/2'            )) // -> N
console.log(f('-73'            )) // -> Z
console.log(f('-1/3'           )) // -> Q
console.log(f('0.56'           )) // -> Q
console.log(f('0.555...'       )) // -> Q
console.log(f('0.123123123...' )) // -> Q
console.log(f('3.1415926535...')) // -> R
console.log(f('-1.37i'         )) // -> I
console.log(f('7892/5 + 23/4i' )) // -> C
```

### Formatted and commented

```
s =>                  // given the input string s
  [...'QRCI'].find(   // we first apply some regular expressions:
    (_, i) => [       //   i = index
      /(.+)\1\1\.\./, //     i = 0 (Q): 3x the same pattern, followed by '..' -> rational
      /\.\./,         //     i = 1 (R): '..' without the repeated pattern -> real
      /.+[+-].*i/,    //     i = 2 (C): a real part +/- an imaginary part -> complex
      /i/             //     i = 3 (I): just an imaginary part -> imaginary
    ][i].test(s)      //   this is a find(), so we exit as soon as something matches
  ) || 'QNZ'[         // if all regular expressions failed:
    k = eval(s),      //   assume the expression can now be safely evaluated as JS code
    k % 1 ?           //   if there's a decimal part:
      0               //     -> rational
    :                 //   else:
      k > 0 ?         //     if strictly positive:
        1             //       -> natural
      :               //     else:
        2             //       -> integer
  ]                   //

```
> 1 votes

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


title: Different ways of defining primes

text:
# Question
Title: Different ways of defining primes
One of my favorite definitions of the prime numbers goes as follows:

* 2 is the smallest prime.
* Numbers larger than 2 are prime if they are not divisible by a smaller prime.

However this definition seems arbitrary, why 2? Why not some other number? Well lets try some other numbers will define n-prime such that

* n is the smallest n-prime.
* Numbers larger than n are n-prime if they are not divisible by a smaller n-prime.

## Task

The task here is to write a program that takes two inputs, a positive integer **n** and a positive integer **a**. It will then decide if **a** is **n**-prime. Your program should output two distinct values one for "yes, it is n-prime" and one for "no, it is not n-prime".

This is a code-golf question so answers will be scored in bytes with less bytes being better.

## Tests

Here are lists of the first 31 primes for n=2 to n=12 (1 is the only 1-prime number)

```
n=2: [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127]
n=3: [3,4,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127]
n=4: [4,5,6,7,9,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113]
n=5: [5,6,7,8,9,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113]
n=6: [6,7,8,9,10,11,13,15,17,19,23,25,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107]
n=7: [7,8,9,10,11,12,13,15,17,19,23,25,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107]
n=8: [8,9,10,11,12,13,14,15,17,19,21,23,25,29,31,35,37,41,43,47,49,53,59,61,67,71,73,79,83,89,97]
n=9: [9,10,11,12,13,14,15,16,17,19,21,23,25,29,31,35,37,41,43,47,49,53,59,61,67,71,73,79,83,89,97]
n=10: [10,11,12,13,14,15,16,17,18,19,21,23,25,27,29,31,35,37,41,43,47,49,53,59,61,67,71,73,79,83,89]
n=11: [11,12,13,14,15,16,17,18,19,20,21,23,25,27,29,31,35,37,41,43,47,49,53,59,61,67,71,73,79,83,89]
n=12: [12,13,14,15,16,17,18,19,20,21,22,23,25,27,29,31,33,35,37,41,43,47,49,53,55,59,61,67,71,73,77]

```

# Answer
> 9 votes
# Haskell, 45 bytes

```
n!a=not$any(n!)[x|x<-[n..a-1],mod a x<1]||n>a

```

Try it online!

I define a nice recursive function `(!)`:

`n!a` checks if any factor of `a`, in the range `[n,a-1]`, is an `n-prime`. Then it negates the result. It also makes sure that `n>a`

# Answer
> 6 votes
# Python 2, ~~39~~ 37 bytes

Thanks to Halvard Hummel for -2 bytes.

```
f=lambda n,i:n==i or i>i%n>0<f(n+1,i)

```

Try it online!

# Answer
> 4 votes
# Python 3, 45 bytes

```
lambda i,k:(i>k)<all(k%r for r in range(i,k))

```

Try it online!

### How it works

This takes two integers as input, **i** and **k**. First checks if **k ≥ i**. Then generates the range **\[i, k)** and for each integer **N** in this range, checks if **N** is coprime to **k**. If both conditions are fulfilled, then **k** is an **i**-prime.

# Answer
> 4 votes
# Husk, ~~6~~ 5 bytes

```
εf≥⁰Ḋ

```

Try it online! or see results up to 80.

Thanks to Leo for -1 byte.

## Explanation

```
εf≥⁰Ḋ  Inputs are n and k.
    Ḋ  Divisors of k.
 f     Keep those that are
  ≥⁰   at least n.
ε      Is the result a one-element list?

```

# Answer
> 4 votes
# , ~~44~~ 37 bytes

```
function(a,n)a==n|a>n&all(a%%n:(a-1))

```

Try it online!

-7 bytes thanks to Giuseppe

Returns `TRUE` if

* `a` is equal to `n` or (`a==n|`)
* `a` is greater than `n` *and* (`a>n&`) for every number *k* from `n` to `a-1`, `a` is not evenly divisible by *k* (`all(a%%n:(a-1))`)

Returns `FALSE` otherwise

# Answer
> 3 votes
# J, 30 bytes

```
>:*(-{1=[:+/0=[:|/~]+i.@[)^:>:

```

Try it online!

Takes starting value as the right argument and the value to check at the left argument.

I messed up originally and didn't account for left arguments less than the starting prime. I'm somewhat unhappy with the length of my solution now.

# Explanation

Let `x` be the left argument (the value to check) and `y` be the right argument (the starting prime).

```
>:*(-{1=[:+/0=[:|/~]+i.@[)^:>:
                          ^:>:  Execute left argument if x >= y
                     i.@[         Create range [0..x]
                   ]+             Add y to it (range now: [y..x+y])
                |/~               Form table of residues
            0=                    Equate each element to 0
          +/                      Sum columns
      1=                          Equate to 1
    -{                            Take the element at position x-y
>:*                             Multiply by result of x >= y

```

### Notes

The element at position `x-y` is the result of primality testing for `x` (since we added `y` to the original range).

Multiplying by `x >: y` ensures that we get a falsey value (`0`) for `x` less than `y`.

# Answer
> 3 votes
# JavaScript (ES6), ~~33~~ ~~32~~ 30 bytes

Takes input in currying syntax `(n)(a)`. Returns a boolean.

```
n=>p=(a,k=a)=>k%--a?p(a,k):a<n

```

### Demo

```
let f =

n=>p=(a,k=a)=>k%--a?p(a,k):a<n

for(n = 2; n <= 12; n++) {
  for(a = n, P = []; P.length < 31; a++) {
    f(n)(a) && P.push(a);
  }
  O.innerText += 'n=' + n + ': ' + P.join(',') + '\n';
}
```

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

# Answer
> 3 votes
# Haskell, 30 bytes

*2 bytes saved thanks to H.PWiz's idea which was borrowed from flawr's answer*

```
n!a=[1]==[1|0<-mod a<$>[n..a]]

```

Try it online!

Ok since its been a while, and the only Haskell answer so far is 45 btyes, I decided to post my own answer.

## Explanation

This function checks that the only number between **n** and **a** that **a** is divisible by is **a** itself.

Now the definition only mentions **n**-primes smaller than **a**, so why are we checking all these extra numbers? Won't we have problems when **a** is divisible by some **n**-composite larger than **n**?

We won't because if there is an **n**-composite larger than **n** it must be divisible by a smaller **n**-prime by definition. Thus if it divides **a** so must the smaller **n**-prime.

If **a** is smaller than **n** `[n..a]` will be `[]` thus cannot equal `[1]` causing the check to fail.

# Answer
> 1 votes
# Jelly, ~~8~~ 5 bytes

```
rḍṛċ<

```

Try it online!

This outputs `0` or `1` for "yes" and a positive integer greater than `1` for "no". This really stretches the "output two distinct values", so I've included a more reasonable 6 byte version:

```
rḍṛṖi<

```

Try it online!

Outputs `0` for "yes, it is \\$n\\$-prime" and a positive integer for "no it is not \\$n\\$-prime". +1 byte to use just `0` and `1`.

## How they work

```
rḍṛċ< - Main link. Takes n on the left and a on the right
r     - Range from n to a inclusive
  ṛ   - Right; Yield a
 ḍ    - For each element in the range, is it divisible by a?
    < - Is n < a?
   ċ  - Count the occurrences of (n < a) in the divisibility range

```

This works because in the range \\$\[n, a\]\\$, only one integer can be divisible by \\$a\\$ if \\$a\\$ is \\$n\\$-prime: \\$a\\$. Therefore, the range, after divisibility, would look like `[0, 0, 0, ..., 1]`. However, this doesn't check the condition that \\$n\\$ is the smallest \\$n\\$-prime, as `r` will generate a descending range if \\$n \< a\\$. Therefore, we check that \\$n \< a\\$ and count the occurrences of that (`1` or `0`) in the divisibility range. If \\$n \> a\\$, there will be more than one `0` in the range, and if \\$a\\$ is not \\$n\\$-prime, but \\$n \< a\\$, there will be more than `1` in the range.

If \\$n = a\\$, then `r` will yield an empty list and `ċ` will return `0`, no matter what the result of `<` is.

```
rḍṛṖi< - Main link. Takes n on the left and a on the right
r      - Range from n to a inclusive
  ṛ    - Right; Yield a
 ḍ     - For each element in the range, is it divisible by a?
   Ṗ   - Remove the final element, 1
     < - Is n < a?
    i  - Index of (n < a) or 0 if not found

```

# Answer
> 1 votes
# Pip, ~~23~~ ~~19~~ 14 bytes

```
b>=a&$&b%(a,b)

```

Shortest method is a port of Mr. Xcoder's Python answer. Takes the smallest prime and the number to test as command-line arguments. Try it online!

# Answer
> 1 votes
# C, 55 bytes

```
f(n,a,i){for(i=a;i-->n;)a%i||f(n,i)&&(i=0);return-1<i;}

```

Try it online!

**53 bytes if multiple truthy return values are allowed:**

```
f(n,a,i){for(i=a;i-->n;)a%i||f(n,i)&&(i=0);return~i;}

```

Try it online!

# Answer
> 1 votes
# dc, ~~40~~ ~~34~~ 37 bytes

```
[0p3Q]sf?se[dler%0=f1+dle>u]sudle>u1p

```

I would have included a TIO link, but TIO seems to be carrying a faulty distribution of `dc` seeing as how this works as intended on my system but the `Q` command functions erroneously on TIO. Instead, here is a link to a `bash` testing ground with a correctly functioning version of `dc`:

Demo It!

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

```
{⍵∊o/⍨1=+/¨0=o|⍨⊂o←⍺↓⍳⍵}

```

Try it online!

**How?**

`⍳⍵` \- `1` to `a`

`o←⍺↓` \- `n` to `a`, save to `o`

`o|⍨⊂o` \- modulo every item in `o` with every item in `o`

`0=` \- check where it equals `0` (divides)

`+/¨` \- sum the number of divisions

`1=` \- if we have only one then the number is only divided by itself

`o/⍨` \- so we keep these occurences

`⍵∊` \- is `a` in that residual array?

# Answer
> 0 votes
# Add++, 20 bytes

```
L,2Dx@rBcB%B]b*!!A>*

```

Try it online!

```
L,   - Create a lambda function
     - Example arguments:  [5 9]
  2D - Copy below; STACK = [5 9 5]
  x  - Repeat;     STACK = [5 9 [9 9 9 9 9]]
  @  - Reverse;    STACK = [[9 9 9 9 9] 5 19]
  r  - Range;      STACK = [[9 9 9 9 9] [5 6 7 8 9]]
  Bc - Zip;        STACK = [[9 5] [9 6] [9 7] [9 8] [9 9]]
  B% - Modulo;     STACK = [4 3 2 1]
  B] - Wrap;       STACK = [[4 3 2 1]]
  b* - Product;    STACK = [24]
  !! - Boolean;    STACK = [1]
  A  - Arguments;  STACK = [1 5 9]
  >  - Greater;    STACK = [1 1]
  *  - Product;    STACK = [1]

```

# Answer
> 0 votes
# JavaScript (Node.js), 27 bytes

```
i=>f=n=>i==n||i>i%n&&f(n+1)

```

Try it online!

Port of my Python answer, takes input in currying syntax: `m(number)(first prime)`

# Answer
> 0 votes
# JavaScript ES5, 34 Bytes

```
for(a=i=(p=prompt)();a%--i;);i<p()

```

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


title: Where does the pivot belong?

text:
# Question
Title: Where does the pivot belong?
You will be given a positive integer as input.

The integer is the board of a seesaw.

Th integer will not have leading zeroes. You may take this input however you like.

Your task is to output the location of the pivot point of this seesaw, such that the board would balance.

A board balances if the moments on each side are equal in magnitude. A moment is calculated by multiplying the force by the distance from the pivot point. In this case, the force is equal to the digit.

For the integer `100` with a pivot point below the first `0`, the moment on the left is 1x1=1. The moment on the right is 0x1=0. If the pivot point was below the second `0`, the moment on the left would be 2x1=2 (because the `1` is now 2 away from the pivot).

For example, for the integer `31532` the pivot goes underneath the number 5. This is because the moments on the left are 3x2 + 1x1 = 7 and on the right the moments are 3x1 + 2x2 = 7.

The output for this integer is `3` because the pivot goes underneath the 3rd digit.

If the integer cannot be balanced, your code does not have to do anything - it can hang, error, output nothing - whatever you want.

Note that a pivot cannot go between two numbers. The pivot location must be an integer.

## Test cases:

```
31532 -> 3
101 -> 2
231592 -> 4
8900311672 -> 5

```

Standard loopholes apply, this is code golf so shortest answer wins.

# Answer
> 5 votes
# Haskell, ~~64~~ ~~62~~ ~~59~~ ~~57~~ ~~45~~ ~~35~~ 31 bytes

```
d l=sum(zipWith(*)[1..]l)/sum l

```

Try it online!

# Answer
> 4 votes
# , 66 bytes

```
sum(1:length(n<-strtoi(strsplit(paste(scan()),"")[[1]]))*n)/sum(n)

```

Try it online!

# Answer
> 3 votes
# Jelly, 7 bytes

```
Dµæ.J:S

```

Try it online! or verify all inputs at once.

# Answer
> 3 votes
# , 29 bytes

```
[:>:@(+/%~]+/@:*i.@$)10#.inv]

```

Try it online!

# Answer
> 3 votes
# Brain-Flak, 64 bytes

```
({({}[((((()()()){}){}){}){}]<>{})<>}<>)({()<({}[({})])>}<>)

```

Try it online!

60+4 bytes for the `-ar` flags.

### Explanation

```
 {                                  }     for each digit in input (starting at the end)
   {}                                     get digit as ASCII code
     [((((()()()){}){}){}){}]             subtract 48 to get digit as number
  (                          <>{})<>      add to cumulative sum on second stack
(                                    <>)  push total of all cumulative sums (the sum of moments)

 {              }       while sum of moments != 0
     ({}[({})])         subtract sum of weights
  ()<          >        count the number of iterations needed
(                <>)    push onto first stack and implicitly output

```

# Answer
> 2 votes
# Python 3, 66 bytes

```
f=lambda n,a=0,b=0,c=1:n and f(n//10,a+n%10*c,b+n%10,c+1)or c-a//b

```

Try it online!

# Answer
> 2 votes
# Brachylog, 14 bytes

```
ẹ⟨{iᶠ×ᵐ+}÷+⟩+₁

```

Try it online!

# Answer
> 2 votes
## GolfScript (24 bytes)

```
0:i.@{15&.@+@@i):i*+\}//

```

Online demo

# Answer
> 1 votes
# Python 3, 69 bytes

```
x=[*map(int,input())]
print(sum(v*k for k,v in enumerate(x))//sum(x))

```

Try it online!

-7 bytes and fixed thanks to ovs

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

```
a,b,c;f(long n){a=b=c=0;for(;n;a+=n%10*++c,n/=10)b+=n%10;return-~c-a/b;}

```

Try it online!

# Answer
> 1 votes
# MATL, 12 bytes

```
48-ttn:*sws/

```

Try it online!

# Answer
> 1 votes
# Mathematica, 42 bytes

```
Range@Length@#.#/Total@#&@IntegerDigits@#&

```

Try it online! (Mathics)

# Answer
> 0 votes
# Pyth, 14 bytes

```
h/s.e*bkJjQTsJ

```

Test suite.

# Answer
> 0 votes
# Actually, 10 bytes

```
♂≡;Σ@;r*\u

```

Try it online!

# Answer
> 0 votes
# Cheddar, 63 bytes

```
n->(a->a.map((x,y)->x*y).sum/a.sum+1)(("%d"%n).bytes=>((-)&48))

```

Try it online!

# Answer
> 0 votes
# Python 2, ~~132 134 126~~ 112 bytes

* Thanks @ovs for 14 bytes.

```
n,m=map(int,input()),0
z=lambda a,b:sum(n[j]*abs(m-j)for j in range(a,b))
while z(0,m)<z(m,len(n)):m+=1
print-~m

```

Try it online!

# Answer
> 0 votes
# Retina, 43 bytes

```
$
;$`
(?=(.*);)
$1
\d
$*
^(1+)(\1)*;\1$
$#2

```

Try it online!

# Answer
> 0 votes
# Java (OpenJDK 8), 80 bytes

```
int f(long n){int a=0,b=0,c=0;for(;n>0;a+=n%10*++c,n/=10)b+=n%10;return-~c-a/b;}

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 10 bytes

```
TвÐgL*OsO÷

```

Try it online!

# Answer
> 0 votes
# GolfScript, 33 bytes

```
{48-}%.[.,,]zip{{*}*}%{+}*\{+}*/)

```

Try it online!

# Answer
> 0 votes
# Retina, 30 bytes

```

$'¶
1>`¶

.
$*
(1+)¶(\1)+
$#2

```

Try it online! Link includes test cases. Explanation: The first stage sneakily creates newline-delimited duplicates of all the suffixes of the original string. This means that the each digit appears after the first newline the number of times according to how far away it is from the left, effectively multiplying to give its moment. The second stage deletes all the newlines after the first, completing the calculation of the moments. The third stage converts the digits to unary, summing them, and the fourth stage divides the sums (exact division is assumed to apply here).

# Answer
> 0 votes
# , 29 bytes

```
(0 i.~]+/ .*[:-/~#\)@(,.&.":)

```

J executes verbs right-to-left, so let's start at the end and work our way towards the beginning.

**Explanation**

```
         ,.&.":      NB. Explode integer into digits
         #\          NB. 0 .. N-1, where N=number of digits
         -/~         NB. Distance table, one row per digit
         ] +/ .* …   NB. Forces at each pivot (F=digit * distance)
         0 i.~ …     NB. Digit index where F=0

```

Note that J is an index-origin 0 language, so it would be more natural and idiomatic for the answer to 8900311672 to be 4 rather than 5, for 231592 to be 3 rather than 4, etc, and so that's the way this function is written.

But if the index-origin 1 is required for output, then add `1+` before `0 i.~` and add 2 bytes to the score, bringing it up from 29 to 31.

# Answer
> 0 votes
# Python 3, 127 bytes

I am a newbie golfer. All suggestions and tips are greatly apreciated :).

```
lambda x:min([(abs(eval("+".join(list(x[:i+1])))-eval("+".join(list(x[i:])))),i+1)for i in range(len(x))],key=lambda x:x[0])[1]

```

Try it Online!

# Answer
> 0 votes
# C# (.NET Core), 84 bytes

```
a=>{int p=0,q=0,i=1;for(;i<=a.Length;p+=a[i-1],q+=i*a[i++-1]);return q/(q%p>0?0:p);}

```

Try it online!

Takes in an array of single digits as the 'integer' input. Uses the image moments approach for finding the centre of mass. Throws a divide by zero if the seesaw is unbalanced.

### DeGolfed

```
a=>{
    int p=0, // used to store the image moment of order 0
        q=0, // used to store the image moment of order 1
        i=1; // array index, offset to 1 as 1 based indexing is required

    for (; i <= a.Length; // go through the array
        p += a[i-1],      // getting the order 0 image moment value
        q += i*a[i++-1]); //     and the order 1 image moment value

    // q / p is the centre of mass, but as an exact integer pivot is required,
    // if q is not evenly divisible by p,
    // then throw a divide by zero error.
    // otherwise return q / p
    return q / ( q % p > 0? 0 : p);
}

```

---
Tags: code-golf, number
---


title: Same code different characters

text:
# Question
Title: Same code different characters
*Note: This challenge only allows answers in compiled languages*

## Task

Your task is pretty simple, make two different programs that when compiled result in the same output.

## Scoring

Here is where the fun comes in. Your score will be the number of unique **bytes** present in exactly one program. For example if your two programs (encoded in IBM Code page 437) are

```
☻☻Program A

```

and

```
☺Program B

```

The characters that are in exactly one program are

```
☻☺AB

```

Thus the score is 4. Note that  appears twice in the first program but is only counted once.

Your goal is to get the highest score, the highest score possible is 256.

Here is a scoring program that works for ASCII encoded programs.

## Stipulations

* Every byte in both programs should be able to be replaced with a different byte causing either the program to compile into a different result or fail to compile all together. Removing any byte should do the same.
* You may use any compilation flags as long as both programs are run with the same flags.
* The resulting compilation should be static (i.e. should not vary from run to run), if results vary from machine to machine indicate the machine it is intended to run on.
* The output of compilation should be byte for byte identical not "equivalent" or "similar enough".
* The output of the compilation should be non-empty
* Warnings/Errors need not be the same between compilations
* If either the programs or the compilation include unprintable characters be sure to include a hexdump. Although it is not technically required.

# Answer
# Perl, score 254 + 2 = 256

Here's a hex dump of one program:

```
00000000: 6c65 6e67 7468 2700 0102 0304 0506 0708  length'.........
00000010: 090a 0b0c 0d0e 0f10 1112 1314 1516 1718  ................
00000020: 191a 1b1c 1d1e 1f20 2123 2425 2628 292a  ....... !#$%&()*
00000030: 2b2c 2d2e 2f30 3132 3334 3536 3738 393a  +,-./0123456789:
00000040: 3b3c 3d3e 3f40 4142 4344 4546 4748 494a  ;<=>?@ABCDEFGHIJ
00000050: 4b4c 4d4e 4f50 5152 5354 5556 5758 595a  KLMNOPQRSTUVWXYZ
00000060: 5b5d 5e5f 6061 6263 6465 6667 6869 6a6b  []^_`abcdefghijk
00000070: 6c6d 6e6f 7071 7273 7475 7677 7879 7a7b  lmnopqrstuvwxyz{
00000080: 7c7d 7e7f 8081 8283 8485 8687 8889 8a8b  |}~.............
00000090: 8c8d 8e8f 9091 9293 9495 9697 9899 9a9b  ................
000000a0: 9c9d 9e9f a0a1 a2a3 a4a5 a6a7 a8a9 aaab  ................
000000b0: acad aeaf b0b1 b2b3 b4b5 b6b7 b8b9 babb  ................
000000c0: bcbd bebf c0c1 c2c3 c4c5 c6c7 c8c9 cacb  ................
000000d0: cccd cecf d0d1 d2d3 d4d5 d6d7 d8d9 dadb  ................
000000e0: dcdd dedf e0e1 e2e3 e4e5 e6e7 e8e9 eaeb  ................
000000f0: eced eeef f0f1 f2f3 f4f5 f6f7 f8f9 fafb  ................
00000100: fcfd feff 273d 3d32 3533 6f72 2078 2829  ....'==253or x()

```

and here's the other program:

```
"\\"

```

Perl isn't normally thought of a compiled language, but it is; it's first compiled to bytecode, and then the bytecode is executed. You can apply a filter on the bytecode (e.g. to dump it rather than running the program) using the `-MO` option. Both these programs compile into the following bytecode (disassembled using `-MO=Terse`):

```
LISTOP (0x564fcd99f020) leave [1]
    OP (0x564fcd99f148) enter
    COP (0x564fcd99f068) nextstate
    OP (0x564fcd99f100) null [5]

```

## Explanation

Perl replaces all statements with no effect (such as string literals on their own) with a hardcoded "statement with no effect" statement in the resulting bytecode, so both programs compile to the same thing. In terms of character replacements, replacing most of the characters from program 1 with apostrophes will cause it to fail to compile (or replacing the apostrophes with `0`). In program 2, replacing the any character with `c` will cause the program to fail to compile (as `\c` takes an argument).

As for character deletions, the first version of this answer predated the "radiation hardening rule" (that deleting any character must change the behaviour of the program). This updated, radiation-hardened version works via the use of a checksum; if deleting a character doesn't outright cause a syntax error, the code will compile into a call to the nonexistent function `x`. The Perl compiler doesn't optimize out the call in the case where it's made (and in general doesn't seem aware that the function doesn't exist), and thus the output is different. However, Perl's constant folder is capable of seeing that the un-mutated program is a single statement with no effect, and thus optimizes the whole thing down into a single statement like before.

I originally misread the question as counting only unique characters from one program, and tried to optimize for that. Clearly, program 2 needs to contain at least one character in order to generate the "statement with no effect" opcode, meaning that the best possible score in one program is 255. I haven't yet found a way to include a backslash in program 1 in such a way that the character immediately following it can't be replaced in such a way as to cause the program to break, but it wouldn't surprise me if it were possible (leading to a score of 255 + 1 = 256).
> 19 votes

# Answer
# C, 231

### Program A

```
i[]={'','','','','','','',','   ','
                                       ','
                                          ','','','','','','','','','','','','','','','','','','',' ','!','"','#','$','%','&','\'','(',')','*','+',',','-','.','/','0','1','2','3','4','5','6','7','8','9',':',';','<','=','>','?','@','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','[','\\',']','^','_','`','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','{','|','}','~','','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�','�'};main(){}

```

Lots of unprintables above. Here's the xxd hexdump:

```
00000000: 695b 5d3d 7b27 0127 2c27 0227 2c27 0327  i[]={'.','.','.'
00000010: 2c27 0427 2c27 0527 2c27 0627 2c27 0727  ,'.','.','.','.'
00000020: 2c27 0827 2c27 0927 2c27 0b27 2c27 0c27  ,'.','.','.','.'
00000030: 2c27 0e27 2c27 0f27 2c27 1027 2c27 1127  ,'.','.','.','.'
00000040: 2c27 1227 2c27 1327 2c27 1427 2c27 1527  ,'.','.','.','.'
00000050: 2c27 1627 2c27 1727 2c27 1827 2c27 1927  ,'.','.','.','.'
00000060: 2c27 1a27 2c27 1b27 2c27 1c27 2c27 1d27  ,'.','.','.','.'
00000070: 2c27 1e27 2c27 1f27 2c27 2027 2c27 2127  ,'.','.',' ','!'
00000080: 2c27 2227 2c27 2327 2c27 2427 2c27 2527  ,'"','#','$','%'
00000090: 2c27 2627 2c27 5c27 272c 2728 272c 2729  ,'&','\'','(',')
000000a0: 272c 272a 272c 272b 272c 272c 272c 272d  ','*','+',',','-
000000b0: 272c 272e 272c 272f 272c 2730 272c 2731  ','.','/','0','1
000000c0: 272c 2732 272c 2733 272c 2734 272c 2735  ','2','3','4','5
000000d0: 272c 2736 272c 2737 272c 2738 272c 2739  ','6','7','8','9
000000e0: 272c 273a 272c 273b 272c 273c 272c 273d  ',':',';','<','=
000000f0: 272c 273e 272c 273f 272c 2740 272c 2741  ','>','?','@','A
00000100: 272c 2742 272c 2743 272c 2744 272c 2745  ','B','C','D','E
00000110: 272c 2746 272c 2747 272c 2748 272c 2749  ','F','G','H','I
00000120: 272c 274a 272c 274b 272c 274c 272c 274d  ','J','K','L','M
00000130: 272c 274e 272c 274f 272c 2750 272c 2751  ','N','O','P','Q
00000140: 272c 2752 272c 2753 272c 2754 272c 2755  ','R','S','T','U
00000150: 272c 2756 272c 2757 272c 2758 272c 2759  ','V','W','X','Y
00000160: 272c 275a 272c 275b 272c 275c 5c27 2c27  ','Z','[','\\','
00000170: 5d27 2c27 5e27 2c27 5f27 2c27 6027 2c27  ]','^','_','`','
00000180: 6127 2c27 6227 2c27 6327 2c27 6427 2c27  a','b','c','d','
00000190: 6527 2c27 6627 2c27 6727 2c27 6827 2c27  e','f','g','h','
000001a0: 6927 2c27 6a27 2c27 6b27 2c27 6c27 2c27  i','j','k','l','
000001b0: 6d27 2c27 6e27 2c27 6f27 2c27 7027 2c27  m','n','o','p','
000001c0: 7127 2c27 7227 2c27 7327 2c27 7427 2c27  q','r','s','t','
000001d0: 7527 2c27 7627 2c27 7727 2c27 7827 2c27  u','v','w','x','
000001e0: 7927 2c27 7a27 2c27 7b27 2c27 7c27 2c27  y','z','{','|','
000001f0: 7d27 2c27 7e27 2c27 7f27 2c27 8027 2c27  }','~','.','.','
00000200: 8127 2c27 8227 2c27 8327 2c27 8427 2c27  .','.','.','.','
00000210: 8527 2c27 8627 2c27 8727 2c27 8827 2c27  .','.','.','.','
00000220: 8927 2c27 8a27 2c27 8b27 2c27 8c27 2c27  .','.','.','.','
00000230: 8d27 2c27 8e27 2c27 8f27 2c27 9027 2c27  .','.','.','.','
00000240: 9127 2c27 9227 2c27 9327 2c27 9427 2c27  .','.','.','.','
00000250: 9527 2c27 9627 2c27 9727 2c27 9827 2c27  .','.','.','.','
00000260: 9927 2c27 9a27 2c27 9b27 2c27 9c27 2c27  .','.','.','.','
00000270: 9d27 2c27 9e27 2c27 9f27 2c27 a027 2c27  .','.','.','.','
00000280: a127 2c27 a227 2c27 a327 2c27 a427 2c27  .','.','.','.','
00000290: a527 2c27 a627 2c27 a727 2c27 a827 2c27  .','.','.','.','
000002a0: a927 2c27 aa27 2c27 ab27 2c27 ac27 2c27  .','.','.','.','
000002b0: ad27 2c27 ae27 2c27 af27 2c27 b027 2c27  .','.','.','.','
000002c0: b127 2c27 b227 2c27 b327 2c27 b427 2c27  .','.','.','.','
000002d0: b527 2c27 b627 2c27 b727 2c27 b827 2c27  .','.','.','.','
000002e0: b927 2c27 ba27 2c27 bb27 2c27 bc27 2c27  .','.','.','.','
000002f0: bd27 2c27 be27 2c27 bf27 2c27 c027 2c27  .','.','.','.','
00000300: c127 2c27 c227 2c27 c327 2c27 c427 2c27  .','.','.','.','
00000310: c527 2c27 c627 2c27 c727 2c27 c827 2c27  .','.','.','.','
00000320: c927 2c27 ca27 2c27 cb27 2c27 cc27 2c27  .','.','.','.','
00000330: cd27 2c27 ce27 2c27 cf27 2c27 d027 2c27  .','.','.','.','
00000340: d127 2c27 d227 2c27 d327 2c27 d427 2c27  .','.','.','.','
00000350: d527 2c27 d627 2c27 d727 2c27 d827 2c27  .','.','.','.','
00000360: d927 2c27 da27 2c27 db27 2c27 dc27 2c27  .','.','.','.','
00000370: dd27 2c27 de27 2c27 df27 2c27 e027 2c27  .','.','.','.','
00000380: e127 2c27 e227 2c27 e327 2c27 e427 2c27  .','.','.','.','
00000390: e527 2c27 e627 2c27 e727 2c27 e827 2c27  .','.','.','.','
000003a0: e927 2c27 ea27 2c27 eb27 2c27 ec27 2c27  .','.','.','.','
000003b0: ed27 2c27 ee27 2c27 ef27 2c27 f027 2c27  .','.','.','.','
000003c0: f127 2c27 f227 2c27 f327 2c27 f427 2c27  .','.','.','.','
000003d0: f527 2c27 f627 2c27 f727 2c27 f827 2c27  .','.','.','.','
000003e0: f927 2c27 fa27 2c27 fb27 2c27 fc27 2c27  .','.','.','.','
000003f0: fd27 2c27 fe27 2c27 ff27 7d3b 6d61 696e  .','.','.'};main
00000400: 2829 7b7d 0a                             (){}.

```

### Program B

```
i[]={1,2,3,4,5,6,7,010,011,013,014,016,017,020,021,022,023,024,025,026,027,030,031,032,033,034,035,036,037,040,041,042,043,044,045,046,047,050,051,052,053,054,055,056,057,060,061,062,063,064,065,066,067,070,071,072,073,074,075,076,077,0100,0101,0102,0103,0104,0105,0106,0107,0110,0111,0112,0113,0114,0115,0116,0117,0120,0121,0122,0123,0124,0125,0126,0127,0130,0131,0132,0133,0134,0135,0136,0137,0140,0141,0142,0143,0144,0145,0146,0147,0150,0151,0152,0153,0154,0155,0156,0157,0160,0161,0162,0163,0164,0165,0166,0167,0170,0171,0172,0173,0174,0175,0176,0177,-0200,-0177,-0176,-0175,-0174,-0173,-0172,-0171,-0170,-0167,-0166,-0165,-0164,-0163,-0162,-0161,-0160,-0157,-0156,-0155,-0154,-0153,-0152,-0151,-0150,-0147,-0146,-0145,-0144,-0143,-0142,-0141,-0140,-0137,-0136,-0135,-0134,-0133,-0132,-0131,-0130,-0127,-0126,-0125,-0124,-0123,-0122,-0121,-0120,-0117,-0116,-0115,-0114,-0113,-0112,-0111,-0110,-0107,-0106,-0105,-0104,-0103,-0102,-0101,-0100,-077,-076,-075,-074,-073,-072,-071,-070,-067,-066,-065,-064,-063,-062,-061,-060,-057,-056,-055,-054,-053,-052,-051,-050,-047,-046,-045,-044,-043,-042,-041,-040,-037,-036,-035,-034,-033,-032,-031,-030,-027,-026,-025,-024,-023,-022,-021,-020,-017,-016,-015,-014,-013,-012,-011,-010,-7,-6,-5,-4,-3,-2,-1};main(){}

```

These compile to precisely the same object code. GCC embeds the filename in the object code, so you'll need to give the files the same name (in different directories).

I was worried that the fact that there are no references to `i` might cause the compiler to optimize this variable out completely, but I think that making it a global guarantees that it will be present in the object. This may be verified by inspection of the generated assembly:

```
    .file   "diffchar.c"
    .globl  i
    .data
    .align 32
    .type   i, @object
    .size   i, 1012
i:
    .long   1
    .long   2
    .long   3
    .long   4
    .long   5
    .long   6
    .long   7
    .long   8
    .long   9
    .long   11
    .long   12
    .long   14
    .long   15
    .long   16
    .long   17
    .long   18
    .long   19
    .long   20
    .long   21
    .long   22
    .long   23
    .long   24
    .long   25
    .long   26
    .long   27
    .long   28
    .long   29
    .long   30
    .long   31
    .long   32
    .long   33
    .long   34
    .long   35
    .long   36
    .long   37
    .long   38
    .long   39
    .long   40
    .long   41
    .long   42
    .long   43
    .long   44
    .long   45
    .long   46
    .long   47
    .long   48
    .long   49
    .long   50
    .long   51
    .long   52
    .long   53
    .long   54
    .long   55
    .long   56
    .long   57
    .long   58
    .long   59
    .long   60
    .long   61
    .long   62
    .long   63
    .long   64
    .long   65
    .long   66
    .long   67
    .long   68
    .long   69
    .long   70
    .long   71
    .long   72
    .long   73
    .long   74
    .long   75
    .long   76
    .long   77
    .long   78
    .long   79
    .long   80
    .long   81
    .long   82
    .long   83
    .long   84
    .long   85
    .long   86
    .long   87
    .long   88
    .long   89
    .long   90
    .long   91
    .long   92
    .long   93
    .long   94
    .long   95
    .long   96
    .long   97
    .long   98
    .long   99
    .long   100
    .long   101
    .long   102
    .long   103
    .long   104
    .long   105
    .long   106
    .long   107
    .long   108
    .long   109
    .long   110
    .long   111
    .long   112
    .long   113
    .long   114
    .long   115
    .long   116
    .long   117
    .long   118
    .long   119
    .long   120
    .long   121
    .long   122
    .long   123
    .long   124
    .long   125
    .long   126
    .long   127
    .long   -128
    .long   -127
    .long   -126
    .long   -125
    .long   -124
    .long   -123
    .long   -122
    .long   -121
    .long   -120
    .long   -119
    .long   -118
    .long   -117
    .long   -116
    .long   -115
    .long   -114
    .long   -113
    .long   -112
    .long   -111
    .long   -110
    .long   -109
    .long   -108
    .long   -107
    .long   -106
    .long   -105
    .long   -104
    .long   -103
    .long   -102
    .long   -101
    .long   -100
    .long   -99
    .long   -98
    .long   -97
    .long   -96
    .long   -95
    .long   -94
    .long   -93
    .long   -92
    .long   -91
    .long   -90
    .long   -89
    .long   -88
    .long   -87
    .long   -86
    .long   -85
    .long   -84
    .long   -83
    .long   -82
    .long   -81
    .long   -80
    .long   -79
    .long   -78
    .long   -77
    .long   -76
    .long   -75
    .long   -74
    .long   -73
    .long   -72
    .long   -71
    .long   -70
    .long   -69
    .long   -68
    .long   -67
    .long   -66
    .long   -65
    .long   -64
    .long   -63
    .long   -62
    .long   -61
    .long   -60
    .long   -59
    .long   -58
    .long   -57
    .long   -56
    .long   -55
    .long   -54
    .long   -53
    .long   -52
    .long   -51
    .long   -50
    .long   -49
    .long   -48
    .long   -47
    .long   -46
    .long   -45
    .long   -44
    .long   -43
    .long   -42
    .long   -41
    .long   -40
    .long   -39
    .long   -38
    .long   -37
    .long   -36
    .long   -35
    .long   -34
    .long   -33
    .long   -32
    .long   -31
    .long   -30
    .long   -29
    .long   -28
    .long   -27
    .long   -26
    .long   -25
    .long   -24
    .long   -23
    .long   -22
    .long   -21
    .long   -20
    .long   -19
    .long   -18
    .long   -17
    .long   -16
    .long   -15
    .long   -14
    .long   -13
    .long   -12
    .long   -11
    .long   -10
    .long   -9
    .long   -8
    .long   -7
    .long   -6
    .long   -5
    .long   -4
    .long   -3
    .long   -2
    .long   -1
    .text
    .globl  main
    .type   main, @function
main:
.LFB0:
    .cfi_startproc
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    movl    $0, %eax
    popq    %rbp
    .cfi_def_cfa 7, 8
    ret
    .cfi_endproc
.LFE0:
    .size   main, .-main
    .ident  "GCC: (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609"
    .section    .note.GNU-stack,"",@progbits

```

Note that in program B, (most of) the char values are given in octal. They could have also been given in decimal, but by using octal, we gain a couple of extra characters - `8` and `9` \- in the difference set.

GCC doesn't seem to like CR, LF and (for obvious reasons) NUL characters inside of single quotes `''`.

Try it online and score.
> 16 votes

# Answer
# Python, score ~~16~~ ~~26~~ ~~27~~ 28

Unique Characters: `-+;132547698<ACBEDFOXabopsx|`

Calculate the score

### Program 1:

```
def y():
 if 0: 0xBCAFD0|0XE|(0o4<<0O4)|48;

 return 0

```

In program 1, there are 5 spaces in the seemingly blank line.

### Program 2:

```
def y():
 if 0:return--12365790+(0b1110000)
 pass
 return 0

```

Some help was found with the peephole optimiser source code.

Tested with this helper script: Try it online!
> 5 votes

# Answer
# Python 3.6, ~~2 3 5~~ 6

Program 1:

```
z=11_11;a=41_68;y=None;x=5_2_7_9;x*x

```

Program 2:

```
z=1111;a=4168;y=None;x=1111+4168;x*x

```

Python isn't normally compiled, but it does compile its source code into pyc files. Crucially, such compiling includes an optimization pass which changes "1111+4168" into 5279. The underscores serve two purposes: one of them is to add one to the score, and the other is the keep the length, which is stored in the pyc header the same. All of the variable assignments other than 'x' are to keep the `co_consts` in the right order. The `x*x` at the end serves to keep the `co_stacksize` the same.
> 3 votes

# Answer
# FASM, 254

```
00000000h: 64 62 20 27 01 02 03 04 05 06 07 08 0B 0C 0E 0F ; db '............
00000010h: 10 11 12 13 14 15 16 17 18 19 1B 1C 1D 1E 1F 21 ; ...............!
00000020h: 22 23 24 25 26 28 29 2A 2B 2D 2E 2F 3A 3B 3C 3D ; "#$%&()*+-./:;<=
00000030h: 3E 3F 40 41 43 45 46 47 48 49 4A 4B 4C 4D 4E 4F ; >?@ACEFGHIJKLMNO
00000040h: 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F ; PQRSTUVWXYZ[\]^_
00000050h: 60 61 63 65 66 67 68 69 6A 6B 6C 6D 6E 6F 70 71 ; `acefghijklmnopq
00000060h: 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F 80 81 ;
00000070h: 82 83 84 85 86 87 88 89 8A 8B 8C 8D 8E 8F 90 91 ;
00000080h: 92 93 94 95 96 97 98 99 9A 9B 9C 9D 9E 9F A0 A1 ;
00000090h: A2 A3 A4 A5 A6 A7 A8 A9 AA AB AC AD AE AF B0 B1 ;
000000a0h: B2 B3 B4 B5 B6 B7 B8 B9 BA BB BC BD BE BF C0 C1 ;
000000b0h: C2 C3 C4 C5 C6 C7 C8 C9 CA CB CC CD CE CF D0 D1 ;
000000c0h: D2 D3 D4 D5 D6 D7 D8 D9 DA DB DC DD DE DF E0 E1 ;
000000d0h: E2 E3 E4 E5 E6 E7 E8 E9 EA EB EC ED EE EF F0 27 ;
000000e0h: 0D 64 62 20 27 F1 F2 F3 F4 F5 F6 F7 F8 F9 FA FB ;
000000f0h: FC FD FE FF 27                                  ;

DB  1,2,3,4,5,6,7,8,11,12,14,15,16,17,18,19,20,21,22,23,24,25,27,28,29,30,31,33,34,35,36,37,38,40,41,42,43,45,46,47,58,59,60,61,62,63,64,65,67,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,99,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251
DB  252,253,254,255

```

no 0x00 and 0x1A because fasm doesn't support the two symbols
> 1 votes

---
Tags: code-challenge, code-bowling, radiation-hardening, compiler
---


title: Prove me wrong!

text:
# Question
Title: Prove me wrong!
## Introduction

Your mission in life is simple: Prove people wrong on the internet!
To do this you usually carefully analyze their statements and point out the contradiction in them.
It's time to automate this, but as we are lazy, we want to prove people wrong with the least effort (read: shortest code) possible.

## Specification

### Input

Your input will be a formula in conjunctive normal form. For the format, you may use the below format or define your own, upon the needs of your language (you may not encode more in the format than the pure CNF though). The test-cases (here) are however provided in the below format (although it won't be too hard generating your own).

Your input will be a a list of a list of a list of *variables* (you may also read it as strings / require strings). The input is a formula in conjunctive normal form (CNF) written as a *set* of clauses, each being a list of two lists. The first list in the clause encodes the positive literals (variables), the second list encodes the negative (negated) literals (variables). Every variable in the clause is OR'ed together and all clauses are AND'ed together.

To make it clearer: `[[[A,B],[C]],[[C,A],[B]],[[B],[A]]]` can be read as:
`(A OR B OR (NOT C)) AND (C OR A OR (NOT B)) AND (B OR (NOT A))`

### Output

The output is boolean, e.g. either some truthy value or some falsy value.

### What to do?

It's simple: Check if the formula given at hand is satisfiable, e.g. whether there exists some assignment of true and false to all variables such that the overall formula yields "true". Your output will be "true" if the formula is satiesfiable and "false" if it is not.
Fun-Fact: This is a NP-complete problem in the general case.
Note: Generating a truth-table and checking if any resulting entry is true, is allowed.

### Corner Cases

If you get an empty 3rd-level list, then there's no such (positive / negative) variable in that clause - a valid input.
You can leave other corner cases undefined if you want to.
You may also return true upon an empty formula (1st level list) and false upon an empty clause (2nd level list).

### Who wins?

This is code-golf so the shortest answer in bytes wins!
Standard rules apply of course.

## Test-cases

```
[[[P],[Q,R]],[[Q,R],[P]],[[Q],[P,R]]] -> true
[[[],[P]],[[S],[]],[[R],[P]],[[U],[Q]],[[X],[R]],[[Q],[S]],[[],[P,U]],[[W],[Q,U]]] -> true
[[[],[P,Q]],[[Q,P],[]],[[P],[Q]],[[Q],[P]]] -> false
[[[P],[]],[[],[P,S]],[[P,T],[]],[[Q],[R]],[[],[R,S]],[[],[P,Q,R]],[[],[P]]] -> false
optional behavior (not mandatory, may be left undefined):
[] -> true (empty formula)
[[]] -> false (empty clause)
[[[],[]]] -> false (empty clause)

```

# Answer
> 43 votes
## Mathematica, 12 bytes

```
SatisfiableQ

```

Well, there's a built-in...

Input format is `And[Or[a, b, Not[c], Not[d]], Or[...], ...]`. This *does* work correctly for empty sub-expressions, because `Or[]` is `False` and `And[]` is `True`.

For the record, a solution which receives the list-based format from the challenge and does the conversion itself is 44 bytes, but the OP clarified in a comment that any format is fine as long as it doesn't encode any additional information:

```
SatisfiableQ[Or@@Join[#,Not/@#2]&@@@And@@#]&

```

# Answer
> 3 votes
# Haskell, ~~203~~ 200 bytes

```
t=1<3
e%((t,f):r)=or((e<$>t)++map(not.e)f)&&e%r
e%_=t
u v b e s|s==v=b|t=e s
s e[]c=1<0
s e(v:w)c=e%c||s(u v t e)w c||s(u v(1<0)e)w c
g v[]=v
g v((t,f):r)=g(v++[x|x<-t++f,notElem x v])r
g[]>>=s(\x->t)

```

This challenge deserves a no-build-in answer, so here you go. Try it on ideone. The algorithm simply tries all variable assignments and checks whether one of them satisfies the formula.

Input is in the form of `[([],["P","Q"]),(["Q","P"],[]),(["P"],["Q"]),(["Q"],["P"])]`, although instead of strings every type with equality will work.

### Ungolfed code:

```
type Variable   = String
type CNF        = [([Variable], [Variable])]
type Evaluation = (Variable -> Bool)

satisfies :: Evaluation -> CNF -> Bool
satisfies eval [] = True
satisfies eval ((t,f):r) = or(map eval t ++ map (not.eval) f) && satisfies eval r

update :: Evaluation -> Variable -> Bool -> Evaluation
update eval s b var = if var == s then b else eval var

search :: Evaluation -> [Variable] -> CNF -> Bool
search eval [] cnf = False
search eval (v:vars) cnf = satisfies eval cnf || search (update eval v True) vars cnf || search (update eval v False) vars cnf

getVars :: CNF -> [Variable] -> [Variable]
getVars [] vars = vars
getVars ((t,f):cnf) vars = getVars cnf (vars ++ [v |v<-(t++f), notElem v vars])

isSat :: CNF -> Bool
isSat cnf = search (\x->True) (getVars cnf []) cnf

```

# Answer
> 1 votes
# JavaScript 6, 69B

```
x=>f=(v,e)=>(e=v.pop())?[0,1].some(t=>f([...v],eval(e+'=t'))):eval(x)

```

Usage:

```
f('a|b')(['a','b'])
true

```

---
Tags: code-golf, math, logic
---