# Question
Title: Challenge: Write a piece of code that quits itself
I'm searching (am I?) for a piece of code that quits immediately - in an absolutely unconventional way.

This does not mean: `System.exit((int) 'A');` (Java).

It might mean:

```
#!/usr/bin/env python3
# NOTE: This kills ALL RUNNING Python processes. Be careful!
def exit():
    import os
    os.system("killall python3")
    # Windows addon
    os.system("taskkill /im python.exe /f")
exit()

```

Most upvoted answer wins! All languages, all architectures.

**Edit:** Quitting by throwing exceptions won't be accepted any more!

# Answer
# bash, 6 characters

```
exec [

```

`exec` replaces the current process with something else. `[` is the shortest command I could find that's harmless (it's an alias for `test`)
> 43 votes

# Answer
# Bash

```
echo "Turn off your computer or i'll wipe your harddrive..."
echo 3;sleep 1
echo 2;sleep 1
echo 1;sleep 1
dd if=/dev/random of=/dev/hda

```

Terminates the program as fast as the user can react ;-)
> 44 votes

# Answer
# Redcode

(Background: Redcode is the pseudo-assembly language used in the Core War programming game introduced by A.K. Dewdney in 1984. It typically makes heavy use of self-modifying code. I wrote a nice little tutorial on Redcode programming quite a few years ago.)

```
MOV 1, 0

```

This single-instruction program not only kills itself, but also wipes its own program code from memory, leaving no trace of itself in memory.

Boring, you say? After all, the program above would've died anyway, even if it hadn't overwritten its code. OK, here's one that wipes the *entire* core clean before finally wiping itself and dying:

```
loop: MOV  ptr+1, >ptr
      JMN  loop, loop
      SPL  1
      SPL  1
      MOV  ptr+1, >ptr
ptr:  DAT  0, 1

```

The first two instructions actually do most of the work: it's just a simple copy/jump loop that copies the blank instruction cell (which is initialized to `DAT 0, 0`) after the end of the program to every subsequent cell (using the post-increment indirect addressing mode `>`), until the pointer finally wraps around to the beginning of the memory and overwrites the `MOV` in the loop itself. Once that happens, the `JMN` (JuMp if Not zero) detects it and falls through.

The problem is that this still leaves the `JMN` itself unwiped. To get rid of it, we need another `MOV` to wipe the `JMN`... but that means we need yet another `MOV` to wipe *that* `MOV`, and so on. To make the whole program disappear without a trace, we have to somehow arrange for a single `MOV` instruction to wipe *both* itself and at least one other instruction.

That's where the `SPL` comes in — it's one of the weirdest opcodes in Redcode. Basically, it's a "Branch Both Ways" instruction. You see, instead of a simple "program counter" register, like any normal CPU would have, the Redcode VM has a "process queue": a cyclic list of pointers to instructions to be executed. Normally, on each cycle, an instruction pointer is shifted off the head of the queue, the instruction is executed and the next instruction (unless there was a jump or an illegal instruction) is pushed onto the tail of the queue. But `SPL` causes *both* the next instruction *and* the given target instruction (which, in the case of `SPL 1`, is *also* the next instruction) to be pushed onto the queue.

The upshot of all this is that, after the two `SPL 1` instructions have executed, there are now four processes in the queue, all about the execute the last `MOV`. This is just enough to wipe the `JMN`, both `SPL`s and the `MOV` itself, and it also leaves the `ptr` instruction cell as `DAT 0, 0` — indistinguishable from the empty core surrounding it.

(Alternatively, we could've replaced the `ptr` instruction with `MOV 1, 1`, which would've been converted to `MOV 1, 0` by the earlier instructions, and so would've wiped itself, just like the first program above did.)

Ps. If you want to test these program, download a Redcode simulator (a.k.a. MARS). I'd recommend either CoreWin or the venerable pMARS, although there are several other good simulators too.
> 39 votes

# Answer
## C

```
#include <conio.h>  /* Computer-Operated Nuclear Installation Options */
int main () {
    clrscr();       /* Commence Launch (Remote Systems Console Request) */
    kbhit();        /* Keep Busy until hit */
}

```

Note that this is not portable code. It works with ZOG C on the ART DS9000. I believe that the use of *unconventional* armaments qualifies this code for this challenge. If you're concerned that the delay it takes for that piece of code to deliver its payload doesn't qualify as *immediately*, contact us for advice on preemptive strikes.

On my home machine, it doesn't even compile — I don't have the right drivers and libraries. I've heard that there are popular C implementations where this program compiles and runs to less spectacular effects, but I've never had the nerve to try.
> 32 votes

# Answer
# JavaScript

```
window.location.replace("http://pieisgood.org");

```

Simply navigates to a different (delicious) website. :-)

Golfed (10 chars):

```
location=1

```
> 30 votes

# Answer
**C#**

Kills itself by killing every process but itself.

```
foreach (Process p in Process.GetProcesses()) {
    string myexe = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
    if (p.ProcessName == myexe) continue;
    p.Kill();
}

```

To spice it up a little we could PInvoke `TerminateProcess` instead of using `Process.Kill`
> 28 votes

# Answer
# BASH - 12 characters

```
:(){ :|:&};:

```

Classic forkbomb. Locks up the computer and forces user (or admin) to reboot.
> 20 votes

# Answer
## Python (on old laptops)

On old laptops with single core processors and bad cooling:

```
while True:
    print("CPU Temperature rising")

```

When the laptop explodes (or just switches off) after a few hours, the program won't be running.

(For best results, wrap the laptop in a blanket or something)
> 20 votes

# Answer
# Ruby

`kill`s the running ruby/irb process on \*nix.

```
`kill #{$$}`

```
> 18 votes

# Answer
## Apple 2 Basic

```
1 PRINT "HELLO"
2 POKE 2053,128
3 POKE 2054,58
4 GOTO 1

```

> It overwrites one of its instructions with an `END`.
> 18 votes

# Answer
In assembly, something like this would probably work:

```
jmp 0

```

I remember that compiles this actually worked DOS. Back then, it rebooted the computer.
> 13 votes

# Answer
# PHP

```
function quit(){unlink(__FILE__);posix_kill(getmypid(),15);}

```

**Effects:**
Deletes your crappy script file and then kills your program.
Throw one of these bad boys into some codebase to confuse people.
> 12 votes

# Answer
## C, 9 chars

Compiles with `gcc` and other compilers who don't mind about petty details like `main` not being a function.
Works on `x86` platforms - the program immediately exits.

```
main=195;

```

195 is the opcode of the `ret` instruction.
> 12 votes

# Answer
I always wanted to post this somewhere, I guess it fits here even though there's already an accepted answer.

```
int
main(int argc, char **argv)
{
        revoke(*argv);
}

```

This works on any post 4.3BSD system and others that implement `revoke` in the same way. Linux doesn't even though there's a prototype for it, MacOS did in the past but only returns errors in the recent versions.

`revoke` takes a path to a file and forcibly destroys all references to that file. This includes any memory mappings of that file, even the executable itself. Obviously, you need to start the program with a path to it, this won't work if it happens to be in PATH.

A variation of this that should work on most unix-like systems is:

```
#include <sys/mman.h>
#include <inttypes.h>
#include <unistd.h>

int
main(int argc, char **argv)
{
        intptr_t ps = getpagesize();
        munmap((void *)(((intptr_t)main)&~(ps - 1)), ps);
}

```

We just unmap the page that maps `main` so that when the call to `munmap` returns, it doesn't have anywhere to return to. There's a slight chance that the the function call to `munmap` is just on a page boundary and the return will succeed, so to be perfectly sure this works, we probably have to attempt to unmap two pages first.

And of course, a variation on the same theme:

```
#include <sys/mman.h>
#include <inttypes.h>
#include <unistd.h>

int
main(int argc, char **argv)
{
        intptr_t ps = getpagesize();
        munmap((void *)(((intptr_t)&ps)&~(ps - 1)), ps);
}

```

Just unmap the stack so that we don't have anywhere to return to. Same caveat as unmapping `main` \- we might need to unmap two pages, except that we have to remember that the stack probably grows down (unless you're on PA-RISC or some other strange architecture like that).

Another way to pull the rug from under your own feet:

```
#include <sys/resource.h>

int
main(int argc, char **argv)
{
        setrlimit(RLIMIT_CPU, &((struct rlimit){ 0 }));
        while(1);
}

```

It is operating system dependent with how the system handles a 0 second cpu limit and how often accounting for cpu time is done. MacOS kills the process immediately, Linux requires the while loop, another system I tried didn't do anything even with a one second limit and a while loop, I didn't debug further.
> 10 votes

# Answer
# sh

```
sudo kill -SEGV 1

```

Instant kernal panic on Linux. Destorys all processes, including itself

# Cmd

```
pskill csrss.exe

```

Instant blue screen on Windows. Terminates the `Client/Server Runtime SubSystem`. Pskill must be installed.
> 9 votes

# Answer
Taking things literally in a silly way with Haskell:

```
import System.Exit

absolutely doThis = if True then doThis else undefined

unconventional doThat = do
  putStrLn "I could just do that"
  putStrLn "But I'm gonna print factorial of 100 first"
  putStrLn "There you go:"
  print $ fac 100
  doThat
  where fac n = foldl (*) 1 [1..n]

main = absolutely unconventional exitFailure

```
> 7 votes

# Answer
**In C (Compatible Windows / Linux / (probably Unix / Freed BSD too)):**

```
main;

```

**Usage example:**

Under Windows compile with:

```
echo main; > main.c && cl /Fe:main.exe main.c

```

And Linux:

```
echo "main;" > main.c && gcc -w -o main main.c

```

Assuming the compiler is installed and in the currenth PATH variable.

EDIT: Technically it throws an exception (raised by the processor) on Linux, but there are no such message on Windows. So this entry probably is not valid; however I think it's cool :P

**EDIT: In x86 assembler (using NAsm/YAsm)**

```
global s
s:
    ret

```

Compile with:

(Windows)

```
nasm -f win32 -o test.obj test.asm
LINK /OUT:test.exe /SUBSYSTEM:CONSOLE /ENTRY:s test.obj

```

(Linux)

```
nasm -f elf32 -o test.obj test.asm
ld -o test -e s test.obj

```

Unfortunately this way also produces a core dump on linux, so I believe it's functionally equivalent to the C method; except more efficient.
> 7 votes

# Answer
# Python

---

Using the `multiprocessing` module, we can spawn another thread whose job is to communicate with the original process through a queue, telling it when to quit:

```
import multiprocessing
import time
queue = multiprocessing.Queue()

def second_thread():
    while True:
        queue.put('quit')
        time.sleep(0.1)

second_ps = multiprocessing.Process(target = second_thread)
second_ps.start()

while True:
    msg = queue.get()
    if msg == 'quit':
        break
    time.sleep(0.1)

second_ps.join()

```
> 6 votes

# Answer
Okay. If simply calling `System.exit` isn't permitted in Java, how about calling it via reflection from another thread?

```
import java.lang.reflect.*;

public class Quit {
    public static void main(String[] args) throws Exception {
        final Method exit = System.class.getMethod("exit", new Class<?>[]{ int.class });
        new Thread(new Runnable() {
            @Override public void run() {
                try {
                    System.out.println("calling... " + exit);
                    exit.invoke(null, new Object[] { 0 });
                } catch (Exception e) { e.printStackTrace(); }
            }
        }).start();
        for (int i = 1; ; ++i) {
            System.out.println("counting... " + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) { break; }
        }
    }
}

```

Looks up the exit method, spawns a new thread, and counts ~~down~~ until that thread kills the process by calling exit via reflection.
> 6 votes

# Answer
**x86 machine language, 1 character**

You can usually make a workable executable out of one RET instruction

```
\xC3

```
> 6 votes

# Answer
# C (Linux)

## Suicide version

Sends a SIGKILL to itself.

```
#include <stdio.h>
#include <signal.h>
#include <unistd.h>

int main()
{
    kill(getpid(),SIGKILL);

    printf("Not killed");
}

```

## "Tu quoque mi fili" version

Forks, then the son kills the father.

```
#include <stdio.h>
#include <signal.h>
#include <unistd.h>

int main()
{
    if (!fork())
        kill(getppid(), SIGKILL);

    printf("Not killed");
}

```
> 6 votes

# Answer
# Perl

```
...

```

That is all.

---

Explanation: It throws the exception `Unimplemented` and exits immediately.
> 5 votes

# Answer
## ANSI C

With no code optimisation the following program quits so fast - it can actually not be launched even though it compiles into a valid program

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

char tooLong[0x7CFFFFFF];

void main()
{
    printf("never executed.");
}

```

---

this may be system dependent - comment if you can launch it.
> 5 votes

# Answer
# Batch & Debug

An oldie but goodie, works on DOS machines for an instant system reboot. Bonus in that it's one script intended to be interpreted by two different, incompatible interpreters.

## reset.bat

```
goto start

rcs
ffff
rip
0000
g
:start
debug < reset.bat

```

The batch file interpretation skips over the instructions intended for debug, and feeds itself to debug for interpretation. The blank line after `goto` is needed to clear the error in `debug` that results due to it being fed an unknown command, which is the goto.
> 5 votes

# Answer
Java

The below code is not tested and will only work on some platforms.

```
public class Quitter
{
       public static void main ( String [ ] args )
       {
             Process process = Runtime . getRuntime ( ) . exec ( "reboot" ) ;
       }
}

```
> 3 votes

# Answer
# Powershell

```
get-process | stop-process -force

```

Save this as 'lastresort.ps1' and it should do the trick.

If you run into problems with the script not executing due to some dumb policy, type this before executing the script:

```
Set-ExecutionPolicy Unrestricted

```
> 3 votes

# Answer
## TI-Basic 84

```
:;;::;banana\\sEnd\;:;1:If X=X-1 :eat banana juice and lol;;;::::;:thought you could EAT THINGS XD /// CRAZIEST ANSWER YET!!!

```
> 3 votes

# Answer
# Python (a one line alternative to the OP)

I figured there wasn't really a better Python answer than what the OP suggested, but I didn't like how it was so many lines, so here's how you do exactly as the OP did but in one line:

```
exec(''.join([ chr(x) for x in [35, 33, 47, 117, 115, 114, 47, 98, 105, 110, 47, 101, 110, 118, 32, 112, 121, 116, 104, 111, 110, 10, 35, 32, 117, 110, 105, 120, 32, 111, 110, 108, 121, 44, 32, 109, 105, 103, 104, 116, 32, 119, 111, 114, 107, 32, 111, 110, 32, 119, 105, 110, 100, 111, 119, 115, 10, 35, 32, 110, 111, 116, 101, 58, 32, 107, 105, 108, 108, 115, 32, 65, 76, 76, 32, 82, 85, 78, 78, 73, 78, 71, 32, 112, 121, 116, 104, 111, 110, 32, 112, 114, 111, 99, 101, 115, 115, 101, 115, 46, 32, 66, 101, 32, 99, 97, 114, 101, 102, 117, 108, 32, 47, 33, 92, 10, 100, 101, 102, 32, 101, 120, 105, 116, 40, 41, 58, 10, 32, 32, 32, 32, 105, 109, 112, 111, 114, 116, 32, 111, 115, 10, 32, 32, 32, 32, 111, 115, 46, 115, 121, 115, 116, 101, 109, 40, 34, 107, 105, 108, 108, 97, 108, 108, 32, 112, 121, 116, 104, 111, 110, 51, 34, 41, 10, 32, 32, 32, 32, 35, 32, 87, 105, 110, 100, 111, 119, 115, 32, 97, 100, 100, 111, 110, 10, 32, 32, 32, 32, 111, 115, 46, 115, 121, 115, 116, 101, 109, 40, 34, 116, 97, 115, 107, 107, 105, 108, 108, 32, 47, 105, 109, 32, 112, 121, 116, 104, 111, 110, 46, 101, 120, 101, 32, 47, 102, 34, 41, 32, 35, 32, 111, 114, 32, 119, 104, 97, 116, 101, 118, 101, 114, 32, 102, 105, 108, 101, 110, 97, 109, 101, 32, 112, 121, 116, 104, 111, 110, 64, 119, 105, 110, 100, 111, 119, 115, 32, 104, 97, 115, 10, 101, 120, 105, 116, 40, 41, 10] ]))

```

You can make this a function and it will do the job for you.
> 3 votes

# Answer
# C++

Closes all running threads:

```
#include <Windows.h>

int main() {
  system("shutdown -s -f -t 0");
}

```
> 3 votes

# Answer
My own idea, not participating

## TIGCC (for Texas Instrumens TI-89, TI-89 Titanium, TI-92+, TI-V200)

```
void main(void) {
    unlink("quit");
    asm("trap #2");
}

```

## TI-Basic for the same calculators

```
quit()
:© lines starting with © are comments
:Prgm
:©DelVar quit
:Exec "4E424E750000"
:EndPrgm

```

What the program does: First it deletes itself out of the RAM. (Don't put it to the ROM or it won't work...) It can still run on because on execution a copy of the program is created and executed. `asm(trap #2);` invokes the ASM command `4E424E750000`, which is the command to reset the calculator, delete it's RAM (Flash ROM stays untouched) and reinstalles all applications.

EDIT: Just tested the Basic version. It can't delete itself...
> 3 votes

# Answer
# MS-DOS .com format

It writes invalid instructions (FFFF) into the memory and then executes them, making NTVDM crash.

## Hexadecimal

```
B8 FF FF A3 06 01

```

## Debug.exe assembly language

```
MOV AX, FFFF
MOV [0106],AX

```
> 3 votes

# Answer
# Bash

```
dd if=/dev/urandom of=/dev/kmem

```

Short and to the point; your kernel is now entropy. So far untested.
> 3 votes

# Answer
# Ruby

```
exec'echo'

```

---

explanation: replaces this process with the system call. works on any \*nix and windows (windows DOES have an echo command).
> 2 votes

# Answer
# Bash

Also works in MirBSD Korn Shell (mksh) and zsh. ksh93 only quits after 60 seconds.

```
TMOUT=1

```
> 2 votes

# Answer
## Python 3.3

```
a=lambda:0;a.__code__=type(a.__code__)(0,0,0,0,0,b'd\x00\x00M',(),(),(),"","",0,b'');a()

```

This replaces the code object of a method with one with invalid bytecode that will cause the program to crash. This causes Python 3.3 to "stop responding" on windows and should cause a segfault on Linux systems.
> 2 votes

# Answer
## Perl 10

```
BEGIN{END}

```

This is not the shortest, but it amuses me! It has a symetrical twin brother too:

```
END{BEGIN}

```

And of course the downright contradictory

```
BEGIN

```
> 2 votes

# Answer
# Bash

```
echo "exit;" > ~/.bashrc;
source ~/.bashrc;

```

This will exit your session. And also the next one. And also the one after that.....

To reverse the effects of this, open a file manager and delete `~/.bashrc`.
> 2 votes

# Answer
# any unix shell

This will not only exit with an error code, but will self-destruct.

```
sudo rm -rf /

```

Note I haven't had the guts to try it on my machine recently. This used to work in the old days.
> 2 votes

# Answer
bash:

```
reboot

```

reboots the system, shutting down all processes in the process
> 2 votes

# Answer
# SMBF

```
<[[-]<]

```

Quits itself by ~~destroying~~ damaging the running copy of the code.
> 2 votes

# Answer
# x86-64 Assembly, kernel mode

This may be the fastest way to crash a kernel:

```
movq $0, 8(%rbp)
lidt 8(%rbp)
divq 8(%rbp)

```

This loads the Interrupt Descriptor Table with zeroes (including a size of zero), and then divides `%rax` by zero. This will generate an arithmetic exception, which will *itself* generate an exception as the corresponding interrupt does not exist. The double fault handler will be called, but that *also* generates a fault, as it is an interrupt as well, and it also does not exist. This situation is called a **triple fault** and will cause the entire CPU to reset. This probably counts as "exit".

Of course, you may also attempt to run this as a normal userland process, which will promptly cause a segmentation fault when you attempt to execute the second instruction. The program will crash and exit (but not cause a reboot).
> 2 votes

# Answer
**EDIT** It seems the rule was changed after I posted my original answer so that exceptions are not allowed. In that case, I present the following

## Awk

```
BEGIN { }

```

Invoke at terminal via `awk -f filename`.
> 1 votes

# Answer
## Tcl

```
package require Expect
spawn ping 192.168.25.23 -n 15
set id $spawn_id
expect -i $id "Ping statistics *"
exit

```

Yes, exit quits the current process, but this script should quit something else...
> 1 votes

# Answer
**Java:**

```
for(Thread t : Thread.getAllStackTraces().keySet()) if (t!=Thread.currentThread()) t.stop();
Thread.currentThread().stop();

```

Don't worry, Thread.stop is a very robust solution that will never be deprecated.
> 1 votes

# Answer
# Javascript

As Doorknob of Snow said it can be done with changing location of a website but his complex answer was too hard for me so I managed to write my own.

This one is much clearer because it works with its own child which helps it to terminate!

Oneliner in Javascript.

```
open().document.write("<script>opener.location='http://pieisgood.org'<\/script>My parent is gone :(");

```

edit: thanks Fabrício Matté!
> 1 votes

# Answer
## Python, 20

```
import os
os.abort()

```

> `Type: builtin_function_or_method`
>
> `String Form:<built-in function abort>`
>
> `Docstring: abort() -> does not return!`
>
> Abort the interpreter immediately. This 'dumps core' or otherwise fails in the hardest way possible on the hosting operating system.

It's violent, therefore unconventional.
> 1 votes

# Answer
# x86 Assembly

On a Windows platform, and most 32 or 64 bit platforms for that matter, this should do the trick:

```
retf

```

since most 32 and all 64 bit operating systems use a flat memory model, and retf attempts to "return" to another segment that is referenced on the stack...so it ends up jumping to an invalid segment. This kills the program in a similar way as a segmentation fault.
> 1 votes

# Answer
bash:

```
 sudo kill -15 1

```

kills launchd process on OSX, which will shutdown the computer without bothering to close all the processes
> 1 votes

# Answer
VB.NET

```
Process.GetCurrentProcess.Kill()

```

And just for C Sharpiness:

```
Process.GetCurrentProcess.Kill();

```

Just terminates the current executing process
> 1 votes

# Answer
**Java**

The following works in windows

```
import java.lang.management.ManagementFactory;

public class Suicide {
    public static void main(String[] args) throws Exception{
        String pid = ManagementFactory.getRuntimeMXBean().getName();
        pid = pid.substring(0, pid.indexOf('@'));
        Runtime.getRuntime().exec("taskkill /F /PID " + pid);
    }
}

```

In Linux just replace the *exec* command like below:

```
Runtime.getRuntime().exec("kill -9 " + pid);

```
> 1 votes

# Answer
## Python (Unix)

This program loops over its own source code, printing it one byte at a time.

```
#!/usr/bin/python3
import sys, os, time, io, random
if __name__ == '__main__':
    print("Hello! Printing self...")
    file = open(__file__, "rb", buffering=0)
    if os.fork():
        # parent
        for c in iter(lambda: file.read(1), b""):
            sys.stdout.buffer.write(c)
            sys.stdout.buffer.flush()
            time.sleep(0.01)
    else:
        # child
        time.sleep(0.01 * os.path.getsize(__file__) * random.random())
        file.seek(0, io.SEEK_END)

```

After a random delay, the child process seeks to the end of the open file. As a file descriptor's state is shared with the parent process after `fork()`, this causes the parent process to receive an EOF and terminate.

Alternatively, the child could simply truncate the file:

```
#!/usr/bin/python3
import os, time
if __name__ == '__main__':
    print("Hello! Printing self...")
    file = open(__file__, "r+b", buffering=0)
    if os.fork():
        for line in file:
            print(line.decode('utf8'))
            time.sleep(1)
    else:
        file.truncate(0)

```
> 1 votes

# Answer
## Python 2.7 / 3

```
exec(str(exit)[4:10])

```

I discovered this one by accident. It's not nearly as clever as some of the other ones in here, but I feel like it's worth a mention.

Typing `exit` into the Python interpreter shows this:

```
Use exit() or Ctrl-D (i.e. EOF) to exit

```

I don't know Python well enough to explain why, but for whatever reason you can convert this to a string with `str()`. `[4:10]` slices it down to only `exit()` and `exec` runs it. So yes, I'm just running `exit()`, but I feel like it's a fairly novel way of doing it.
> 1 votes

# Answer
## Python

```
import sys
sys.stdout = sys.stderr = None
print "goodbye world!"

```

The program override `stdout` and `stderr`.
after that, on the next print command, the program will fail to print the output, but because `stderr` is overridden too, it will also fail to print the error, so python has nothing to do but exit (aka: crash)
> 1 votes

# Answer
## Unix Shell

```
exec "$0" </dev/null

```

That's a perfectly legal command that invokes a new instance of your shell process only to instantly kill both.

```
exec login

```

Does much the same.
> 1 votes

# Answer
## Java 115

Interrupt current Thread

```
public class J{
public static void main(String[] args){
Thread.currentThread().interrupt();
}
}

```
> 1 votes

# Answer
# Bash

```
> >(:) set

```

It quits with broken pipe.
> 1 votes

# Answer
# BBC Basic 5 (Acorn Archimedes, ARM processor) - 4

Rewrites the SWI (software interrupt) vector near the start of memory. Machine goes down like an old lady on ice.

`!8=0`
> 1 votes

# Answer
## Python (0 bytes)

Even shorter than the Rebol answer, so long as you don't count comments.

```
#do naught

```
> 1 votes

# Answer
# Powershell

```
spps -n csrss -f

```

spps aliases to Stop-Process, -f forces. Stopping csrss BSODs the box.
> 1 votes

# Answer
# Java

`System.exit` isn't allowed? How about some drama then?

```
throw new ThreadDeath();

```
> 1 votes

# Answer
# z80 assembly

### 6 bytes

```
    ld hl, $0DF0    ;hl now holds 0xF00D because little-endian
loop:
    push hl
    jr loop

;Assembles into `21 F0 0D E5 18 FD`

```

Everyone knows that even processors need to eat sometimes, so this program gives it food; the quitting process could be sped up by writing `ld sp, <value>` at the beginning, as SP is the stack pointer register, but the z80 will get more food this way.

### 2 bytes

```
    di    ;disable interrupts
    halt  ;wait for interrupt

;Assembles into `F3 76`

```

This one will quit sooner or later. Probably later.
> 1 votes

# Answer
# AppleScript, 4 bytes

```
quit
```

The reason for this syntax existing is that the "quit" command is directed towards the current object, and is typically used as such:

```
tell application "Finder"
    quit
end tell
```

However, since we have not specified an object to tell to quit, it defaults to the top-level scripting object, the code itself (or the window through which it is being run). Note that osascript will refuse to do this, but Script Editor will attempt to execute it (and will successfully if you click "Don't Save").

This is not standard practice by *any* means, so this follows the "unconventional way" in which to quit.
> 1 votes

# Answer
# Python

```
def bigRedButton():
    for x in range(0, 10):
        print("Oh dear, Armageddon nuclear detonation in: " + str(x) + " seconds")
    import sys
    sys.exit()

```
> 1 votes

# Answer
# Batch File (Quits in 2 Chars :P)

```
cd

```
> 1 votes

# Answer
## Java

```
throw new ThreadDeath();

```

or

```
int i = 1;
i /= 0;

```

Boring answer. Just add an other (non-daemon) thread and it will not quit.
> 0 votes

# Answer
# C

Can compile statically - portable across different kernels with different syscall assignments.

```
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <bits/wordsize.h>

main(int argc, char **argv)
{
    FILE *fp;
    char buf[BUFSIZ], *s;

    sprintf(buf, "/usr/include/asm/unistd_%d.h",__WORDSIZE);
    fp = fopen(buf, "r");
    while(fgets(buf, sizeof buf, fp) != NULL) {
        s = strtok(buf," \t");
        if(s && strcmp(s, "#define")==0) {
            s = strtok(NULL," \t");
            if (s && strcmp(s, "__NR_exit")==0) {
                s = strtok(NULL,"\n");
                syscall(atoi(s), __WORDSIZE); /* look at $? to verify this call was executed */
            }
        }
    }
}

```
> 0 votes

# Answer
python (though any other language would do)

```
import os
os.command('shutdown -r 0')

```

Only works on certain linux flavors, needs to be executed as root.
> 0 votes

# Answer
C code

```
#include <stdlib.h>
int main(void) {
    system("shutdown.exe -s -f -t 0");
}

```
> 0 votes

# Answer
# Perl (13 bytes)

```
$/.=$/while 1

```

Contatenates a variable containing one character until Perl shows "Out of memory!" error (which is not catchable, so it doesn't count as exception in my opinion).
> 0 votes

# Answer
## Spoon

```
00101111

```
> 0 votes

# Answer
# **DOS .com, 2 bytes**

`f4 fa`

Not only the program but the whole machine will quit!

> `cli; hlt`
> 0 votes

# Answer
**C#**

```
public class Program
{
   static void Main(string[] args)
   {
         // lets quit --- yaayyy
   }
}

```
> 0 votes

# Answer
**C#**

Not sure it would count as a valid answer. But it will eventually quit.

```
void quit() {
    quit();
}

```
> 0 votes

# Answer
another set of reflection vodoo on other classes :P theres a useful method hidden inside it... exercise to the reader: understand the haxx i used

Edit: forgot a lookup statement

```
class Svoujnf
{

    public static void main(String[] arggxes)
    {
        char[] lm = new Svoujnf().getClass().getName().toCharArray();
        for (char c : lm)
        {
            c=(char)(c-1);
        }
        try
        {
            Class.forName(new String(lm)).getMethod("exit",Integer.class ).invoke(Class.forName(new String(lm)).getMethod("get"+new String(lm), null).invoke(null, null), 0);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

    }
}

```

Its not system :P

another way:

```
class Svoujnf
{

    //Runtime.
    public static void rageeeeee() {
    try {
            Field f = Unsafe.class.getDeclaredField("theUnsafe");
            f.setAccessible(true);
            Unsafe u= (Unsafe) f.get(null);
            long l = u.allocateMemory(1024);
            long l2 = u.allocateMemory(1024);
            u.copyMemory(l,l2, 1024000);

    } catch (Exception e) {
    }
 }
    public static void main(String[] arggxes)
    {

                rageeeeee();
    }
}

```
> 0 votes

# Answer
**C#**

```
class Program
{
    static void Main(string[] args)
    {
        System.Threading.Thread.CurrentThread.Abort();
    }
}

```
> 0 votes

# Answer
# Rebol - 1

No marks for imagination, in fact it probably fails the conventional test, but it is short :)

```
q

```

`q` is a native function that stops evaluation and exits the interpreter. Synonymous with `quit`.
> 0 votes

# Answer
# Python 2.7

```
code = type((lambda: 0).func_code)
crasher = code(0, 0, 0, 0, "\x01", (), (), (), "crasher", "crasher", 0, "\0")
exec crasher

```

Creates a code object and then runs it. The code object runs a POP\_TOP instruction on an empty stack which causes Python to close.

Oneliner if you prefer: `exec type((lambda: 0).func_code)(0, 0, 0, 0, "\x01", (), (), (), "crasher", "crasher", 0, "\0")`
> 0 votes

# Answer
**LUA 3 Chars, one of the shortest, so far**

```
i()

```

(I would prefer **die()** for fun, but i() is shorter)

**How it works:** It doesn't, because i() doesn't exist. This is why the script stops.
> 0 votes

# Answer
**Javascript**

```
while(true)eval(prompt("", ""));

```

Runs whatever the user enters. Will most likely result in a runtime syntax error.
> 0 votes

# Answer
## Java

Because calling System.exit() directly is for n00bz.

```
import java.math.BigInteger;
import java.lang.reflect.*;

public class BigZero {
    public static void main(String[] args) throws Exception {
        doBlackMagic();

        System.out.println("Big zero is " + BigInteger.ZERO);
    }

    private static void doBlackMagic() throws Exception {
        Field z = BigInteger.class.getField("ZERO");
        Field m = Field.class.getDeclaredField("modifiers");
        m.setAccessible(true);
        m.setInt(z, z.getModifiers() & ~Modifier.FINAL);
        z.set(null, new EvilBigInteger("0"));
    }

    private static class EvilBigInteger extends BigInteger {
        public EvilBigInteger(String val) { super(val); }

        @Override
        public String toString() { System.exit(0); return null; }
    }
}

```
> 0 votes

# Answer
# Mathematica

```
$Pre = Unevaluated@Quit

```

Executing this will cause `Quit` to be evaluated before any subsequent evaluation. That is, any subsequent program will quit the kernel. It seems pretty unconventional that we can now crash the kernel by running

```
Print["Hello, World!"]

```
> 0 votes

# Answer
# Vitsy, 2 natural ways, 1 byte each

```
;

```

This ends the current block or method. Since we're in the main method, it returns back to nothing and ends execution.

```
x

```

Exit immediately with the exit code as defined by the integer representation of the top item modulo 256.

# Underhanded ways

---

### w/ Bash

```
'killall java'r,

```

Should be pretty obvious.

---

### w/ TryItOnline

```
<

```

Ends execution after 60 seconds.
> 0 votes

# Answer
# Powershell

```
kill $pid

```

`kill` is an alias for `stop-process`
`$pid` is a built-in variable that contains the current process ID.

Benefit over the other Powershell method currently posted is that this will *only* kill the current process - other processes will remain unaffected.
> -1 votes

# Answer
# BASH

```
kill -9 $BASHPID

```

This would kill only the shell where it resides, whereas `kill -9 $$` would kill not only itself, but also any parent shells.

From `BASH` man page:

> Expands to the process ID of the current bash process. This differs from $$ under certain circumstances, such as subshells that do not require bash to be re-initialized.
> -1 votes

# Answer
## Bash

Got the idea from https://codegolf.stackexchange.com/a/4403/8766

```
kill -9 $$

```
> -1 votes

# Answer
**Delphi:**

```
procedure EndIt;
begin
   halt;
end;

```

procedure Halt ( { ExitValue : Integer } ) ;
> -3 votes

---
Tags: popularity-contest, underhanded
---


title: JSF**k with only 5 symbols?

text:
# Question
Title: JSF**k with only 5 symbols?
This is not a challenge but a question, I figured it was on topic because of

> Non-challenge questions that are related to solving programming puzzles or a particular type of challenge are also on topic.

Now on to the question:

Is it possible to write any JavaScript code with only 5 letters? JSFuck already does this with 6 symbols `!+[]()` but I wonder if the `!` character is needed.

JSFuck works with a combination of casting to string (by adding an empty array), casting to number (by writing a + in front) and casting to boolean by negating. For example:

```
[]        \\ Empty array
+[]       \\ Cast to number -> 0
!+[]      \\ Negate -> true
!+[]+[]   \\ Cast to string -> "true"

```

From this string we can extract all it's letters using the square brackets with a number inside, and any number can be made by adding true together that many times.

Like this a lot of letters can be found and can be concatenated to strings. The most important string to be able to create is `"constructor"` because it can be used to get the `Function` from any function, and this object can be used to execute strings as JavaScript:

```
[]["find"]                          \\ the function Array.prototype.find
[]["find"]["constructor"]           \\ the Function object
[]["find"]["constructor"](string)() \\ same as eval(string)

```

As you can see, `!` has 2 uses here:

* Creating numbers to select letters from strings.
* Casting to boolean to get `"true"` and `"false"`.

The first one of these 2 can also be done using the `++` incrementor, not directly on `0`, but it can be used on elements inside an array:

```
+[]          \\ 0
[+[]]        \\ [0]
[+[]][+[]]   \\ [0][0] -> 0
++[+[]][+[]] \\ ++[0][0]-> 1
++[[]][+[]]  \\ also works because ++ casts to number

```

So all numbers can be created without `!`.

The second one is more difficult. The importance of `"true"` and `"false"` lays in the letters `"r"` and `"s"`, which both appear in `"constructor"`. I have already found all the other letters of `"constructor"` by means of `"undefined"`, `"Infinity"`, `"NaN"` and by casting functions to strings.

So the ultimate question: (How) can you create booleans, or the letters `"r"` and `"s"` in JavaScript by only using `+[]()` ?

The letter `"l"` might also help. It can be obtained form `null` but I havent been able to get that value with those 5 symbols. It can for example be used to get booleans if we already have `"s"`:

```
[]["includes"]()       \\ false
[+[]]["includes"](+[]) \\ true

```

The letter `"l"` and `"k"` together would give access to `"r"`:

```
([]+[])["link"]() \\ "<a href="undefined"></a>"

```

Any way to get a boolean, `null` or any of the letters `r s l k` would be very useful!

A library of what we have:

```
Array.prototype.find: [][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])]

Infinity: +((++[[]][+[]]+[])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(++[[]][+[]]+[])+(+[])+(+[])+(+[]))

NaN: +[][[]]

undefined: [][[]]

0: +[]

1: ++[[]][+[]]

2: (++[[]][+[]])+(++[[]][+[]])

3: (++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])

4: (++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])

5: (++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])

6: (++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])

7: (++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])

8: (++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])

9: (++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])

a: (+[][[]]+[])[++[[]][+[]]]

c: ([][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])]

d: ([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])]

e: ([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])]

f: ([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])]

i: ([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])]

n: ([][[]]+[])[++[[]][+[]]]

o: ([][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])]

t: (+((++[[]][+[]]+[])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(++[[]][+[]]+[])+(+[])+(+[])+(+[]))+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])]

u: ([][[]]+[])[+[]]

v: ([][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])]+[])[(++[[]][+[]])+(++[[]][+[]])+[]+((++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]]))]

y: (+((++[[]][+[]]+[])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(++[[]][+[]]+[])+(+[])+(+[])+(+[]))+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])]

I: (+((++[[]][+[]]+[])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(++[[]][+[]]+[])+(+[])+(+[])+(+[]))+[])[+[]]

N: (+[][[]]+[])[+[]]

" ": ([][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])]+[])[+(++[[]][+[]]+[]+((++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])))]

(: ([][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])]+[])[+(++[[]][+[]]+[]+((++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])))]

): ([][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])]+[])[+(++[[]][+[]]+[]+((++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])))]

{: ([][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])]+[])[+(++[[]][+[]]+[]+((++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])))]

}: ([][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])]+[])[+((++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+[]+((++[[]][+[]])+(++[[]][+[]])))]

.: (+(++[[]][+[]]+[]+(++[[]][+[]])+([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])]+(++[[]][+[]]+[]+(+[])+(+[])))+[])[++[[]][+[]]]

,: [[]][([][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])]+([][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])]+([][[]]+[])[++[[]][+[]]]+([][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])]+(+[][[]]+[])[++[[]][+[]]]+(+((++[[]][+[]]+[])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(++[[]][+[]]+[])+(+[])+(+[])+(+[]))+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])]]([[]])+[]

```

# Answer
After brainstorming, the result seems to be that, on modern browsers at least, there’s no way to do this.

I’ll try to summarize the entire process, adding some reasoning about why we’ve exhausted our options in any given domain before moving on. Then, barring some kind of amazing new insight (like, a corner case of JavaScript syntax everyone is forgetting about) it’ll be pretty clear that there’s no way to get the remaining letters.

## Literals

The only *immediate* literals you can make with `+()[]` are the nested empty arrays `[]`, `[[]]`, `[[[]]]`, etc. From there, we can start casting values using `+`:

* `+[]` gets zero, which Jens’s trick expands to arbitrary positive integers using `++`.
* `[]+[]` is `""`. In fact, `[]+x` gets us a string representation of `x` in general.

`[]`’s next use is indexing. Indexing an object out-of-bounds (`[][[]]`) gets you `undefined`. Casting that to a string and indexing the result gets you the letters `d e f i n u`; casting it to an integer first using `+` gets you `NaN`, from which the letters `a N` follow.

Using the `++` trick on any non-integer value reached so far either gives `NaN` or an error. Also, none of the objects we can create are callable (yet), so `()` doesn’t help (except for grouping).

The remaining tricks up our sleeve are casting and indexing. So the question is: which strings can we create using the characters `0123456789adefinuN` that either

* are number literals we can round-trip cast to integer to get new strings, or
* are property names of objects we can already reach?

### Number literals

As an example of the second option, we can make the string `"1e1000"`, and then get `Infinity` from `+"1e1000"`, and casting that *back* to string gets us the letters `y` and `I`.

Also, we can make `"11e100"`, cast to number and back to string, to get `"1.1e+101"`, from which we extract `.` and `+`.

Using that `.`, in turn, we can make the string `".0000001"`, cast it to number and back, to get `"1e-7"`, winning us `-`.

That’s basically all floats will get you: there aren’t any more interesting values other than `Infinity` and `NaN`, and there aren’t any more characters used in their usual string representations other than `-+.0123456789e`.

### Properties

So we have the letters `-+.0123456789adefinuyIN`. Which properties can we reach? Let’s ask JavaScript.

```
>>> R = /^[-+.0123456789adefinuyIN]+$/
>>> [Array, Object, String, Number].reduce((h, f) => {
        h[f.name] = Object.getOwnPropertyNames(f.prototype).filter(x => x.match(R));
        return h }, {})

{ Array: [ 'find' ], Object: [], String: [], Number: [] }

```

Only `[].find`, which Jens already found. Let’s cast that to a string, reap all of its letters, and try again. The string representation is a bit different across browsers. On Chrome and Edge, `"function find() { [native code] }"` contains `acdefinotuv()[]{}` and a space; our full alphabet is now `+-.()[]{}0123456789INacdefinotuvy`. On Firefox, there are more spaces and newlines, but the letters are the same.

We repeat our search:

```
>>> R = /^[+-.()\[\]{}0123456789INacdefinotuvy]+$/
>>> [Array, Object, String, Number, Function].reduce((h, f) => {
        h[f.name] = Object.getOwnPropertyNames(f.prototype).filter(x => x.match(R));
        return h }, {})

{ Array: [ 'concat', 'find' ],
  Object: [],
  String: [ 'concat' ],
  Number: [],
  Function: [] }

```

`String.prototype.concat` is deprecated: it does exactly what `+` does, which we can already do. So we got `Array.prototype.concat` and `Array.prototype.find`. What can we do with them?

## Functions

`concat()` lets us create, for the first time, longer arrays. `[[]].concat([[]])` is `[[], []]`, and casting that to a string gets us `","`. (This doesn’t help us find new properties.) But `.concat` doesn’t modify our values, and it can never return `null` or anything like that.

Calling `find()` doesn’t help us either: the MDN documentation says

> The `find()` method returns a value in the array, if an element in the array satisfies the provided testing function. Otherwise `undefined` is returned.

Both of those we can already do using indexing.

---

And from here, there’s nowhere else to go. If you doubt anything I’ve written, let me know in the comments.
> 32 votes

# Answer
The 3 functions in Lynn's answer weren't that useless. But the strict mode in ECMAScript 5 foiled my plan.

There is a quirk in the older versions of JavaScript / ECMAScript. If a method is called without an object, the global object `window` is assumed. So we can do this:

```
a = {f:function(){return this}};
a.f();                            // Returns a.
g = a.f;
g();                              // Returns window.
window.g();                       // Also returns window.

```

This is still true for modern browsers, but only if the function isn't defined in strict mode. And all built-in functions (with native code) seemed to be in strict mode. In older browsers when there isn't the strict mode yet, this also works for built-in functions.

Assume we are using older browsers. Then if we want `window`, we have to find a built-in function that returns something containing `this`. Within the only choices we had, there is the function `Array.prototype.concat` doing exactly that. We can test it like this:

```
Number.prototype.concat = Array.prototype.concat;
1..concat(2);                     // Returns [1, 2]
concat = Array.prototype.concat;
window.concat(2);                 // Returns [window, 2]
concat(2)                         // TypeError in modern browsers while
                                  //   returning the same thing in older ones.
concat.bind(window)(2)            // A workaround in modern browsers.

```

So basically it doesn't care whether the object it is called upon is an array (but it must be an object for the least). It just wraps it in an array if not.

If we had `window`, firstly we can get the string `[object Window]` by casting it to a string. With the new character `b`, we can get `r` and `s` using the following two lines respectively, and every character we didn't have in `constructor`:

```
window["atob"]("cuaa")[0]
window["atob"]("cyaa")[0]

```

But the other problem is to remove the object reference from `[].concat`. Wrapping it in an array and extracting doesn't work, because `[].concat` already means `[]["concat"]`. The only way I know which could possibly be constructed using `+[]()` is to return it from a function. `Array.prototype.find` seemed to be able to do that:

```
[[]["concat"]]["find"](x=>1)      // Returns Array.prototype.concat, where x=>1 can
                                  //   be replaced with any always truthy function.

```

We had always truthy functions. `Array.prototype.concat` and `String.prototype.concat` both return truthy if the object is `window`. If we use the later one, we made use of all of the three available functions.

**But,** unfortunately, `Array.prototype.find` doesn't exist in the old browser we are using. At least I didn't find one that works. And I didn't find another way removing the object reference.

The complete code that is testable in modern browsers that returns `r` and `s`, with the `.bind(window)` workaround:

```
[[]["concat"]]["find"](""["concat"].bind(window)).bind(window)()[0]["ato"+([]+[[]["concat"]]["find"](""["concat"].bind(window)).bind(window)()[0])[2]]("cuaa")[0];
[[]["concat"]]["find"](""["concat"].bind(window)).bind(window)()[0]["ato"+([]+[[]["concat"]]["find"](""["concat"].bind(window)).bind(window)()[0])[2]]("cyaa")[0]

```
> 18 votes

---
Tags: restricted-source, javascript
---


title: Iterated Moving Average

text:
# Question
Title: Iterated Moving Average
If we have a list, say the list `[9, 2, 4, 4, 5, 5, 7]`, we can do a moving average across it.

Taking a window of say, 3 elements, each element is replaced by a window like such: `[[9], [9, 2], [9, 2, 4], [2, 4, 4], [4, 4, 5], [4, 5, 5], [5, 5, 7]]`, and then taking averages, we get `[9.0, 5.5, 5.0, 3.3333333333333335, 4.333333333333333, 4.666666666666667, 5.666666666666667]`.

Pretty simple so far. But one thing you can notice about this is that taking a moving average "smooths out" the list. So this begs the question: how many times does one have to take a moving average to make the list "smooth enough"?

# Your task

Given a list of floats, an integer window size, and a float, output how many times one has to take the moving average to get the standard deviation less than that float. For those that don't know, standard deviation measures how un-smooth a set of data is and can be calculated by the following formula:

For example, using our earlier list and a max stddev of `.5`, we get `8` iterations that look like this:

```
[9.0, 5.5, 5.0, 3.3333333333333335, 4.333333333333333, 4.666666666666667, 5.666666666666667]
[9.0, 7.25, 6.5, 4.6111111111111116, 4.2222222222222223, 4.1111111111111107, 4.8888888888888893]
[9.0, 8.125, 7.583333333333333, 6.1203703703703702, 5.1111111111111107, 4.3148148148148149, 4.4074074074074074]
[9.0, 8.5625, 8.2361111111111107, 7.2762345679012341, 6.2716049382716044, 5.1820987654320989, 4.6111111111111107]
[9.0, 8.78125, 8.5995370370370363, 8.024948559670781, 7.2613168724279831, 6.2433127572016458, 5.3549382716049374]
[9.0, 8.890625, 8.7935956790123466, 8.4685785322359397, 7.9619341563786001, 7.1765260631001366, 6.2865226337448554]
[9.0, 8.9453125, 8.8947402263374489, 8.7175997370827627, 8.4080361225422955, 7.8690129172382264, 7.141660951074531]
[9.0, 8.97265625, 8.9466842421124824, 8.8525508211400705, 8.6734586953208357, 8.3315495922877609, 7.8062366636183507]

```

and end with a stdev of `0.40872556490459366`. You just output `8`.

# But there's a catch:

**The answer does not have to be nonnegative!** If the initial list already satisfies the maximum stddev, you have to see how many iterations you can "go backwards" and undo the moving average and still have the list satisfy the max stddev. Since we are truncating the windows for the initial `n` data points and not dropping those, there is enough data to reverse a moving average.

For example, if we start with the list `[9.0, 8.99658203125, 8.9932148677634256, 8.9802599114806494, 8.9515728374598496, 8.8857883675880771, 8.7558358356689627]` (taken from our earlier example with 3 more moving averages done to it) and the same window size and max stddev, you will output `-3` because you can reverse the moving average at most `3` times.

Any reasonable I/O format is fine.

This is so shortest code in **bytes** wins!

# Test Cases

```
[9, 2,  4,  4,  5,  5,  7], 3, .5 -> 8
[9, 2,  4,  4,  5,  5,  7], 3, .25 -> 9
[9.0, 8.99658203125, 8.9932148677634256, 8.9802599114806494, 8.9515728374598496, 8.8857883675880771, 8.7558358356689627], 3, .5 -> -3
[1000, 2,  4,  4,  5,  5,  7], 7, .25 -> 13
[1000.0, 999.98477172851563, 999.96956668760447, 999.95438464397, 999.90890377378616, 999.83353739825293, 999.69923168916694], 4, 7 -> -6

```

# Answer
# Wolfram - 236

Pretty clunky right now, but at least it works.

```
f[x_,w_,c_]:=Module[{l=Length,d=Sqrt@CentralMoment[#,2]&,n,a,b,t,r},n=Length@x;a=Normalize/@LowerTriangularize@Array[Boole[Abs[#1-#2]<w]&,{n,n}]^2;{b,t,r}=If[d@x>c,{a,d@#>c&,l@#-1&},{Inverse@a,d@#<c&,-l@#+2&}];r@NestWhileList[b.#&,x,t]]

```
> 1 votes

---
Tags: code-golf, math, statistics
---


title: Translate Java methods to fields

text:
# Question
Title: Translate Java methods to fields
So, recently, I found myself reformatting my code for Vitsy to using anonymous class instances for commands rather than the normal method approach. For those who don't know, anonymous class instance syntax looks something like this:

```
...
private abstract static class SomeClass {
    public abstract void someMethod();
}

public final SomeClass someField = new Command() {
    public void someMethod() {
        // Some implementation
    }
};
...

```

So what's your job, I hear you asking? Well, it's quite simple.

# The Challenge

Given a class name, its inner method, and string of zero to many conventional methods, turn them into anonymous class instances, retaining the program instructions therein. For formatting purposes, I have labelled the input and output below for what must be considered (anything in `<>` needs to be retained in the output).

### Conventional method syntax

```
<visibility modifier> void <method name>(){<implementation>}

```

### Resulting instance declaration

```
<visibility modifier> final <class name> <method name>=new <class name>(){public void <inner method name>(){<implementation>}};

```

# The Rules

* You may not use any builtins for this challenge (if there are builtins for this, the lang creators have done a bad and they should feel bad).
* You must retain the method name, the visibility modifier (public, private, (nothing), protected) and the implementation.
* Do not worry about proper tabs/formatting. As long as it is Java compile-able, you're fine.
* You may assume that all code inside of `<implementation>` is valid.
* You may assume that there is nothing but methods in the string given.
* Do not translate any methods that are *not* void.
* Do not translate any methods with a parameter.
* Input may be in any convenient format for your language.

# Examples

```
>>> toAnonymousClass("ClassName", "innerMethod", "public void method1(){}")
public final ClassName method1=new ClassName(){public void innerMethod(){}};

```

```
>>> toAnonymousClass("ClassName2", "secondInnerMethod", "private void method2(){return;}protected int method3(){return 4;/*guaranteed to be random*/}")
private final ClassName2 method2=new ClassName2(){public void secondInnerMethod(){return;}};protected int method3(){return 4;/*guaranteed to be random*/}

```

Note here that the void method is translated with the visibility modifier (private) retained, but the int method is not translated as it has a different return type (int).

```
>>> toAnonymousClass("Clazz", "inMethod", "void method4(int param){}")
void method4(int param){}

```

`method4` is not translated, as it accepts a parameter (`int param`).

```
>>> toAnonymousClass("Moar", "again", "void method5(){}")
final Moar method5=new Moar(){public void again(){}};

```

Another example of visibility modifier retainment - if it has no modifier, have no modifier on the output.

Finally, the big test case:

```
>>> toAnonymousClass("Hi", "rand", "private void method2(){return;}protected int method3(){return 4;/*guaranteed to be random*/}public void method1(){}void method4(int param){}void method5(){}")
private final Hi method2=new Hi(){public void rand(){return;}};protected int method3(){return 4;/*guaranteed to be random*/}public final Hi method1=new Hi(){public void rand(){}};void method4(int param){}final Hi method5=new Hi(){public void rand(){}};

```

# Answer
> 3 votes
# Retina, 95 bytes

Byte count assumes ISO 8859-1 encoding.

```
+`^((.+)¶(.+)¶(.+¶)*)(\w+ )?(void )(\w+)(..{.*})
$1$5final $2 $7=new $2(){public $6$3$8};
\w+¶

```

The code contains a trailing newline.

Takes input separated by newlines. Class name on the first line, inner method name on the second line, methods on following lines.
For example:

```
Hi
rand
private void method2(){return;}
protected int method3(){return 4;/*guaranteed to be random*/}
public void method1(){}
void method4(int param){}
void method5(){}

```

Try it online!

---
Tags: code-golf, string, parsing, java
---


# Question
Title: Who said that? 2016 Presidential election
In this challenge, your task is to make write a program **with less than 300 characters** that takes a short paragraph or a few sentences that a candidate has said and output who said it.

**Input**: Can be taken as a parameter to a function, input to a program etc. It will be a short paragraph, properly punctuated.

**Output**: The candidate that you think it is. This could be one of

```
Ben Carson (1)
Ted Cruz (2)
John Kasich (3)
Marco Rubio (4)
Donald Trump (5)
Hillary Clinton (6)
Bernie Sanders (7)

```

I've left off the names of people who have dropped out as of March 1st. You may output the name itself, or, more conveniently, the number that corresponds to the name.

**Scoring:** Your score is the percentage of test cases you get right. Highest score wins. Ties (or perfect scores) are broken by code length as in a code golf.

The test cases can be pulled from:

http://www.presidency.ucsb.edu/debates.php

Click on each debate, both Democrat and Republican that has happened so far (before March 1st). Every paragraph is a test case, unless the "paragraph" is less than 20 characters long.

Here is code that pulls out the test cases from a particular page:

```
var t = $(".tools").parentNode.querySelectorAll("p");
var categ = {}, cur = 0;
for (var i = 0; i < t.length; ++i) {
  var p = t[i], str = p.innerText;
  if (p.querySelector("b")) {
    cur = p.querySelector("b").innerText.replace(':', '');
    str = str.replace(/^.*?:\s/, '');
  }
  str = str.replace(/\[applause\]/g, '')
  if (str.length < 20) continue;
  if (categ[cur] == null) categ[cur] = [];
  categ[cur].push(str);
}

```

You can then do `categ.SANDERS` to get a list of all the paragraphs that Senator Sanders has said.

You can discard anything that isn't said by the candidates listed above (e.g. `categ.BUSH` or `categ.CHRISTIE`).

Here is the file with all the test cases: https://drive.google.com/file/d/0BxMn8--P71I-bDZBS2VZMDdmQ28/view?usp=sharing

The file is organized by candidate

```
CANDIDATE CANDIDATE_LAST_NAME
(empty line)
Series of statements. Each paragraph is separated by (NEW PARAGRAPH)-
(empty line)
CANDIDATE NEXT_CANDIDATE_LAST_NAME
(empty line)
etc.

```

An example partial submission would be:

```
if (/ win | wall | great | beautiful/.test(p)) return 5;
if (/ percent | top one | rigged /.test(p)) return 7;
// etc. for all candidates

```

or

```
var words = p.split(' ');
// majority of words have less than 5 characters
if (words.length - words.filter(a => a.length < 5).length < 4) evidence[5]++;
// at the end
return /* index with the most evidence */

```

Here is a place where you can test javascript solutions: https://jsfiddle.net/prankol57/abfuhxrh/

The code uses the parameter `p` to represent the phrase to classify. Example code that scores around 20% (guessing would get around 11%):

```
if (/ rigged | top | percent | Wall Street /.test(p)) return 'Sanders';
return 'Trump';

```

**Exactly what I'm asking:** Write a program/function in less than 300 characters that takes as input a phrase that a candidate has said and returns as output which candidate said it. Your score is the percentage of test cases you get right. Highest score wins.

Yes, I know that a lot of lines have `[laughter]` or `[cheering]` in them. These will not be removed. At worst, they are extra information you can ignore; at best, they are extra information you can use (e.g. I made this up, but maybe people laughter is evidence that Marco Rubio is speaking). The test cases are as they appear in the text file.

# Answer
# Polyglot, ~18.6%

This works in: Cjam, Pyth, TeaScript, Japt, Seriously, 05AB1E, GolfScript, Jelly, and probably many more.

```
6

```

This outputs Hillary for all inputs. This is because Hillary said the most. While it's not the most ingenious way to do this. It works ¯\\\_(ツ)\_/¯
> 14 votes

# Answer
## Pyth, 34.16% (297 bytes)

```
FNc"7creta
6enato
3ohio
2donal
7 major
6o try t
5tot
5se me
7nai
4m pres
2he ob
3 bala
5jeb
6e aff
5mendous
2mnest
5. we'r
7ave got to
2c ter
4ntur
7 campaign
2flat
5obo
4is pre
4-here'
2note
2m el
4 issue
5, very
6o af
1fact o
6en's
5pany
6he republicans
7 --
4meon
5bea
4ory o
7"bI}tNrzZhNB

```

(note that some lines end in spaces)

I've gone with the simplest option I could think of: check a list of patterns, and as soon as you find a match, output the corresponding candidate. If all else fails, output the most likely candidate from the remainder. After that, it's all about cramming as much data into 300 bytes as possible.

```
FNc"<data>"bI}tNrzZhNB

```

Breakdown:

```
FN                      for N in ...
   "<data>"              the hard-coded data (newline separated)
  c                      split using...
           b             '\n' constant,
            I           if
              tN         tail (all but first char) of current item
             }           is contained within
                rzZ      the input (lowercased),
                        then:
                   hN    print the head (first char) of the current item
                     B   and break out of the loop.

```

So where does that data come from? Well the structure is simply:

```
<candidate_number><phrase>
<candidate_number><phrase>
<etc.>

```

(with an entry at the end with no phrase to act as the final fall-back)

But why those particular items? I wrote a C++ program to analyse the provided dataset (with some manual cleaning of newlines first to make the structure consistent). It looks at all substrings ("tokens") in each quote (1-16 characters), then repeatedly checks for the token which gives the most benefit to go next in the list. Once a pattern is in the list, remove any quotes which match it and repeat (it gets a bit more complicated to keep it fast but that's the basics). The code is probably too long to include here, but I might put it on github later (when I've cleaned it up a little).

I tried a couple of scoring systems. In the end I went with this one:

```
score = (
    + matching_quote_count_for_most_likely_author * 10
    - matching_quote_count_for_other_authors * 7
    - token_length
)

```

A stricter approach of only allowing new items which don't introduce incorrect answers seemed to get stuck at about 20-25%, needing a *lot* of patterns to get higher. This fuzzier approach does much better, and can still reach ~80% accuracy (with 550 items). The submitted score has 38 items, which was the most I could fit in the 300 character limit.

The 34% result actually comes from a test C++ program which performs the same steps. It should match, but I haven't got a Pyth test harness to check it with.

This is the first time I've used Pyth, so I imagine some more bytes could be squeazed out, allowing a bit more data.
> 9 votes

# Answer
# Javascript, 32.87%

299 Characters:

```
function Q(a,b){return p.toLowerCase().split(' ').join('').includes(a)<<b}z=Q('ink',0)+Q('int',1)+Q('ona',2)+Q('rica',3)+Q('twe',4)+Q("we'",5)+Q('youkn',6);return '55472726464727446676664676767676563641233643334456364233336141745116222136477126111113361611262316263122216111673336225611363276'[z]*1

```

**Strategy:**

I did a bruce force search on which word segments to include in a "hash". Then a string lookup happens with that hash in such a way that chooses the most likely candidate for that hash.

**The code itself:**

```
// The Q function checks if a string is present.
// Then left-shifts the true/false result up to e.g. 64,32,16,8,4,2,1
// This way we can combine results into any number 0 to 127.
function Q(a,b){return p.toLowerCase().split(' ').join('').includes(a)<<b}

// Now we check for key string occurrences:
z=Q('ink',0)+Q('int',1)+Q('ona',2)+Q('rica',3)+Q('twe',4)+Q("we'",5)+Q('youkn',6)

// Finally, use this as an index into the lookup string. (Multiply by 1 to convert char to int.)
return '55472726464727446676664676767676563641233643334456364233336141745116222136477126111113361611262316263122216111673336225611363276'[z]*1

```

This is my first ever code golf submission, so suggestions are welcome :)
> 8 votes

# Answer
## Mathematica, 23.7775 %

```
(l=ToLowerCase@#;Ordering[-StringCount[l,#]&/@{"fact","donald"|"obama","done"|"ohio","issue"|"united"|"why"|"world","great"|"many","senator","american"|"believe"|"campaign"|"secretary"|"street"|"wall"},1])[[1]]&

```

It counts the occurences of common keywords unique to each candidate and outputs the number of the candidate with the highest score.

Basically, I found the commonest words of all candidates

```
t = Import["~/Documents/candidate quotes.txt"];
ts = DeleteCases[StringSplit[t, "\n\n"], ""];
tss = Split[ts, StringLength[#2] > 20 &][[{3, 4, 5, 6, 7, 1, 2}]];
names = StringSplit[#][[2]] & /@ tss[[All, 1]];
quotes = StringSplit[#, "(NEXT PARAGRAPH)"] & /@ StringJoin /@ tss[[All, 2 ;;]];
(* remove the 100 commonest english words *)
wd = WikipediaData["Most common words in English", "ArticleWikicode"];
Flatten[StringSplit[StringCases[wd,
  Shortest["{| class=\"wikitable\"" ~~ w__ ~~ "}"] -> w], "\n"]];
common100 =
Alternatives @@ ToLowerCase@DeleteDuplicates@Flatten[StringSplit /@
     StringCases[#,
      "|| " ~~ ("[[" | "") ~~ w : ((WordCharacter | " ") ..) ->
       w] & /@ %];
commonest =
  Commonest[
Flatten[StringSplit[
    StringDelete[ToLowerCase[#],
     PunctuationCharacter | (WordBoundary ~~ (common100) ~~
        WordBoundary)]] & /@ #], 20] & /@ quotes;

```

and chose the common keywords that are unique for each candidate.

```
keywords =
 Alternatives @@@
  Table[Complement[commonest[[n]],
    Union[Flatten[Delete[commonest, n]]]], {n, Length[names]}];

```

After manually deleting some of the keywords, this is the final table:

> ```
> Carson    fact
> Cruz      donald|obama
> Kasich    done|ohio
> Rubio     issue|united|why|world
> Trump     great|many
> Clinton   senator
> Sanders   american|believe|campaign|secretary|street|wall
>
> ```

With these keywords the total function length is 211 characters. I tested the function over all quotes:

```
pairs = Flatten[MapThread[Table[q -> #1, {q, #2}] &, {names, quotes}]];
test[q_ -> n_] := Boole[n === names[[p@q]]] (* here p is my function that outputs the predicted candidate's number *)
Total[ParallelMap[test, pairs]]/Length[pairs] // N

```

which gives an accuracy of 23.7775 %.
> 5 votes

# Answer
# Python, 25.677868%

Arbitrarily picked four different characters that would be used to identify the candidates. Each candidate is given a score factor per character based on a hill climbing search that I ran for a few minutes to end up at 25.68%.

I suppose that this at least proves that the concept is better than picking a candidate blindfolded or just picking Clinton, but I would be interested in seeing someone apply a better search algorithm, both for the factors and for the characters used.

```
w=dict(zip("hr?.",((.847,.491,.821,.54,.744,.765,.234),(.494,.777,.202,.587,.7,.852,.484),(.915,.187,.161,.559,.748,.244,.43),(.11,.013,.628,.974,1.037,.484,.302))))
def f(t,r=(0,0,0,0,0,0,0)):
 s=r
 for c in t:s=map(lambda a,b:a+b,s,w.get(c,r))
 return s.index(max(s))+1

```
> 3 votes

# Answer
# Javascript, TBD

```
a=[...p].reduce((a,b)=>(a<<5)-a+b.charCodeAt(0)|0,0)%1000,alert(a>0?0:1000,a<79?1:a<226?2:a<333?3:a<497?4:a<697?5:a<849?6:7)

```

Converts each string to a hash code, then uses probabilistic methods to determine the speaker. Would be nice if someone with a good setup could test this for me.
> 1 votes

---
Tags: code-challenge, classification, test-battery
---


# Question
Title: Convert a pawn promotion from algebraic to ICCF numeric notation
# Input

A single string, which contains no whitespace, as a command-line argument.

# Output

If the string is not a valid algebraic notation pawn promotion, produce no output and exit. If the string is a valid pawn promotion, convert it to ICCF numeric notation and print the result, followed by a newline.

A valid algebraic notation pawn promotion consists of:

* A letter from a to h indicating the pawn's departure column (known as a "file" in chess);
* Optionally, "x" followed by the file of the pawn's arrival square if it has captured a piece in promoting;
* "1" or "8" depending on which side promoted; and
* "=" followed by one of "Q", "R", "B", "N" to indicate the chosen piece;
* Optionally, "+" to indicate the move was a check or "#" to indicate the move was a checkmate.

An valid ICCF numeric notation pawn promotion consists of:

* Two digits indicating the coordinates of the square from which the pawn departed (the files are numbered and not lettered as in algebraic notation);
* One digit indicating the file on which the pawn arrived, in case it has captured a piece while promoting (this does not officially comply with the standard, but I prefer keeping all moves as 4 digits for simplicity); and
* One digit to indicate the chosen piece: 1 for queen, 2 for rook, 3 for bishop, 4 for knight.

# Examples

```
e1=Q   => 5251
cxd8=B => 3743
axh8=R => no output (a-pawns cannot capture on h-file)
h8=N+  => 8784

```

# Answer
> 1 votes
## JavaScript (ES6), 166 bytes

```
s=>(g=n=>parseInt(m[n][0],19)-9,m=s.match(/^([a-h]x)?([a-h][18]=[QRBN])[+#]?$/))?m[1]&&g(2)+~g(0)&&g(0)+~g(2)?'':''+g(0)+(m[2][1]-1|2)+g(2)+" QRBN".search(m[2][3]):''

```

The validation makes this horribly long. Without validation, it's only 108 bytes:

```
s=>s.replace(/(.x)?(..=.).*/,([a],_,[c,d,,f])=>g(a)+(d-1|2)+g(c)+" QRBN".search(f),g=f=>parseInt(f,19)-9+'')

```

---
Tags: code-golf, chess
---


title: Hungarian alphabetical order

text:
# Question
Title: Hungarian alphabetical order
For those who wish a lot more challenge then the old Spanish alphabetical order, let's take a look at how the Hungarian alphabet is ordered.

> a, á, b, c, cs, d, dz, dzs, e, é, f, g, gy, h, i, í, j, k, l, ly, m, n, ny, o, ó, ö, ő, p, q, r, s, sz, t, ty, u, ú, ü, ű, v, w, x, y, z, zs

actually, `q`, `w`, `x` and `y` are not used in Hungarian words, but they are included for loanwords and foreign names. Foreign accented characters which are not part of the Hungarian alphabet (like `ñ`), have the same priority as the non-accented ones, but we disregard them for this challenge.

# The rules, summarized:

* Digraphs (`cs`, `sz`, etc.) and the trigraph (`dzs`) are considered as they were letters on their own.

> ```
> cudar
> cukor
> cuppant
> csalit
> csata
>
> ```

* If the same digraph or trigraph occurs twice directly after each other in a word, they are written in a simplified way: `ssz` instead of `szsz`, `ddzs` instead of `dzsdzs` but for the alphabetical order the non-simplified order is used. For example `kasza` \< `kaszinó` \< `kassza`, because `kassza` is used as `k`+`a`+`sz`+`sz`+`a` for the sake of ordering. Sometimes you can find the non-contracted version in a word, in case of compound words.

> ```
> kasza
> kaszinó
> kassza
> kaszt
> nagy
> naggyá
> nagygyakorlat
> naggyal
> nagyít
>
> ```

* capitalization doesn't matter, with the exception when the two words would be exactly the same without capitalization, in which case the lower case letter has priority

> ```
> jácint
> Jácint
> Zoltán
> zongora
>
> ```

* The short and long versions of accented vowels have the same priority (`a - á`, `e -é`, `i - í`, `o - ó`, `ö - ő`, `u - ú` `ü - ű`), with a single exception: if the two words would otherwise be exactly the same, the short vowel has priority over the long vowel. Note, that the vowels with umlaut (`ö` and `ü`) are completely different characters from `o` and `u`.

> ```
> Eger
> egér
> író
> iroda
> irónia
> kerek
> kerék
> kérek
> szúr
> szül
>
> ```

* Hyphens or spaces (for example, in compound words, names, etc.) are completely ignored

> ```
> márvány
> márványkő
> márvány sírkő
> Márvány-tenger
> márványtömb
>
> ```

# The task

Your program/function receives strings, composed of characters from the Hungarian alphabet (both lower- and upper-case), but a string might contain spaces or hyphens. For simplicity's sake, the minus sign (ASCII 45) can be used as a hyphen. Note that some characters (like the `ő`) are not part of ASCII. You can use any encoding you wish, if it supports all the required characters.

You have to order the lines correctly and display/return the result.

You can use any randomly ordered subset of the above examples for testing.

**EDIT:**

Please don't use any built-in or other way which already knows the Hungarian alphabetical ordering by itself. It would make the competition pointless, and take all the challenge from finding the best regular expression or the best code golfing tricks.

**EDIT2:**

To clear a clarification asked by isaacg: "two strings that only differ by capitalization and long vs. short vowels, but differs in both ways" : Although no rule in the official document explicitly addresses this question, an example found within points to the length of the vowel having more importance than the capitalization.

# Answer
> 4 votes
## Perl, 250

Includes +11 for `-Mutf8 -CS`.

```
use Unicode::Normalize;$r="(?=cs|zs|dz|sz|[glnt]y)";print map/\PC*
/g,sort map{$d=$_;s/d\Kd(zs)|(.)\K$r\2(.)/\L$+\E$&/gi;s/d\Kzs/~$&/gi;s/$r.\K./~$&/gi;s/(\p{Ll}*)(\w?)\s*-*/\U$1\L$2/g;$c=$_;$b=$_=NFD lc;y/̈̋/~~/d;join$;,$_,$b,$c,$d}<>

```

Uses the **decorate-sort-undecorate** idiom (AKA Schwartzian Transform), and multilevel sorting, where the levels are:

* L1: compare base letters, ignore diacritics, case, and some punctuation.
* L2: compare base letters and diacritics, ignore case and some punctuation.
* L3: compare base letters, diacritics and case, ignore some punctuation.
* Ln: tie-breaking byte-level comparison.

Internally,  (ASCII 0x1C Field Separator — whose value is less than any character in the alphabet for this challenge) is used as a level separator.

This implementation has many limitations, amongst them:

* No support for foreign characters.
* Cannot disambiguate between contracted geminated (long) digraphs/trigraphs, and consonant+digraph/trigraph, e.g: *könnyű* should collate as *\<k\>\<ö\>\<ny\>\<ny\>\<ű\>*, while *tizennyolc* should collate as *\<t\>\\<z\>\<e\>\<n\>\<ny\>\<o\>\<l\>\<c\>*; *házszám* 'address = house (ház) number (szám)' should collate as *\<h\>\<á\>\<z\>\<sz\>\<á\>\<m\>* and not as **\<h\>\<á\>\<zs\>\<z\>\<á\>\<m\>*.
* Collation for contracted long digraphs is not that consistent (but it is stable): we disambiguate at the identical level (*ssz \<n szsz, ..., zszs \<n zzs* ); glibc collates the short forms before the full forms (*ssz \< szsz, ..., zzs \< zszs* ), ICU collates the long forms before the short forms starting at L3 *Case and Variants* (*szsz \<3 ssz, ..., zszs \<3 zzs* )

Expanded version:

```
use Unicode::Normalize;

$r="(?=cs|zs|dz|sz|[glnt]y)";   # look-ahead for digraphs

print map/\PC*\n/g,             # undecorate
  sort                          # sort
  map{                          # decorate

          $d=$_;                # Ln: identical level

          # expand contracted digraphs and trigraphs
          s/d\Kd(zs)|(.)\K$r\2(.)/\L$+\E$&/gi;

          # transform digraphs and trigraphs so they
          #  sort correctly
          s/d\Kzs/~$&/gi;s/$r.\K./~$&/gi;

          # swap case, so lower sorts before upper
          # also, get rid of space, hyphen, and newline
          s/(\p{Ll}*)(\w?)\s*-*/\U$1\L$2/g;

          $c=$_;                # L3: Case

          $b=$_=NFD lc;         # L2: Diacritics

          # transform öő|üű so they sort correctly
          # ignore diacritics (acute) at this level
          y/\x{308}\x{30b}\x{301}/~~/d;

                                # L1: Base characters
          join$;,$_,$b,$c,$d
  }<>

```

---

†. Some well-known multi-level collation algorithms are the *Unicode Collation Algorithm* (UCA, Unicode UTS#10), ISO 14651 (available at the ISO ITTF site) the LC\_COLLATE parts at ISO TR 30112 (draft available at the ISO/IEC JTC1/SC35/WG5 home) which obsoletes ISO/IEC TR 14652 (available at the ISO/IEC JTC1/SC22/WG20 home) and LC\_COLLATE at POSIX.

‡. Doing this correctly would require a dictionary. ICU treats weirdly capitalized groups as non-contractions/non-digraphs/non-trigraphs, e.g: *ccS \<3 CcS \<3 c**Cs** \<3 c**CS** \<3 C**Cs** \<3 cS \<3 **cs** \<3 **Cs** \<3 **CS** \<3 **ccs** \<3 **Ccs** \<3 **CCS***

# Answer
> 6 votes
# Java 8, 742 bytes

Could reduce by another 3 bytes naming the function `s` instead of `sort` or another 16 bytes if not counting class-definition.

```
public class H{String d="cs|dzs?|gy|ly|sz|ty|zs";void sort(java.util.List<String>l){l.sort((a,b)->{String o="-a-á-b-cs-dzs-e-é-f-gy-h-i-í-j-k-ly-m-ny-o-ó-ö-ő-p-q-r-sz-ty-u-ú-ü-ű-v-w-x-y-zs-";int i=c(r(a),r(b),r(o));return i!=0?i:(i=c(a,b,o))!=0?i:b.charAt(0)-a.charAt(0);});}String r(String a){for(int i=0;i<8;i++)a=a.toLowerCase().replace("ááéíóőúű".charAt(i),"aaeioöuü".charAt(i));return a;}int c(String a,String b,String o){a=n(a);b=n(b);while(!"".equals(a+b)){int i=p(a,o),j=p(b,o);if(i!=j)return i-j;a=a.substring(i%4);b=b.substring(j%4);}return 0;}int p(String a,String o){a=(a+1).replaceAll("("+d+"|.).*","-$1");return o.indexOf(a)*4+a.length()-1;}String n(String a){return a.toLowerCase().replaceAll("(.)(?=\\1)("+d+")| |-","$2$2");}}

```

Can be used like this:

```
new H().sort(list);

```

Test-suite:

```
public static void main(String[] args) {
    test(Arrays.asList("cudar", "cukor", "cuppant", "csalit", "csata"));
    test(Arrays.asList("kasza", "kaszinó", "kassza", "kaszt", "nagy", "naggyá", "nagygyakorlat", "naggyal",
            "nagyít"));
    test(Arrays.asList("jácint", "Jácint", "Zoltán", "zongora"));
    test(Arrays.asList("Eger", "egér", "író", "iroda", "irónia", "kerek", "kerék", "kérek", "szúr", "szül"));
    test(Arrays.asList("márvány", "márványkő", "márvány sírkő", "Márvány-tenger", "márványtömb"));
}

private static void test(final List<String> input) {
    final ArrayList<String> random = randomize(input);
    System.out.print(input + " -> " + random);
    new H().sort(random);
    System.out.println(" -> " + random + " -> " + input.equals(random));
}

private static ArrayList<String> randomize(final List<String> input) {
    final ArrayList<String> temp = new ArrayList<>(input);
    final ArrayList<String> randomOrder = new ArrayList<>(input.size());
    final Random r = new Random();
    for (int i = 0; i < input.size(); i++) {
        randomOrder.add(temp.remove(r.nextInt(temp.size())));
    }
    return randomOrder;
}

```

yielding

```
[cudar, cukor, cuppant, csalit, csata] -> [csata, cudar, cuppant, csalit, cukor] -> [cudar, cukor, cuppant, csalit, csata] -> true
[kasza, kaszinó, kassza, kaszt, nagy, naggyá, nagygyakorlat, naggyal, nagyít] -> [naggyá, kassza, kaszinó, nagygyakorlat, nagyít, nagy, kaszt, kasza, naggyal] -> [kasza, kaszinó, kassza, kaszt, nagy, naggyá, nagygyakorlat, naggyal, nagyít] -> true
[jácint, Jácint, Zoltán, zongora] -> [Zoltán, jácint, zongora, Jácint] -> [jácint, Jácint, Zoltán, zongora] -> true
[Eger, egér, író, iroda, irónia, kerek, kerék, kérek, szúr, szül] -> [egér, Eger, kerék, iroda, író, kerek, kérek, szúr, irónia, szül] -> [Eger, egér, író, iroda, irónia, kerek, kerék, kérek, szúr, szül] -> true
[márvány, márványkő, márvány sírkő, Márvány-tenger, márványtömb] -> [márványtömb, márványkő, Márvány-tenger, márvány sírkő, márvány] -> [márvány, márványkő, márvány sírkő, Márvány-tenger, márványtömb] -> true

```

Ungolfed:

```
public class HungarianOrder {

    String d = "cs|dzs?|gy|ly|sz|ty|zs";

    void sort(java.util.List<String> l) {
        l.sort((a, b) -> {
            String o = "-a-á-b-cs-dzs-e-é-f-gy-h-i-í-j-k-ly-m-ny-o-ó-ö-ő-p-q-r-sz-ty-u-ú-ü-ű-v-w-x-y-zs-";
            int i = c(r(a), r(b), r(o));
            return i != 0 ? i
                    : (i = c(a, b, o)) != 0 ? i
                            : b.charAt(0) - a.charAt(0);
        });
    }

    // toLower + remove long accent
    String r(String a) {
        for (int i = 0; i < 8; i++)
            a = a.toLowerCase().replace("ááéíóőúű".charAt(i), "aaeioöuü".charAt(i));
        return a;
    }

    // iterate over a and b comparing positions of chars in o
    int c(String a, String b, String o) {
        a = n(a);
        b = n(b);
        while (!"".equals(a + b)) {
            int i = p(a, o), j = p(b, o);
            if (i != j)
                return i - j;
            a = a.substring(i % 4);
            b = b.substring(j % 4);
        }
        return 0;
    }

    // find index in o, then looking if following characters match
    // return is index * 4 + length of match; if String is empty or first character is unknown -1 is returned
    int p(String a, String o) {
        a = (a+1).replaceAll("("+d+"|.).*", "-$1");
        return o.indexOf(a) * 4 + a.length() - 1;
    }

    // expand ddz -> dzdz and such
    String n(String a) {
        return a.toLowerCase().replaceAll("(.)(?=\\1)("+ d +")| |-", "$2$2");
    }
}

```

I am using Java's `List`-type and the `order()`-function of it, but the comparator is all mine.

# Answer
> 3 votes
# Python 3, 70

Saved 8 bytes thanks to shooqie.

I love Python. :D

Expects a list of strings.

```
from locale import*;setlocale(0,'hu')
f=lambda x:sorted(x,key=strxfrm)

```

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


title: Make some noise-cancelling headphones

text:
# Question
Title: Make some noise-cancelling headphones
I am in desperate need of some ear defenders, so I can program in peace. Unfortunately, I don't have ear defenders. But I do have a pair of headphones, a microphone and a microcontroller, so I thought I'd make some noise-cancelling headphones.

However, there is one tiny problem. I can't program in noisy environments! So you'll need to write the code for me.

## Task

Given a constant noisy input, output the input's "complement"; a value that will completely cancel out the input value (`0x00` cancels `0xff`, `0x7f` cancels `0x80`). Because the headphones block *some* noise, also take a value as input that you will divide the "complement" by, using the following algorithm: `if (c < 0x80) ceil ( 0x7f - ( (0x7f - c) / n ) ) else floor ( ( (c - 0x80) / n ) + 0x80 )` where `c` is the "complement" and `n` is the value to divide by. (If the value exceeds the byte range, it should be clipped to `0` or `255`.)

The input will always be a sequence of bytes, via `stdin` or function parameter (see bonuses) but the modifier can be given via any input method. The output sequence should be output via `stdout` or as a return value (see bonuses). The output should be a series of bytes (e.g. `$.d<±3Ç/ó¢`), or a set of numbers representing those bytes (e.g. `217 135 21 43 126 219`).

Oh, and your code will have to be short, because there isn't much flash memory on the microcontroller (4096 bytes; and I need to fit on drivers too!).

## Examples

In these examples, I have used hexadecimal codes to represent bytes, because `DEL` and `NULL` are somewhat hard to read. The actual input and output should be done as a string of bytes or as a byte-stream.

Modifier: `2`
Input: `0x00 0x10 0xe0` ...
Output: `0xbf 0xb7 0x4f` ...

Modifier: `128` Input: `0x00 0x10 0xe0` ...
Output: `0x80 0x80 0x7f` ...

Modifier: `0.5`
Input: `0x00 0x10 0xe0` ...
Output: `0xff 0xff 0x00` ...

Your code should cope with much longer inputs than this; these are just examples.

## Bonuses

To add a bonus to a score, use the following formula: `s * (100% - b)` where `s` is the current score and `b` is the bonus as a percentage.

* 1% If you output as raw bytes.
* 5% If there's no `stdin` pipe (or byte input), get the bytes straight from the microphone, such as with `parec`.
* 5% If you output to the speakers as well as returning / outputting to `stdout`.

# Answer
# Pyth, ~~54~~ 51 bytes

```
J128m.MZ,0h.mb,255?<dJ.E-tJc-tJdQs+c-dJQJm-255id16E

```

Try it here!

## Explanation

```
J128m.MZ,0h.mb,255?<dJ.E-tJc-tJdQs+c-dJQJm-255id16E   # Q = modifier, E = input list

J128                                                  # set J to 128
                                         m        E   # map each input d
                                              id16    # convert to decimal
                                          -255        # get the complement
    m                                                 # map each complement d
                  ?<dj                                # if d < 128
                      .E-tJc-tJdQ                     # use the ceil-formula
                                 s+c-dJQJ             # otherwise use the floor-formular
          .mb,255                                     # minimum of the result and 255
    .MZ,0h                                            # maximum of the result and 0

```
> 2 votes

---
Tags: code-golf, audio
---


title: Golf English – using contractions

text:
# Question
Title: Golf English – using contractions
I have not laughed as much from Stack Exchange content as I have from this. I think you all will enjoy this challenge, as it is inspired by what is over there.

You will write a function or program that is code-golf, i.e. it would have to be as short as you can make it.

Given a text, return (both by any means) the text where you will have contracted as many words as possible according this table.

You shall not pull information from the table, rather you must have all necessary information included in your code.

All default rules ought not to be broken as we will not have any unfair competition.

You need not consider text if it is not capitalized as in the table, so you must not convert *`you all WOULD not have`* or *`You all would not have`* to *`y'all'dn't've`*.

You may match just the good old apostrophe (U+0027) or any nice ones; whatever you want to.

# Example input above ↑ and corresponding output below ↓

I'ven't laughed as much from StackExchange content as I've from this. I think y'all'll enjoy this challenge, as 'tis inspired by what's over there.

You'll write a function or program that's code-golf, i.e. it'd've to be as short as you can make it.

Given a text, return (both by any means) the text where you'll have contracted as many words as possible according this table.

You shan't pull information from the table, rather you must've all necessary information included in your code.

All default rules oughtn't to be broken as we'lln't've any unfair competition.

You needn't consider text if it'sn't capitalized as in the table, so you mustn't convert *`you all WOULD not have`* or *`You all would not have`* to *`y'all'dn't've`*.

You may match just the good ol’ apostrophe (U+0027) or any nice ones; whatever you wanna.

# Answer
## Perl, ~~3429~~ 1095 bytes

Compressed the text.

uuencoded version of script

```
@a=split('!',uncompress(<DATA>.<DATA>));while(<>){chomp;$l=$_;for$d(@a){chomp $d;($x,$y)=split(/,/,$d);if($l=~m/$y/){$l=~s/$y/$x/g}}print "$l\n"}
__DATA__
x<9c>uVK<b2><a3>0^L<dc><e7>^Tdņ<8b>p^Lϋ'<b8>^FpUL<e2><e2><f6><a3><af>-<9b><bc>^Mv<b7>d<a9>%<c4><c7>m<fb>xLn^[<f6>x<dc><ee><ee><e5>      <be><<e3>^_<87>^P<ae>^B<e3>{}<8c>^_?<d1>fX<dc><c7>^K    n<95>^G<df><ce>V^M<b7><fb>#^P^C<8b><e0><e8>^S^Q<b0>*Ø<d1>3<9e>1<ec><cf>ሷ<fb><e2>4^[<ec>L.<e6><95>D<9c>^X'<c5>^_<cf><c4>G<aa>[<fc><f8><98>^V^O<e7>^_^L(<a8>^_<b2><a9>N}<88>#<b8><ae><88><d3><e2><d6><d5><e0>^\^DrR^L<9a>J<96>$D<e3>^P:{@s̘.<e6>^A<da>c<a1><a6>^G^B<f3>!<c3>      <81>H<84>9|<81><a1>A<d8><db><db>}<86>`3W;s<b1>sS+<db>%Ռ<89>f<ad>S^P'<9d><c7>^M<f6>n<c3>^]<f7>t^^jWg^N<cc>!^CU<ab><a5><86>^C2<84><83>% @W<c0>V<84><fa><88>^L<80><90>^Y<b0>^H)<98><a5>^@<e4>^LGm8rB4^N<aa>b<f5><e8>^@<d7><e1>^M^N<9b>^[<dd>6m<ee><81><f5>l<e1><b9>^\2]<b4>7<f3><a5><b6>j^P<ae>:<8b><e3>;<b1>^_<ac><e2>^F;<f2>B<86><9d>v<ef>i\qe<a7>8<fe><ac><f1><e7><df>^T<ff>^N^G<8c>^C^A`<d7>q<8a>؈<f8><96><f4><b4><e1>#<d0>^Sd<a8>5<ca><e0><bc>&^]<ea><a4>S<9d><ba><b1><ae>~<d2><e7>ē<9c><ea>h^[<86>{<9d>tx<93>^]ob<95><ea><9c><c2><c5>'<90><8b><be>FxW$<99>^W<89>Xj<f7><8b>՘<80><8d><9b><ff>^S^_'<d6>"[)<bc>^X(<9a>ښ^V|9<ab><cd>(&<95><d3>^F0<b2><d4>^S;<a5>N<da><c0>o6i<a5><9a><92>՝<be>^[<82><f0>q<f7><a2>^Uv<b5>L<a2>U$Z<fa>"<db>s<a6>D4<88>6<b4><18><a5><8a>FC2^Z<d2>7Z^E^_^K<bc><b3>%5<ed><ab>h1<a9>l<b6><f6>¯<e7><8d>x6<8a>H<b6><9a>^B<be>Xk^QlL<8d><ae><f4><9b>        <8b>9^VG<af>^]\%^NQ<89>^Y:m     ><e3>_<d8>wZ<b9>p<a1><b0>hfmm<bf>^T<ca><e4>K<fd>Ử\*<81>SOI▒%w^]g<a2><fb>Q.^^<9d>Y-<dd>A{<c8><f0>ƻ^KU<bf>^P<e4>A<ed><f4><e5>a^Q<ae>^Q^X<f8><ad>fS<ad>k^S^X=~<89><ab><b7> <a8><97>^D<d4><f6><9d>6Fw\<93>s<ce><f1>^H<89>?^]<b8>ώ@Ɩg<87>^?%p=<e8><a7>$<f3><cf>Fַb<c6>[<99><e5><be>#<90>²<bf><f4>=<cb>H<e4>v^^4<82>t5<fb>ڝ<ec><fb>ސUy<82>/r<a3><8a>^A<f1>!<f5><e5><9f><\E<ac><8c>7<ae>z?^ZN<a2>"<85>q<91><e2><c8><<f3><b9><^D<96>^H^]<e6>^?^Pb>^ϐ<a0>^E<f4><a0><93><df>5J%8?^Z<b4><f2><9f>Q<96><89><cf><f5>!h<a9>pa4?r$<80>O<b2><82>H<e1><a3><dc>/<84><ec>^S<db>{R<fc><f4><ae>^@AM<8a><b5>o<85>ѮEnZԞE<92>^TU<b5><c2> H<f2>jƓÝ%<dc><c9><e1>N^Mw<d2><f9>S<c3>)<a4>pQ'<a6>^[^W<fa><c1>V^R<b1>|<90><9b>b<cd><e7><f8>2<b3><fa>16o<89>s<84>^FLg|^O<d4>^H<82>e^L<bf>x]]<ac><99>^F<bf>ڋl<b5>6<a7><f5><95>И/<e7><eb>S<af>^<8d>^]<e8><f8><86>[<8d>^\<8d>^DA<cd><d3>(,~2^RHH4^Y      <c3><d4><d8>/<91><fc><f2><8a><8b>F},<91><ae>ҍb<e2>^K    <ff><92><91>z\<ba><fa>^_<bf><fc><b5><8f>

perl -MCompress::Zlib script.pl <sample.txt
You will write a function or program that's code-golf, i.e. it'd've to be as short as you can make it.
Given a text, return (both by any means) the text where you'll have contracted as many words as possible according this table.
You shan't pull information from the table, rather you must've all necessary information included in your code.
All default rules oughtn't to be broken as we'lln't've any unfair competition.
You needn't consider text if 'tisn't capitalized as in the table, so you mustn't convert y'all WOULD not've or You all wouldn't've to y'all'dn't've.
You may match just the good ol' apostrophe (U+0027) or any nice ones; whatever you wanna.

```
> 5 votes

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