title: Write a compact spelling checker

text:
# Question
Title: Write a compact spelling checker
Here is a list of 1000 basic English words. Yes, I'm aware that there are only 997 words in the list! It was taken from Wiktionary so blame them!

Your task is to write a program that accepts a word and returns `TRUE` or `FALSE` (or `0` or `1`) depending on whether the word is in the list or not. You must use the spelling as it appears in the list, so it is `colour`, not `color` (sorry Americans!). As far as I am aware, there is only one word in the list that uses a capital letter: `I`. This means that `i` (Roman numeral for 1) should return `FALSE`. All other words may be spelt with an initial capital letter, i.e. `Colour` should return `TRUE`.

Rules for letter cases: Your program should return `TRUE` for any word that has just the first letter capitalised. If the entire word is capitalised, e.g. `COLOUR` it's your choice whether it is correct or not, as long as it is found in the word list in its lowercase form. If you accept `COLOUR` you must accept all other words entirely in capitals. If you don't accept `COLOUR` you must not accept any other word entirely in capitals. Any other mixture of lower and upper case e.g. `coLoUR` should return `FALSE`. As stated above only `I` is correct, not `i`. Briefly, both lowercase `colour` and titlecase `Colour` must be `TRUE`, uppercase `COLOUR` may be either `TRUE` or `FALSE` and any other mixed case must be `FALSE`.

Standard rules apply, you may not use external libraries or spelling libraries built into your language, etc. If you use any external files, such as reading the word list via the internet, you must include that number of bytes in your score. Reading the uncompressed word list will add 5942 to your score.

Your code must be at least 95% accurate, including both false positives and false negatives. So if you have 30 false positives and 20 false negatives there are 50 errors in total which is acceptable (even though there are only 997 words, 94.98% accurate if you're being pedantic). One more false positive or false negative invalidates your code. You must post all the errors for verification. Don't make people guess where the errors are!

Shortest code in bytes wins. Add 10 points for each error. Please post a non-golfed version of your code as well so that other people can try to break it / verify that it works. If you can provide a link to a working online version that would be great! The list is 5942 bytes long so ideally you want your code to be shorter than that.

Start your post with the following:

### \<Language\> - Bytes: \<num\>, False +ves: \<num\>, False -ves: \<num\> = Score: \<num\>

Score = bytes + 10 × (false\_pos + false\_neg)

I might provide a list of false positives to check against as people post answers.

# Answer
### Python - Bytes: 4411, False +ves: 0, False -ves: 0 = Score: 4411

```
import base64,zlib,sys;T=eval(zlib.decompress(base64.b64decode("[encoded data, 4228 characters]")));t=T;f=1
for c in sys.argv[1]:
 C=c.lower()
 if c in t:t=t[c]
 elif f and C in t:f=0;t=t[C]
 else:t={}
print""in t

```

This is a python program that expects one command line argument, the `word`. From the list of words I constructed a trie, zlib'ed the argument and finally encoded it with base64. If the word is in the trie, the program prints `True`, otherwise it prints `False`. I wanted to create a spell checker that has 100% accuracy.

I could substantially decrease the number of characters, by not encoding the zlib'ed string (specifically, zlib'ed string is 1113 characters shorter than base 64 encoded), but I wanted to have a code that you can copy/paste directly.

### Examples

```
$python check.py colour
True

$python check.py Colour
True

$python check.py coLoUr
False

$python check.py color
False

$python check.py Color
False

$python check.py I
True

$python check.py i
False

```

The trie is traversed with characters of the `word`, each time getting a new trie from the key of current character. If the word is in the trie, then a `""` must be present in the final trie.

### Ungolfed version

```
import base64, zlib, sys

TRIE = eval(zlib.decompress(base64.b64decode("[encoded data, 4228 characters]")))

trie = TRIE
first = True
for character in sys.argv[1]:
    CHARACTER = character.lower()
    if character in trie:
        trie = trie[character]
    elif first and CHARACTER in trie:
        first = False
        trie = trie[CHARACTER]
    else:
        print False
if "" not in trie:
    print False
print True

```

### Construction of base 64 encoded, zlib'ed trie

```
f = file("dictionary","r")
END = ""
TRIE = {}

def addWord(word):
    trie = TRIE
    for character in word:
        trie = trie.setdefault(character, {})
    trie.setdefault(END, 0)

for line in f.readlines():
    l = line.replace("\n", "")
    addWord(l)

import zlib, base64
compressed = zlib.compress(str(TRIE).replace(" ", ""), 9)
print base64.b64encode(compressed)

```
> 3 votes

# Answer
## PHP - Bytes : ~~2892~~ 2811, False +ves: 0, False -ves: 0 = Score: ~~2892~~ 2811

```
<?php
preg_match_all('/(\D*)(\d)/i',bzdecompress(base64_decode('QlpoOTFBWSZTWaILilgAAfKNgH/gACA////wYAhL71trq71ortD2Kw3J6ZeWvTF3c6Iqf6JkTCYTSNA0jU0Ip4AQJpJptVPE1MAip+DRU/VPTRNDQAAGqexCJpMp6mlPUepsp6jJjDIwJpg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DKNgdEYwAuSjJFIZosePcg8l+I/rFOfs5khIuUHYpBlo1R8oyZr6eth30STIGQitOBYiKgl7oGd0RWdvw3kx8lCxsse70IUvx14HjKbIEusdZIjdQN9TS72jt3ZoRSotFa4ky3iT6Hepk/RErposPd69dxfRk0Pw499oGe/mJGLImBf9JPyfKVBjtVnl0BxSSCzsJ+fDGhARYHs0pOb9Myi9Ig7+5tTbno8Q/zlaIcngPBqAKi4FRMwPy6uqcoIIyCoNjNkDb5dnqoW7pWqqC7ODP95zHrUUgQTchXQdmj3cPWQKbATBPwRrs/8LuSKcKEhRBcUsA')),$b,2);$w='';foreach($b as$p){$l[]=strrev($w.=$p[1]);$w=substr($w,0,strlen($w)-$p[2]);}echo 1-!array_intersect([$argv[1],lcfirst($argv[1])],$l);

```

Ungolfed (slightly):

```
<?php
$z='QlpoOTFBWSZTWaILilgAAfKNgH/gACA////wYAhL71trq71ortD2Kw3J6ZeWvTF3c6Iqf6JkTCYTSNA0jU0Ip4AQJpJptVPE1MAip+DRU/VPTRNDQAAGqexCJpMp6mlPUepsp6jJjDIwJpgTIYmjAanoCBMpMJ6mptQMj1jt+3vz889/XMld2kXPhiMgQJwBAfi+ycsvZ/qwWRmQhcQKUtRAd1Ml+2zpBLJ53aoUhCPzfLzu5B1M9wnUYtgN3XbcTTBwP2QBBNCNgoD1wqkkr1osQpQHMkCUltCBliCKmXjaYDDfmTdJGizbGn/jWpIrDGpStVeTiOoFn8ASoSseHaSYC7Iau2KMXZxZB2YWpMqFlT2CSKmkxEJM0V8ag9ed+DsN1gWzRpewuHHh4x4i3rjLGY3I/WC4K6a3BuLkQ69xFrEiu9q1OzrY6cFKZVAxSSz2kdqQkN6S7rrFy1jY9434MVTgwnycz59BHrxqJuDrqSSuplpG3a2b7wzptRP6DFxkZtHRNEk0Kvylx7uMCR5PfcixfGSLa9vGX0uhpyJ8yr5O9dVp/rdzjGxl1VknpS1qNRj7DXd7j2jB98PSQbMCRNp6WowFajA48z07uAXxnHJBfe+u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CaIYXwi0XNMieiCMyhpeN9oWDWGKUz99dVZCM3ZA50AwIDDYHnCFY1TKkFgRgz1OJsVAZCTaGXtj8qUlPLafUxT5xFqY2QclwVpdKISdQiLFG2gTZUiwr8a+vghqNxC8eAtvrlyFFYtP1dvjd9Zj5zEFF9jSSMsRHGRTIrePWqiaF5n8Ph1+mukR8L2WNnxb/sYDuSG5ZHlNMgPaCzf4+mddOSwIq/tm8ozhGUPWmCpdcyx49uLc4HWJHrQ0gAxdxNY8uwCOzp6PuNEkRw3utTsw3odJwKVJ9bcb0EHheguSbpLhgx5k1qlBB6STiAsxkcXG3hDyigqo8morvnIL1mUSyoSmbFFBDTLqA92RaF9+sZsd8ITAzAYpJRaRbTa1CiPBaRAoKWeOIstgil1kEE1O1aC1QHUUJoJ0JSLBHBchSDDj2ZVDjGBG8PNCJeBrM01eV6IfXwRjV8HmFxiYfLPR9FzRsnQZNGItcSimQWNDA6YGL1ouYsyduqOwjjh27I40WU0vloEn6dKRMOjDxl4QiaRLW4EeLP8ycLxC49pbri5Zs17TZSJCkPfTgH7iNPiqgcZmDKNgdEYwAuSjJFIZosePcg8l+I/rFOfs5khIuUHYpBlo1R8oyZr6eth30STIGQitOBYiKgl7oGd0RWdvw3kx8lCxsse70IUvx14HjKbIEusdZIjdQN9TS72jt3ZoRSotFa4ky3iT6Hepk/RErposPd69dxfRk0Pw499oGe/mJGLImBf9JPyfKVBjtVnl0BxSSCzsJ+fDGhARYHs0pOb9Myi9Ig7+5tTbno8Q/zlaIcngPBqAKi4FRMwPy6uqcoIIyCoNjNkDb5dnqoW7pWqqC7ODP95zHrUUgQTchXQdmj3cPWQKbATBPwRrs/8LuSKcKEhRBcUsA';
preg_match_all('/(\D*)(\d)/',bzdecompress(base64_decode($z)),$b,PREG_SET_ORDER);
$w='';
foreach($b as$p){
  $l[]=strrev($w.=$p[1]);
  $w=substr($w,0,strlen($w)-$p[2]);
}
echo 1-!array_intersect([$argv[1],lcfirst($argv[1])],$l);

```

### Old data

I have applied my own compression before compressing with bzip2 and encoding as base64. My compression reduces the data from 5942 bytes to 3662 bytes, then bzip2 gets that down to 1997 bytes and base64 increases it to 2664 bytes. bzip2 without my compression gets it down to 2852.

The data used to look like this:

```
a0bout2ve4cross4t0ive1ity7dd2

```

Which translates into:

```
a
about
above
across
act
active
activity
add

```

etc. The example 29 bytes expand into 45 bytes.

### New data

I reduced the compressed size of the data by reversing it! I saved 64 bytes in the base64 representation and only added 8 bytes to undo the reversal!

Then I just use `in_array()` to find the match in each letter case. I have chosen to save a few bytes by not checking for all uppercase words.

And, by the way, if this should somehow have the lowest score it won't be selected as the winner.
> 2 votes

# Answer
### Python 2 - Bytes: 3170, False +ves: 0, False -ves: 0 = Score: 3170

```
i=raw_input()
print[e for e in'eJw1lwF64yoMhK+iqxGbOGww+AFO6uXy7x+5+7W209QIaaQZiWDhUc8x6ydaWFrtfY450ifqlsZlYV0tPFtI6xyxWdhCKjPOOltkReKbnGctfFM2vgvrNb/h6hb2Wc8yLJS5zq1ds45XbLN/uV3z0oprvBKLrpF2TB1HDG0emY8tzhjmPvdLNtbZ3B8Lfb4t4F5YeGJ8jnMvFtjPHuFxzR7n8tZ2E5/Ke/Z35J2XPeLEDayHc6TnmSc+rHNtte7zFbD9rGy5ERgOrVqc63f2tMY+OxYIfI5vjMUeiSBxaLx0reESWtEeGZdmjOusPGvl+Z0n39fA27gMKgmXQOnNesy1MlvjJQyNkYlu4Ms3z59JLC2U5TXlGHhyvXU9A67EAIozrRu37TWm8LuBrd8yz06sZ8qrzPdUItnkR05i9bIlvKNDM8vKnsdsHkzkV6i0mLWiNUeSwJaXLbGMFlgyTr5ug+zb8iLvILoIVjwJXY4exM+HtLxjmfKBq/GxLjWHQeSJ92vt0ZbUFoWMQzmwYfzgfyRDKoC0P24QQUaRdUpg1UUtaG19PmMUpGQrK1dxGaTrbJOFe5w7uRzhgf19r2Xuh6ppp6yGHqdSWdY0Ev8rI5Uz8mg1KzHcKcI7N0XPJtugXhT2VMFxAc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iGHmQ07RbfvonGWCZtg3pPGLpsR7l/QIU+aIebfcL/X69krxsNbVR/H3PVLlpe7xzgOK9X35LJf/oZkwktS4JLIypakHNfBD2bw7ssir+Xh4A1Fbk/jpFz7at2rOLH4cXr236OSqCgSgb3PDFPalLtudhH7gtque0GTTKPyXA5b9rfV/GAUQyw=='.decode('base64').decode('zlib').split()if e[:2]==i[:1].lower()+i[1:2]and i[2:]in e[2:].split('{')]>[]or'I'==i

```

The word is taken from standard input, and `True` or `False` is printed in response. The code part isn't very golfed yet. Here's a (somewhat) more readable version:

```
i = raw_input()
d = 'eJw1lwF64yoMhK+iqxGbOGww+ ...'
d = d.decode('base64').decode('zlib').split()
m = [e for e in d if e[:2] == i[:1].lower() + i[1:2] and i[2:] in e[2:].split('{')]
print m > [] or i == 'I'

```

---

After decoding, the long string looks like this:

```
about{ove across{t{tive{tivity add afraid{ter again{e{o{ree ...

```

The words are grouped by their first two letters (i.e. `about{ove` stores `about` and `above`).

We search through each group, checking to see if any starts with the same prefix as the input word and also contains the rest of the word. Single letter words (`a`, `A` and `I`) are handled separately.
> 1 votes

# Answer
**Factor - Bytes: 1342, False +ves: X, False -ves: 0 = Score: X**

```
USING: ascii base64 bit-arrays bloom-filters io kernel sequences system ;
IN: examples.golf.wordcheck

CONSTANT: S "iAlOYCCAE2MARMNA4ICNzwABZAbwhAeGBMIYgDsYAAwIgoQFB/ADCBwX4IrgAOHA/g7YAYiAYaEBgEINgMGZAeGIJI0AwAqePxzLhi7HYgMaY8PLMQAKIOAPMAC7xoEB4AA6+J+zAOAAzxhDBEwaAAYQbHEYYA8YIMFw0DIaDHhA2H4RMAkYAgACGjOCD2Dmwwy2YuDSdMcCZQAkwJ4siYMPFxjQfN0MMIwDPgIBDBDvGSY4M4IAIjYOgoyMxwCOujfje5AL7KFwfGEAiIPBOAABsIDDAR8gBgAjgEUAPng+71kCJoAdBiZw+zA4gAAaILANEBxwg5eBMEZqeAYwC53BgBlYaoMBMAlAUMCgeeD2gQ4rAK7gQce4D/BmEJhfAR48D8QKMxk2CMSP8ObTAHmcB8aemAEyDiOjAJhhwLvGAJhvP7zwgY4D6Ms2cx/A4KcAjgOzY8SbzMFgN+AU1Hwwhjd3MyD3wcNjBGAY3OEZgHAA/AbvfwI3NiEQAoCDOOjRMDP4IGH2EYUoD27ygAd44AyA9+2z33jXDMRAG2xiAQBgDsALgG0O+dgAfwMIXJZHMPKolod/68CJh+HDwNAcwTEGgCci29hsdCAA2IESQPCYg+AcAIABmB3MwAfHIL8v5gSw5vtmEACeA8CQyMc77DzaZmDh/Q/ceEDCHTwA5gPyAAOgAJsPA4GDt2sNt9ULYBb9TRhigJ1OGAA2YOE6/xuzIAA5AhA8wB9swAKA4Abd+Qfwe0C8c+Gmf+QAcX4AQwYwM2A2zgAD/koLsOOAAcIgMA5sO8AC9xN+/AkYAA7UWVCG+QPwwAW8eQEcAMB++H15EBAS0A6/gQHD5QBghkEGkAEQez9i3gP9BB4ZxzABKl48mOANgAcMaPMh4EkI0HgeWBje3zbwQAcAHWaZQS5wgM8HDAIFxBiBn/MGbPMCwzATX+AwQdnECAMQEFgYwuA5xjAAoAAs3AzkGMDPA2MYHtownIGBGU5w0AQAMGAGDBADDgEs0AEzXB6ARGzDgXE4gkaejd2REQ=="

: F ( -- f )
    4 S base64> 6247 swap bit-array boa 1000 996 bloom-filter boa ;

readln 1 cut swap >lower prepend
dup "I" = [ drop t ] [ F bloom-filter-member? ] if
1 0 ? exit

```

Run using:

```
$ factor golf/wordlist/wordcheck.factor ; echo $?
color
0
$

```

The approach is based on a pre-calculated Bloom filter. There are a bunch of false positives (misspelled words seen as correctly spelled) so the code probably isn't competitive when you take that into account.
> 1 votes

# Answer
# Python - Bytes: 2294, False +ves: 0, False -ves: 1 = Score: 2304

Code (273 bytes):

```
import gzip
c=gzip.open("b").read()
def d(k):
 t={}
 while 1:
  b=ord(c[k]);s,k=(0,k+1)if b&32 else d(k+1);t[chr((b&31)+96)]=b&64,s;
  if b&128:break
 return t,k
t=d(0)[0]
w=raw_input()
if w.istitle():w=w.lower()
r=0
for x in w:
 r,t=t[x]if t and x in t else(0,0)
print r>0

```

In addition, this needs a binary file named `b` that is 2021 bytes long. Not sure how I can best share it. Suggestions are welcome if somebody wants to see it. Or I can post the code that produces it from the dictionary.

I'm taking a penalty for a false negative on **I**. Bothering with upper case letters, or special casing it, would cost me at least 10 bytes anyway.

The pre-processing procedure is:

* A trie is built from the 996 words in the dictionary (skipping **I**).
* The trie is encoded in a byte array. In addition to the 5 bits for the letter itself in each node, 3 extra bits are used to encode trie structure information:

+ 1 bit for tracking if the node is a leaf node.
    + 1 bit for tracking if the node is at the end of a valid word (note that non-leaf nodes can be at the end of a word, e.g. for "any" vs. "anyone").
    + 1 bit for tracking if the node is the last one in the list of children for its parent.

The encoded byte array is 2664 bytes long.
* The encoded byte array is compressed to 2021 bytes with gzip.

The spelling check code posted here then:

* Reads the compressed and encoded trie from the binary file, and decompresses it.
* The function `d()` decodes the byte stream, and builds a trie using nested dictionaries.
* Processes the input word for the upper/lower case rules (all upper is not accepted).
* Walks the trie letter by letter until either the end of the input word is reached, or a leaf node of the trie.
* Prints the result.
> 1 votes

# Answer
# JavaScript ~~4737~~ 4378

```
alert(is(prompt("enter word")))
function is(w){if(w=="I")return true;w=w.toLowerCase();var key='/345I_abcdefghijklmnopqrstuvwxyz',x = "MemsgBtQBIvTGACy7agOz4AQCSkAF3M5IBZVcAmGdMAVAoC6lAE64ARiCk1AYAN1GT4A+G9gA5U1PIBzSBl/ADTLVXAPHFXAL1JqAHLXTYATpKAEAa1Ua4AxUAV1GACXgApqaQCu7agCyAGIABnJkQAPU8gBnUpgHw3gCOY/gARAAEgYCMQAnAAMKBBWQCy0AVGmC4NZcvUQBAJN6UkAargAul1AEx0wBabagBdNIBRiCnABw5KsAFkAM5VcAeKVMAQBcwF0gy1JvACAOVADEyIACpSQBoiAAUSAHAA0oAaGukAMgAnwAOiAE1ABSAAXSq4AzBenACy0GYqACkgC5EAOg8AFzTQ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mmnABUDKrgFdQAYUBoAZbTWQBAGkjTAGaVXAK6QQBFIAX8AGMgFd2VADSbAD8o1wAxlV0m8AIBZACmpsAC4BfVegA0oARSl"
for(var i=0,t="",x=atob(x),m;i<x.length;i++)m=x.charCodeAt(i).toString(2),t+="00000000".substr(m.length)+m
t=t.replace(/.{5}/g, function(m){return key.charAt(parseInt(m,2))}).split(/_/)[0];
t=JSON.parse("{"+t.replace(/[a-zA-Z]/g,'"$&":{').replace(/\/(\d*)/g, function(m,d){
for(var n=parseInt(d,10)||1,o="";n--;)o+="}"
return o +",";}).replace(/\,\}/g, "}").replace(/\{\,/g, "{").replace(/\,$/, "").replace(/\{\}/g, "null"))
for(var i=0,n=t,c;i<w.length;n=n[c]){
c=w.charAt(i++)
if(!(c in n))return false}
return n==null}
```

There's three encodings of the words. First the words are converted into a shorthand tree like `about/2ve`. This has the word **about** then back 2 `/2` add `ve` for **above**. The encoding is converted to only allow for / /3 /4 and /5 backing and all others are converted as combinations. This gives a total of 32 different chars and allows for 5 bit encoding. The 5bit encoding is binary and needs to be base64 encoded.

When decoding the shorthand tree is converted to a JSON tree for a simple node search.

I initially tried to use canvas and toDataURL to get some compression but it wasn't good. If you go that route do not use the alpha channel. Browsers hack the alpha and do rounding with the data so just set that to 255 and put your data in rgb.
> 1 votes

# Answer
## Shell - Bytes: 2545, False +ves: 0, False -ves: 0 = Score: 2545

Code: ~~54~~ 52 bytes, Dictionary: ~~2518~~ ~~2494~~ 2493 bytes, FP: ~~1~~ 0, FN: 0

```
[ $1 = "${1#?*[A-Z]}" ]&&unlzma<z|grep -qix "${1%I}"

```

Quotes are not needed around the initial `$1` because "the input is always a single word, all ASCII `[A-Za-z]`." However, quotes *are* needed around the parameter expansions because they might generate an empty string.

### Examples:

In shell, an exit code of `0` is true (anything else is false). `$?` is the previous command's exit code.

```
$ sh in997 colour; echo $?
0
$ sh in997 Colour; echo $?
0
$ sh in997 coLoUr; echo $?
1
$ sh in997 COLOUR; echo $?  # I chose to consistently mark these false
1
$ sh in997 Color; echo $?
1
$ sh in997 I; echo $?
0
$ sh in997 i; echo $?
1
$ sh in997 ColourI; echo $? # testing because I strip off one trailing "I"
1
$ sh in997 II; echo $?      # … and "I" isn't in the dictionary (see below)
1

```

(Examples copied from Nejc's answer plus an all-caps example and two tests for specific corner cases used to vet my `i` vs `I` logic. I have no idea why Google Prettify likes Proper Case and CamelCase words when highlighting `lang-bash`.)

### Ungolfed and explained:

```
if [ "$1" = "${1#?*[A-Z]}" ]; then
  cat z | unlzma | grep -q -i -x "${1%I}"
fi

```

The conditional compares the argument with itself after a string manipulation that alters the string if it matches any character followed by any number of characters followed by an uppercase letter (equivalent to `s/^..*?[A-Z]//` – ignore the `?` if you don't understand it), which would compare `coLoUr` to `oUr` and `Colour` to `Colour`. This controls for mixed case (and fails all-caps), though it skips the first letter. It accepts `i` (but neither `i` nor `I` are in the dictionary, see below).

If the conditional matches (there are no capitals after the first letter), `unlzma` is run on the contents of the file named `z`, which puts the uncompressed dictionary into standard output. `grep` then queries quietly (`-q`), without regard to case—we've already controlled for that (`-i`), and on a whole line (`-x`).

The query is an altered version of the argument: if the argument has a trailing capital `I` (case sensitive!), it is removed. Because we controlled for case earlier, the only time we'd remove a capital `I` would be for the word `I`, in which case the `grep` query seeks an empty string on its own line. The dictionary's `I` entry was swapped for a blank line, so we'll get a match.

The last item that executed dictates the exit value of the script. If the conditional was false, the script exits false. If `grep` found no match, it (and the script) return false. If `grep` found a match, it and the script return true.

### Dictionary creation:

Wow. There are some awesome dictionary compression schemes in other answers here. I didn't do anything that fancy. There is zero custom compression in this code (unless you count removing DOS linebreaks), just minor prep work that makes it easier to check later on (blanking the `I` line actually *costs* a byte!).

I just took the stock dictionary, blanked the `I`, and compressed the output. I chose LZMA because it compressed this particular file better than `zip`, `gzip`, `bzip2`, `xz`, or `zlib`.

Here's my code:

```
wget -qqO- 'http://pastebin.com/raw.php?i=wh6yxrqp' \
  | perl -pne 's/\r//; s/^I$//' | lzma -c9 > z

```

`wget` flags `-qqO-` suppress all output and sends the HTML content to standard output. That's parsed by `perl`, which removes the DOS line breaks (`\r`) and converts the `I` entry to a blank line (since we stripped the trailing `I` in `grep`). That's then passed to `lzma` which outputs the compressed dictionary into a pipe to file `z`.

Note that `unlzma` will refuse to operate on a file lacking the `.lzma` extension, but it's fine with a pipeline. That means `unlzma z` fails while `unlzma<z` (effectively `cat z | unlzma`) succeeds.
> 0 votes

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


title: And all the people said…

text:
# Question
Title: And all the people said…
**Objective** Given an input of text that does not contain characters `[` or `]`, perform the following actions:

1. For every instance of `Amen` with at least one capital letter (so all instances of `Amen` excluding `amen`), output that same `Amen` (retain capitalization).
2. For every instance of `/all the people said[?: ]/i` (that's a Regular Expression), also output `Amen` (any case is fine.)

After every output, you may choose any *constant* separator, e.g. a newline, space, or nothing.

This is a , so the shortest program in bytes wins.

# Example IOs

```
Input: I said AMEN! AMEN, PEOPLE!
Output: AMENAMEN         ; any separator is fine, I choose none.

Input: amen amen amen amen
Output:                  ; nothing

Input:                   ; empty
Output:                  ; nothing

Input: *blah blah blah* And all the people said?
Output: Amen

Input: all the people said:
Output: Amen

Input: AMEN AMeN AmeN aMEN amen AmEn
Output: AMEN AMeN AmeN aMEN AmEn

Input: All the people said Amen! And all the people said AMEN!
Output: Amen Amen Amen AMEN

Input: LAMEN! Amen.
Output: AMEN Amen

Input: AmenAmenAmenAmenAMENamen
Output: Amen Amen Amen Amen AMEN

Input: And he was like, "Amen", then we were all like, "Amen, bruh."
Output: Amen Amen

Input: And all the aMen people said.
Output: aMen

```

## Bonus

* **-20 bytes** if you can "grab" the punctuation that follows the `Amen`, i.e., `Amen! => Amen!`, `AmEN. => AmEN.`, `I said Amen, bruh. => Amen,`, and `AMEN!!!! => AMEN!!!!`. `!` is the only character to be preserved multiple times. `.?!,` are the only characters to be preserved thus.
* **-40 bytes** if, there is an instance of `amen`, output, `Heresy! at index [i]` instead of nothing, where `[i]` is the index of the offending word i.e. `amen`.

### Bonus IOs

Input and output is of the form `input => output`. (Separator here is a space.)

```
BONUS 1
Can I get an Amen! => Amen!
AMEN! and AMEN! and a final Amen... => AMEN! AMEN! Amen.
Amen? Amen, and amEn! => Amen? Amen, amEn!

BONUS 2
The man sighed and said, "amen," and left. It's AMEN! => Heresy! at index [26] AMEN!

```

## Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
var QUESTION_ID=64109,OVERRIDE_USER=8478;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?([-\d.]+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 11 votes
# Retina, 37 bytes

```
S`amen
i`all the people said[?: ]
amenx
!i`amen([.,?]|!*)

```

The code if **57 bytes** long and qualifies for the **-20 bytes** bonus. Try it online!

*Thanks to @MartinBüttner for porting my Perl answer to Retina!*

### How it works

```
S`                          Split the input at...
  amen                      matches of "amen".
i`                          Case-insensitively search for
  all the people said[?: ]  matches of "all the people said",
                            followed by '?', ':' or ' '...
    amenx                   and replace them with "amenx"
!i`                         Print all case-insensitive matches of...
  amen([.,?]|!*)            "amen", followed either by a single '.',
                            ',' or '?', or by 0 or more '!'s.

```

# Answer
> 7 votes
# VBA, 193 bytes

```
Function v(b)
For i=1 To Len(b)
If StrConv(Mid(b,i,19),2) Like "all the people said" Then v=v& "Amen"
q=Mid(b,i,4):k="amen"
If StrConv(q,2) Like k And Not q Like k Then v=v& q
Next
End Function

```

No Separation, No Regex, No Bonus. Had a version that got both Bonus but was MUCH longer.

# Answer
> 5 votes
# Perl, 51 bytes

```
s/amen/x/g;s/all the people said[?: ]/amenx/ig;say/amen[.,?]|amen!*/ig

```

The actual source code contains **70 bytes**, it must be run with `perl -nE` (**+1 byte**), and it qualifies for the **-20 bytes** bonus.

# Answer
> 4 votes
# Python 2, 155 bytes

```
from re import*
F,m=findall,"((?i)amen)"
for i in split(m,input()):
 if F("((?i)all the people said[?: ])",i):print'AMen'
 elif F(m,i)and i!="amen":print i

```

---

### Example

```
$ python2 test.py
"All the people said Amen! And all the people said AMEN!"
AMen
Amen
AMen
AMEN

```

# Answer
> 3 votes
## grep and sed, 85 83 84 77 - 20 = 57 bytes

```
sed 's/all the people said[?: ]/Amenx/ig'|grep -oi 'amen[.,!?]*'|grep \[AMEN]

```

# Answer
> 3 votes
## JavaScript, 88 bytes

108 bytes - 20 bytes (catches punctuation)

```
alert(prompt().replace(/amen/g,' ').replace(/all the people said[?: ]/ig,'Amen').match(/amen(\??!?\.?)+/ig))

```

# Answer
> 3 votes
# Perl, 103 - 60 = 43 bytes

```
#!perl -p
s/amen/Heresy! at index [@-]/g;s/all the people said[?: ]/Amen /gi;s/(amen([.,?]|!*)|h[^h]+\])\K|.//gi

```

Counting the shebang as one, input is taken from stdin. Maintains punctuation for *-20* bytes, and identifies heresy for *-40*.

---

**Sample Usage**

```
$ echo amen amen, and all the people said?? amen amen | perl amen.pl
Heresy! at index [0]Heresy! at index [5]AmenHeresy! at index [37]Heresy! at index [42]

$ echo AMEN AMeN AmeN aMEN amen AmEn | perl amen.pl
AMENAMeNAmeNaMENHeresy! at index [20]AmEn

$ echo The man sighed and said, "amen," and left. It's AMEN! | perl amen.pl
Heresy! at index [26]AMEN!

```

---

# Perl, 70 - 20 = 50 bytes

```
#!perl -p
s/all the people said[?: ]/Amen /gi;s/amen|(?i:amen([.,?]|!*))\K|.//g

```

Counting the shebang as one, input is taken from stdin. Maintains punctuation for *-20* bytes.

---

**Sample Usage**

```
$ echo All the people said Amen, and all the people said AMEN!! | perl primo-amen.pl
AmenAmen,AmenAMEN!!

```

# Answer
> 3 votes
# , 66 - 20 = 46 chars / 80 - 20 = 60 bytes

```
ïċ/all the people said[?: ]⍀,`Amen”ċ(/amen⌿,`x”ĉ/amen(\??!?\.?)+⍀)

```

Try it here \- Firefox only.

First time here at PPCGSE. Hope this golf is pretty good.

EDIT: Actually, I'm beating CJam (in char count), so that's pretty good!

# Answer
> 2 votes
# CJam, 57 bytes

```
 q_,,\f{\:I>_4<_el"amen":A=*_A="Heresy! at index ["I+']+@?oK<)"?: "&,*el"all the people said"=A*o}

```

The code is **97 bytes** long and qualifies for the **-40 bytes** bonus.

Try it online in the CJam interpreter.

# Answer
> 2 votes
## JavaScript, 100 bytes

```
alert(prompt().replace(/all the people said[?: ]/ig,'Amen').replace(/amen/g,'x').match(/amen/ig));

```

# Answer
> 2 votes
# JavaScript, ~~136~~ 135 - 40 - 20 = 75 bytes

```
alert(prompt(A="ameN").replace(/all the people said[?: ]|(amen)([.,?]|!*)|./ig,(v,a,p,i)=>a?a>A?`Heresy! at index [${i}]`:v:v[1]?A:""))

```

Explanation:

This code is driven by a three-part regex that feeds results into a `replace` callback. The parts are:

* `all the people said[?: ]` \- simply matches the required `all the people said` pattern
* `(amen)([.,?]|!*)` \- matches any-case `amen` and punctuation (one of `.,?` or zero or more `!`, which makes the punctuation optional) into separate match groups -- credit to Dennis for the punctuation pattern
* `.` \- matches any other character, not part of the above patterns, one at the time

Therefore, any match must either be an all-the-people string, an Amen match with optional punctuation, or a single character not part of either of those phrases. We use logic in the replacer callback to save and replace the appropriate parts of the string, and change every other character to the empty string.

```
alert(
  // store "ameN" in `A` and then prompt
  prompt(A="ameN")
    .replace(
      // three-part regex:
      /all the people said[?: ]|(amen)([.,?]|!*)|./ig,

      // replacer callback, with arguments
      //   v - total match
      //   a - "amen" match group
      //   p - punctuation match group (unused)
      //   i - index of match
     (v,a,p,i)=>
        a?           // if there is an Amen match
          a>A?      //   if the Amen is lowercase (lexically more than "ameN")
               `Heresy! at index [${i}]`
              :v     //   otherwise, output full Amen with punctuation
         :v[1]?      // if there is no Amen, but more than one character
          A          //   this must be all-the-people; output "ameN"
         :""         // otherwise, not an Amen or all-the-people
  )
)

```

# Answer
> 1 votes
# Python 2, 191 - 40 = 151 bytes

```
i=input()
a='amen'
for j in range(len(i)):
 s=i[j:j+20];w=s[:4]
 if s[:-1].lower()=="all the people said"and s[-1]in'?: ':print a
 if w.lower()==a:print'Heresy! at index[%d]'%j if w==a else w

```

No regex, and Bonus 2

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


title: Fast, Cheap, and Good - Choose any Two

text:
# Question
Title: Fast, Cheap, and Good - Choose any Two
As programmers, we all know the saying: "You can have it fast and good, but it won't be cheap, you can have it cheap and good, but it won't be fast, or you can have it fast and cheap, but it won't be good."

For this challenge, you are implementing an imaginary configuration tool for your custom programming services. You should render a set of three check boxes, with a heading of "SELECT ANY TWO":

```
SELECT ANY TWO
☐ FAST
☐ CHEAP
☐ GOOD
```

Once two items have been selected, the third item must be disabled. Upon deselecting one of the two selected items, all options must again be enabled. Put another way, if zero or one items are selected, all are still enabled, but if two items are selected, the third must be disabled.

No special controls allowed. The check boxes should be the standard check box in your language of choice. For example, don't use a "CheckBoxList" control, if your language has one. I'm imagining most entries will be HTML/jQuery, but that is not a rule. This is code golf, looking for the shortest entry.

**WINNERS SO FAR**

I'll break it down into categories. There are some clear winners:

**jQuery:** nderscore, Mr. Tenacity Under 100b when you exclude text "resources". Honorable mention should also go to Matt for introducing the jQuery concepts that many took inspiration from.

**Dyalog APL:** marinus, a.k.a. Mr. Unicode How do you type all those things? I can see why you would want to write short programs.

**PHP:** SuperScript I believe this is the shortest entry that actually disables rather than deselecting the third option, following the strictest interpretation of the rules.

# Answer
> 23 votes
# Javascript (*ES5*) with jQuery - 143 (Demo)

I modified Matt's solution and golfed it as far down as I think it can go:

```
$("*").html(["SELECT ANY TWO","FAST","GOOD","CHEAP"].join("<input type=checkbox onclick=(a=$('input:not(:checked)')).prop('disabled',!a[1])>"))

```

# Javascript (*ES5*) without jQuery - 185 175 (Demo)

Using jQuery is kind of cheating, so here's a solution without it:

```
(d=document).write(["SELECT ANY TWO","FAST","GOOD","CHEAP"].join("<input type=checkbox onclick='for(b in a=d.querySelectorAll(\"input:not(:checked)\"))a[b].disabled=!a[1]'>"))

```

---

If we're allowed to prevent the user from checking the 3rd box instead of actually disabling the field, we can make it even shorter:

# With jQuery - 126 123 (Demo)

```
$("*").html(["SELECT ANY TWO","FAST","GOOD","CHEAP"].join("<input type=checkbox onclick=this.checked*=!$(':checked')[2]>"))

```

# Without jQuery - 150 147 (Demo)

```
(d=document).write(["SELECT ANY TWO","FAST","GOOD","CHEAP"].join("<input type=checkbox onclick=this.checked*=!d.querySelectorAll(':checked')[2]>"))

```

# Answer
> 28 votes
# JavaScript - 184 169 (with jQuery)

```
b="input",a="<input type=checkbox>",c=":checked";$("body").html("SELECT ANY TWO"+a+"FAST"+a+"GOOD"+a+"CHEAP").click(function(){$(b).not(c).attr("disabled",!!$(b+c)[1])})

```

http://jsfiddle.net/L33JK/16/

EDIT: improved with help from @Daniel Lisik - https://codegolf.stackexchange.com/a/26805/16278

# Answer
> 12 votes
## Dyalog APL (on Windows) (169)

This is a static function, to test it if you don't know APL, type `)ed C` and paste this in the edit window, then run `C`.

```
C
'R'⎕WC'Form' 'Select any two',2/⊂S←2/20
1 21 41{('R.',⊃⍵)⎕WC'Button'⍵(⍺1)S'Check'('Event' 'Select' 'F')}¨'Fast' 'Cheap' 'Good'
B←R.(F C G)
F←{B.Active←X∨2≠+/X←B.State}

```

Newer bits of APL have *long* keywords. I still beat HTML though.

Explanation:

* `'R'⎕WC'Form' 'Select any two',2/⊂S←2/20`: create a form `R`, with title *Select any two* and size and position `20 20`. Also stores `20 20` in `S`.
* `1 21 41{`...`}¨'Fast' 'Cheap' 'Good'`: for each of these pairs of data (name and y-coordinate, which are the only variables that differ between the checkboxes:
    + `('R.',⊃⍵)⎕WC'Button'`: create a button within `R` with the first letter of the name,
    + `⍵(⍺1)S'Check'`: with the right argument as the title, `(left arg, 1)` as position, reusing `S` as the size and `Check` as style,
    + `('Event' 'Select' 'F')`, which calls the function `F` when clicked.
* `B←R.(F C G)`: use `B` as an abbreviation for the three checkboxes we created
* `F←{`...`}`: define the callback function as:
    + `X←B.State`: get the state for each checkbox and store them in `X`,
    + `X∨2≠+/X`: sum X, if this is not equal to two all checkboxes must be active, if it is equal to two only checked checkboxes must be active
    + `B.Active←`: enable or disable the checkboxes

Result:

# Answer
> 11 votes
# Python ~~3~~ 2, ~~454~~ ~~434~~ ... ~~393~~ 392 bytes

I thought, *Python must be shorter than Java.* Here is the "proof" (~~*EDIT:* now it really is shorter~~):

```
from Tkinter import*
t=Tk()
r=str.replace
exec r(r(r(r('a@b@c@l=Label(t,text="SELECT ANY TWO");A`FAST|a);B`CHEAP|b);C`GOOD|c);l^A^B^C^','`','=Checkbutton(t,text="'),'|','",v='),'^','.pack();'),'@','=IntVar();')
def f(p,b,B,s):
 for i in 0,1,2:
    y=b[i].get()
    if p[i]-y:
     p[i]=y;s-=1
     if p[i]:s>0and B[i].toggle();s+=2
 t.after(1,f,p,b,B,s)
t.after(1,f,[0]*3,[a,b,c],[A,B,C],0)
t.mainloop()

```

For those of you curious as to what the `exec` expression actually executes, it executes this (this is what the replaces do to the string. Newlines added for readability):

```
a=IntVar();
b=IntVar();
c=IntVar();
l=Label(t,text="SELECT ANY TWO");
A=Checkbutton(t,text="FAST",v=a);
B=Checkbutton(t,text="CHEAP",v=b);
C=Checkbutton(t,text="GOOD",v=c);
l.pack();
A.pack();
B.pack();
C.pack();

```

This uses the same logic as my Java answer: unselect the checkbox if it causes more than 2 checkboxes to be selected. ~~Unf~~ ~~Fortunately~~ Unfortunately, I spent ~~more~~ ~~less~~ more bytes doing this.

**EDITS:**

1. massive adjustment of code to use `exec`, saving a whopping 1 byte!
2. switched to python 2 to squeeze two bytes from the `exec` (removing parentheses).
3. more golfing. Includes changing `range(3)` to `0,1,2` and changing the indentation to have one layer of tabs. Unsure if `\t\t` would work instead of `\t__`(`_` is the space character). Finally reached the longest my Java answer ever was.
4. used replace trick
5. used Bakiru's suggestion, and golfed some more. Actually made it shorter than Java! But now, the Java answer got golfed more, so this is again longer. :-(
6. used improved replace trick.
7. changed a `!=` for a `-`.

# Answer
> 10 votes
# Java, ~~421~~ ... ~~369~~ 351 bytes

```
import java.awt.*;class F extends Checkbox{F(String s){super(s);}public static void main(String[]a){new Frame(){{add(new Panel(){{add(new Label("SELECT ANY TWO"));F[]c={new F("FAST"),new F("CHEAP"),new F("GOOD")};for(F b:c){add(b);b.addItemListener(e->{int x=0;for(F d:c)x+=d.getState()?1:0;if(x>2)((F)e.getSource()).setState(1<0);});}}});}}.show();}}

```

Java... because Java. Nicer looking code:

```
import java.awt.*;

class F extends Checkbox {
    F(String s) {
        super(s);
    }

    public static void main(String[] a) {
        new Frame() {
            {
                add(new Panel() {
                    {
                        add(new Label("SELECT ANY TWO"));
                        F[] c = {new F("FAST"), new F("CHEAP"), new F("GOOD")};
                        for (F b: c) {
                            add(b);
                            b.addItemListener(e -> {
                                int x = 0;
                                for (F d: c) {
                                    x += d.getState() ? 1 : 0;
                                }
                                if (x > 2) ((F) e.getSource()).setState(1 < 0);
                            });
                        }
                    }
                });
            }
        }.show();
    }
}

```

Sample run (different sizings of the window, first is on startup):

The checkboxes are arranged horizontally; this is allowed. It would take much more to align it properly. Also, I'm disabling by unchecking the box when it is clicked, not by making it impossible to be clicked.

**EDITS:**

1. saved 3 bytes by making the main class extend `Checkbox`.
2. reread Lambda Expressions and realized that the type name was unnecessary. Take that Python!
3. converted a `while` loop to a foreach loop (thanks Lee); why didn't I think of that before?
4. saved 18 bytes by using an anonymous class and an instance initalizer for both the `Frame` and `Panel`.

# Answer
> 10 votes
# Rebol, 219 197

```
load-gui p: func[p][p/state/value]x: func[v][if all[p a p b p c][set-face v false]] view [title"SELECT ANY TWO"a: check"FAST"on-action[x a]b: check"CHEAP"on-action[x b]c: check"GOOD"on-action[x c]]

```

Ungolfed:

```
load-gui    ;; this is temporary while r3-gui is in beta

p: func [p] [p/state/value]

x: func [v] [
    if all [p a p b p c] [set-face v false]
]

view [
    title "SELECT ANY TWO"
    a: check "FAST" on-action [x a]
    b: check "CHEAP" on-action [x b]
    c: check "GOOD" on-action [x c]
]

```

This is the Rebol 3 View dialect (r3-gui). Screendump below from Ubuntu Linux:

**Update** \- Thanks to Earl & Graham from Rebol SO Chatroom for shaving 22 chars of the code - http://chat.stackoverflow.com/transcript/message/16345039#16345039

# Answer
> 7 votes
# C++11/Qt5.2 - ~~561~~ ~~481~~ ~~433~~ ~~423~~ 369

Because why not.

Shockingly, as of now we are shorter than Python, and the non-buggy C#, and tied with Java!

Credits to EveBird for cutting it down from 561 to 481.

And once more EveBird shortens it from 481 to 433!

Took a few off with a lambda connect

Down to 389 with C++11 initializers

And 373 without the separate class

Removed a few spaces - 369

## Golf'd:

```
#include<QtWidgets>
#define C(x,y,z)z.setEnabled(x.isChecked()+y.isChecked()<2);
#define S(x)l.addWidget(&x);
#define X(x)S(x);x.connect(&x,&QCheckBox::clicked,[&](){C(g,f,c)C(g,c,f)C(f,c,g)});
int main(int n,char**v){QApplication a(n,v);QWidget m;QLabel t{"Select any two"};QCheckBox g{"Good"},f{"Fast"},c{"Cheap"};QVBoxLayout l(&m);S(t)X(g)X(f)X(c)m.show();a.exec();}

```

## Sort of Un-Golfed:

```
#include<QtWidgets>

#define C(x,y,z)z.setEnabled(x.isChecked()+y.isChecked()<2);
#define S(x)l.addWidget(&x);
#define X(x)S(x);connect(&x, &QCheckBox::clicked, [&](){C(g,f,c)C(g,c,f)C(f,c,g)});

int main(int n,char**v){
    QApplication a(n,v);
    QWidget m;
    QLabel t{"Select any two"};
    QCheckBox g{"Good"},f{"Fast"},c{"Cheap"};
    QVBoxLayout l(&m);
    S(t)X(g)X(f)X(c)m.show();
    a.exec();
}

```

# Answer
> 6 votes
# CoffeeScript - ~~167~~, 154

CoffeeScript port of **@Matt**'s answer.

```
b="input";a="<input type=checkbox>";c=":checked";$("body").html("SELECT ANY TWO#{a}FAST#{a}GOOD#{a}CHEAP").click ->$(b).not(c).attr "disabled",!!$(b+c)[1]

```

Somewhat ungolfed:

```
b = "input"
a = "<input type=checkbox>"
c = ":checked"

$( "body" ).html( "SELECT ANY TWO#{a}FAST#{a}GOOD#{a}CHEAP" ).click ->
    $( b ).not( c ).attr "disabled", !!$( b + c )[1]

```

JSFiddle.

# Answer
> 5 votes
Thanks to Rotem and Johnbot for the golfing help!

# C# ~~343~~ 334

This one uses the same "cheat" as Quincunx's Java answer \- the checkboxes aren't actually disabled; they just don't allow you to check them if that check makes 3.

```
using System.Windows.Forms;using System.Linq;class P:Form{static void Main(){P p=new P();p.Text="SELECT ANY TWO";int y=0;var a=new CheckBox[3];foreach(var n in "FAST CHEAP GOOD".Split()){var c=new CheckBox();a[y]=c;c.Top=y++*50;c.Text=n;c.Validating+=(s,e)=>{if(a.Count(b=>b.Checked)>1)e.Cancel=true;};p.Controls.Add(c);}Application.Run(p);}}

```

There's also a minor bug that you can't close the window after selecting the third checkbox unless you unselect one, because the validation won't pass. But this is , so who cares? ;)

# C# ~~403~~ ~~397~~ 374

This is a proper one that actually disables the third checkbox.

```
using System.Windows.Forms;using System.Linq;class P:CheckBox{static void Main(){var p=new Form{Text="SELECT ANY TWO"};P[]a=null;a="FAST CHEAP GOOD".Split().Select((x,i)=>{var c=new P{Top=i*50,Text=x};c.Click+=(s,e)=>{a.First(b=>!b.Checked).Enabled=a.Count(b=>b.Checked)>1?1<0:a.All(b=>b.Enabled=0<1);};p.Controls.Add(c);return c;}).ToArray();Application.Run(p);}}

```

Kinda ungolfed:

```
using System.Windows.Forms;
using System.Linq;

class P:Form
{
    static void Main()
    {
        P p = new P();
        p.Text = "SELECT ANY TWO";
        int y = 0;
        var a = new CheckBox[3];
        foreach (var n in "FAST CHEAP GOOD".Split())
        {
            var c = new CheckBox(); a[y] = c; c.Top = y++ * 50; c.Text = n; c.Click += (s, e) =>
            {
                if (a.Count(b => b.Checked) == 2)
                {
                    a.First(b => !b.Checked).Enabled = false;
                }
                else
                {
                    foreach (var b in a) b.Enabled = true;
                }
            };
            p.Controls.Add(c);
        }
        Application.Run(p);
    }
}

```

# Answer
> 5 votes
# PHP, Javascript, jQuery - 135b

I was admiring @nderscore's answer, but then I decided to copy and one-up him.

```
<?echo"SELECT ANY TWO".($m="<input type=checkbox onclick=(a=$('input:not(:checked)')).prop('disabled',!a[1])>")."FAST$m GOOD$m CHEAP"?>

```

Basically I replaced his `.join` trick with some PHP Hypertext Preprocessing.

# Answer
> 5 votes
# Ruby, ~~219~~ 218 bytes

I use the same Tk widgets as the Python 3 answer by Quincunx.

This program breaks the rules because it has a **check box list**. (The rules said, "Don't use a check box list.") Yes, `a` is an array of 3 TkCheckButton objects, and I believe that an array is a list. My defense is that I did not use any existing check box list, but I used the standard check boxes and made my own list.

```
require'tk'
o=->(c){c.variable.value>?0}
TkLabel.new{text'SELECT ANY TWO'
pack}
a=%w[FAST CHEAP GOOD].map{|t|TkCheckButton.new{text t
command{a.map{|c|c.state a.count(&o)<2||o[c]?:normal: :disabled}}
pack}}
Tk.mainloop

```

I tested with Ruby 2.1.0 and Tk 8.5.15.

* `o[c]` is a predicate to test if check button `c` is selected. With the default strings, `c.variable.value` is `'0'` or `'1'`, so the string comparison is only true if `'1'>'0'`. EDIT: I saved 1 byte (219 down to 218) by changing `'0'` to `?0`. In Ruby, `?0` is a character constant.
* `a.count(&o)` uses the predicate to count the selected check buttons.
* When the user toggles a check button, the command calls `a.map` to loop for all buttons, making them `:normal` or `:disabled`.

# Answer
> 5 votes
# AngularJS - 214

```
<input type=checkbox ng-model=fast ng-disabled=cheap&&good>FAST</input>
<input type=checkbox ng-model=cheap ng-disabled=fast&&good>CHEAP</input>
<input type=checkbox ng-model=good ng-disabled=fast&&cheap>GOOD</input>

```

# Answer
> 4 votes
**Mathematica**

A more code-golfed version as suggested by David, **255 characters**:

```
h = Checkbox;
i = Dynamic;
j = Enabled;
t = True;
i[
 If[Total@Boole@{a, b, c} == 2,
  {d, e, f} = {a, b, c},
  {d, e, f} = {t, t, t}
  ];
 Row@{
   "SELECT ANY TWO",
   h[i@a, j -> d], "FAST",
   h[i@b, j -> e], "CHEAP",
   h[i@c, j -> f], "GOOD"
   }
 ]

```

# Answer
> 4 votes
## JavaScript (with jQuery) - 224, 222, 210, 205, 178

```
a="<input type=checkbox>",c=":checked",e="input",f="disabled",d=$("body").html("SELECT ANY TWO"+a+" FAST"+a+"CHEAP"+a+"GOOD").click(function(){$(e).not(c).attr(f,$(e+c).length>1)})

```

Thanks to a comment from brilliant @Matt I reduced the code by 27 characters.

**JSFiddle**

# Answer
> 4 votes
# k3 - 95

```
a[`FAST`CHEAP`GOOD]:0
a[.;`c]:`check
a..l:"SELECT ANY TWO"
a..t:"if[3=+/a[];.[_v;_i;:;0]]"
`show$`a

```

code is here

<sub>(source: nsl.com)</sub>

# Answer
> 3 votes
# C#, 335 333 326 320 308

Based off Bobs Answer, mine does use fewer characters than his (335 v 342), but I might not understand fully how to count this.

```
using System.Linq;using System.Windows.Forms;class P:Form{static void Main(){new P();}P(){Text="SELECT ANY TWO";var a="FAST CHEAP GOOD".Split().Select(r=>new CheckBox{Text=r,Top=r[0]%9*20}).ToList();a.All(r=>{r.Validating+=(b,c)=>c.Cancel=a.Count(z=>z.Checked)>1;Controls.Add(r);return 1>0;});ShowDialog();}}

```

Ungolfed

```
using System.Linq;
using System.Windows.Forms;

class P : Form
{
    static void Main()
    {
        new P();
    }

    P()
    {
        Text = "SELECT ANY TWO";

        var a = "FAST CHEAP GOOD".Split().Select(r => new CheckBox
        {
            Text = r,
            Top = r[0] % 9 * 20
        }).ToList();

        //loops, I dont need no stinking loops
        a.All(r => { r.Validating += (b, c) => c.Cancel = a.Count(z => z.Checked) > 1; Controls.Add(r); return 1 > 0; });
        ShowDialog();
    }
}

```

# Answer
> 3 votes
## Groovy - 357 221 217 chars

I've ported Quincunx's solution to Groovy 2.2.1, using SwingBuilder (and made it even more Groovier):

```
c=[];new groovy.swing.SwingBuilder().frame(){panel(){label("SELECT ANY TWO");f={if(c.count{it.isSelected()}>2)it.source.setSelected(1<0)};["FAST","CHEAP","GOOD"].each{c<<checkBox(label:it,itemStateChanged:f)}}}.show()

```

Ungolfed:

```
c=[]
new groovy.swing.SwingBuilder().frame() {
    panel() {
        label("SELECT ANY TWO")
        f = { if (c.count{it.isSelected()} > 2) it.source.setSelected(1<0) }
        ["FAST","CHEAP","GOOD"].each { c << checkBox(label: it, itemStateChanged: f) }
    }
}.show()

```

# Answer
> 3 votes
# mIRC script (727 719 bytes)

Forgot about this language until a drunken conversation last night.

```
alias select_two {
  dialog -m s2 s2
}

dialog s2 {
  title "Select any two:"
  size -1 -1 200 100
  check "Fast",1, 5 10 170 25
  check "Cheap",2, 5 30 170 25
  check "Good",3, 5 50 170 25
}

on *:dialog:s2:sclick:*: {
  if ($did(s2, $did).state = 1) {
    if ($did = 1) {
      if ($did(s2, 2).state = 1) { did -b s2 3 }
      if ($did(s2, 3).state = 1) { did -b s2 2 }
    }
    if ($did = 2) {
      if ($did(s2, 1).state = 1) { did -b s2 3 }
      if ($did(s2, 3).state = 1) { did -b s2 1 }
    }
    if ($did = 3) {
      if ($did(s2, 1).state = 1) { did -b s2 2 }
      if ($did(s2, 2).state = 1) { did -b s2 1 }
    }
  }
  if ($did(s2, $did).state = 0) {
    did -e s2 1
    did -e s2 2
    did -e s2 3
  }
}

```

More should be coded in this language! But there needs to be a way to make this into a real mess so it can be as good as Perl.

Edit: noticed that my Python-isms are leaking through and was able to reduce the code by 8 bytes!

# Answer
> 3 votes
## QML - 369 315 254 251 248 bytes

Here goes QML (QtQuick 2.0) version, given only the .qml file contents. This code requires Qt 5.1 at least to run. Not a big deal as its huge compared to other solutions (**248 bytes**), but it's a full featured cross-platform application (Android and iOs included)! :D

```
    import QtQuick 2.0;import QtQuick.Controls 1.1;Row{Text{text:"SELECT ANY TWO"}CheckBox{id:a;text:"FAST";enabled:!b.checked|!c.checked}CheckBox{id:b;text:"CHEAP";enabled:!a.checked|!c.checked}CheckBox{id:c;text:"GOOD";enabled:!b.checked|!a.checked}}

```

To run it, save the code to a .qml file, install Qt 5.1 and run qmlscene.exe (or just qmlscene on linux), which will show an open file dialog. Chose the .qml file you've saved the code to and see the awesome result! :D

# Answer
> 2 votes
# JavaScript 209 (was 346)

Shortened: thanks for comments.

```
function f(){var a=document.getElementsByClassName("x"),n=0,i=0;for(i in a){if(a[i].checked)n++;}if(n<2){for(i in a){a[i].disabled=false;}}else{for(i in a){i(false===a[i].checked){a[i].disabled=true;break;}}}}

```

Golfed function:

```
function f(a,b,c){
var x=document.getElementById(a);
var y=document.getElementById(b);
var z=document.getElementById(c);
var n=0,i=0;
var a=[x,y,z];
for(i in a)
{
if(a[i].checked) n++;
}
if(n<2)
{
for(i in a)
{
a[i].disabled=false;
}
}
else
{
for(i in a)
{
if(false===a[i].checked)
{
a[i].disabled=true;
break;
}
}
}
}

```

HTML form: provides input and calls the function. * Form now uses class=x to group inputs.

```
<form>
        SELECT ANY TWO<br>
        FAST <input id="a" type="checkbox" class="x" value="0" onchange="f()"><br>
        CHEAP <input id="b" type="checkbox" class="x" value="1" onchange="f()"><br>
        GOOD <input id="c" type="checkbox" class="x" value="2" onchange="f()"><br>
    </form>

```

Tested with NetBeans and Chrome.

# Answer
> 2 votes
# JavaScript / jQuery 237 234 229

Very similar approach as Matt's answer, although a little longer.

```
$(function(){var e="input ",t="disabled",n,r;$("body").html("SELECT ANY TWO|FAST|CHEAP|GOOD".replace(/\|/g,"<"+e+'type="checkbox">'));n=$(e);n.change(function(){n.removeAttr(t);r=$(":checked");if(r.length>1)n.not(r).attr(t,t)})})

```

# Answer
> 2 votes
# Groovy

Based on the Java version, but much slimmed down ;)

Types were replaced by 'def', semicolons removed, add replaced by \<\<, the 1\<0 replaced by 0, collect for creating the checkboxes, removed the itemevent type, removed casting the checkbox, enhanced the loops.

```
import java.awt.*
class F {
    def static main(a) {
        def f = new Frame()
        def p = new Panel()
        f << p
        p << new Label("SELECT ANY TWO")
        def c = ['FAST','CHECK','GOOD'].collect { new Checkbox(it) }
        c.each { b ->
            p << b
            b.addItemListener { e->
                int x = 0, i = 0
                3.times {
                    x += c[it].state ? 1 : 0
                }
                if (x > 2) {
                    e.source.state = 0
                }
            }
        }
        f.show()
    }
}

```

# Answer
> 1 votes
# TCL 347

At least it beats Python and Java.

```
set d .
proc a v {upvar f f c c g g d d $v x
if $x&&$f+$c+$g==2 {set d .$f$c$g
$d configure -state disabled}
if !$x {$d configure -state normal}}
set z -variable
set y -command
set x checkbutton
label .l -text {SELECT ANY TWO}
$x .011 -text FAST $z f $y a\ f
$x .101 -text CHEAP $z c $y a\ c
$x .110 -text GOOD $z g $y a\ g
pack .l .011 .101 .110

```

Note: if you start by selecting one checkbox and immediately unselecting it, you will get an error. You can fix it by adding `110` to the end of the first line.

Ungolfed:

```
# Keep track of the last disabled button. Set it to something valid to start with.
set last .110

proc toggled name {
        # Access some globals
        upvar fast  fast
        upvar cheap cheap
        upvar good  good
        upvar last  last
        upvar $name value

        # Just toggled one on, check if exactly two are now on
        if {$value == 1 && ($fast + $cheap + $good) == 2} {
                set last .$fast$cheap$good
                $last configure -state disabled
        }
        # Just toggled one off. Re-enable disabled one.
        if {$value == 0} {
                $last configure -state normal
        }
}

label .label -text {SELECT ANY TWO}

checkbutton .011 -text FAST  -variable fast  -command {toggled fast}
checkbutton .101 -text CHEAP -variable cheap -command {toggled cheap}
checkbutton .110 -text GOOD  -variable good  -command {toggled good}

pack .label .011 .101 .110

```

# Answer
> 1 votes
## Javascript + Knockout: ~250 Characters

```
a=function(i){return "<input type=checkbox data-bind='value: "+i+", checked: x, disable: x().length>=2 && x().indexOf(\""+i+"\")==-1'>"},document.body.innerHTML = "SELECT ANY TWO"+a(0)+"Fast"+a(1)+"Good"+a(2)+"Cheap"; ko.applyBindings({x:ko.observableArray([])})

```

# Answer
> 0 votes
# AngularJS - 155 (Demo)

```
SELECT ANY TWO :<i ng-init=t=[]><p ng-repeat="(i,v) in ['FAST','CHEAP','GOOD']"><input type=checkbox ng-disabled=t[(i+1)%3]&&t[(i+2)%3] ng-model=t[i]>{{v}}

```

The ungolfed version:

```
SELECT ANY TWO :
<i ng-init="checkedArray = []" /> <!-- A useless tag to initialize the array (which can't be done on the `input` tag, unfortunately) -->
<p ng-repeat="(key, value) in ['FAST', 'CHEAP', 'GOOD']">
    <input
        type="checkbox"
        ng-model="checkedArray[key]"
        ng-disabled="checkedArray[(key + 1) % 3] && checkedArray[(key + 2) % 3]"
    />
    {{value}}
</p>

```

# Answer
> 0 votes
# Ruby with Shoes, 133 characters

```
Shoes.app{para'SELECT ANY TWO'
$o=%w{FAST GOOD CHEAP}.map{|q|c=check{|c|$o[c]=!$o[c];$o.values.all?&&c.checked=p}
para q
[c,p]}.to_h}

```

Sample output:

# Answer
> 0 votes
# FLTK, 303 characters

```
decl{int c;}Function{}{}{Fl_Window{}{xywh {9 9 195 195}}{Fl_Pack{}{label{SELECT ANY TWO}}{Fl_Check_Button{}{callback{e(o);}label FAST}Fl_Check_Button{}{callback{e(o);}label GOOD}Fl_Check_Button{}{callback{e(o);}label CHEAP}}}}Function{e(Fl_Button*o)}{}{code{if((c+=o->value()*2-1)>2){o->value(0);c--;}}}

```

Ungolfed:

```
decl { int c; }

Function {} {} {
    Fl_Window {} {
        xywh {9 9 195 195}
    } {
        Fl_Pack {} {
            label {SELECT ANY TWO}
        } {
            Fl_Check_Button {} {
                callback { e(o); }
                label FAST
            }
            Fl_Check_Button {} {
                callback { e(o); }
                label GOOD
            }
            Fl_Check_Button {} {
                callback { e(o); }
                label CHEAP
            }
        }
    }
}

Function { e(Fl_Button* o) } {} {
    code {
        if ((c += o->value() * 2 - 1) > 2) {
            o->value(0);
            c--;
        }
    }
}

```

Sample output:

---
Tags: code-golf, counting
---


title: Hello World window

text:
# Question
Title: Hello World window
Create a window that says hello world inside and nothing else. You can not have any ok or cancel buttons inside. It must be just a plain window that says hello world. I do not care about the contents of the window frame or how the window looks, but inside it must say hello world only.

Example:

**Shortest code wins.**

EDIT: I am sorry Johannes Kuhn the window has to actually stay there, it may not close right away. I didn't think of this scenario and as such didn't account for this.

EDIT 2: We currently have 3 tied answers (20 characters). Any suggestions of who should be the winner is welcome.

# Answer
### bash ~~20~~ 19 chars

Thanks @manatwork for the useless space after `-p`!

```
read -pHello\ World

```

In action:

```
echo 'read -pHello\ World' >/tmp/helloworld.sh
chmod +x /tmp/helloworld.sh

```

Than double click from file manager:

And see:

Having as default shell.

### ~~19~~ 16

As question stand for *only Hello World* and *Nothing else*, *the window have to stay* but nothing like *print text only once* or so on, I think this match requirement too!

```
yes Hello\ World

```

There is only 16 chars.

```
echo >/tmp/helloworld.sh 'yes Hello\ World'

```

With same procedure this give:
> 13 votes

# Answer
## Windows Command Prompt, 26

```
echo Hello World>.hta&.hta

```
> 25 votes

# Answer
# R, 23

```
plot(1,m="Hello World")

```

This opens a plot window.
> 16 votes

# Answer
## Dyalog APL (20)

```
⎕SM←'Hello World'1 1

```

Picture:
> 14 votes

# Answer
### HTML (kinda), 17

```
data:,Hello World

```

Paste that into your browser's address bar.

### Javascript, 25

```
open("data:,Hello World")

```

This uses your browser's `window.open` and a data uri.

A Data URIs's mime-type and charset default to `text/plain;charset=US-ASCII` when omitted.

### Javascript, 19

```
eval($("s").text())

```

This one only works when this answer is the top (or accepted) answer and it is run on THIS stackoverflow page (via your JavaScript console). :-)

~~open("data:,Hello World");~~
> 13 votes

# Answer
## Powershell, 23

```
'Hello World'>.hta;.hta

```
> 11 votes

# Answer
# Matlab, 30 27 20

```
title('Hello World')

```

Are plot windows allowed? It does not have any buttons inside.
> 9 votes

# Answer
# Java, 117 chars

```
import java.awt.*;class C{public static void main(String[]a){new Frame(){{add(new Label("Hello World"));show();}};}}

```

With formatting:

```
import java.awt.*;

class C {
    public static void main(String[] a) {
        new Frame() {
            {
                add(new Label("Hello World"));
                show();
            }
        };
    }
}

```

We can avoid having to explicitly declare a variable by using initializer blocks inside an anonymous subclass of Frame. Interestingly, using awt, it's just as many characters to `import java.awt.*;` as it is to just fully qualify both classnames.
> 9 votes

# Answer
# Mathematica ~~29 27~~ 25

With 1 byte saved thanks to CatsAreFluffy.

```
DialogInput@"hello world"

```
> 7 votes

# Answer
# Shell, 32

```
xmessage -buttons '' Hello World

```
> 5 votes

# Answer
# Ruby with Shoes, 28

```
Shoes.app{para'Hello World'}

```

Result:
> 5 votes

# Answer
# Rebol 2, 29

```
view layout[txt{Hello World}]

```
> 5 votes

# Answer
# Python 2/3, 54 characters

Capitalize the t in tkinter to make it work on Python 2.

```
__import__("tkinter").Label(text="Hello World").pack()

```
> 5 votes

# Answer
## Windows Batch, 23

```
@pause|echo Hello World

```
* Opens a black window that shows `Hello World`, nothing else.
* Now the windows stays open
* There are no buttons in the window.
> 4 votes

# Answer
### ExtJS (Javascript) 44

```
new Ext.Window({html:'Hello world',}).show()

```

```
new Ext.Window({html:'Hello world',}).show()
```

```
<link rel="stylesheet" type="text/css"
  href="http://dev.sencha.com/deploy/dev/resources/css/ext-all.css"/>
<script type='text/javascript'
  src="http://dev.sencha.com/deploy/dev/adapter/ext/ext-base.js"></script>
<script type='text/javascript'
  src="http://dev.sencha.com/deploy/dev/ext-all.js"></script>
```
> 4 votes

# Answer
## Processing, 23

Based on my answer here: Make a PNG image with "Hello World!" with programming APIs, in the shortest code possible

```
text("HeΠo World!",9,8);

```

---

24 char non-cheating solution:

```
text("Hello World!",9,9);

```
> 4 votes

# Answer
## Tcl/Tk, 34

```
pack [label .l -text Hello\ World]

```
> 3 votes

# Answer
## PowerShell: 162 124 114 or 20

---

## The Long Way Around

```
($t=($a='New-Object Windows.Forms')+".Label"|iex).Text='Hello World';($x=iex $a".Form").Controls.Add($t);$x.Show()

```

Since PowerShell really doesn't have any built-in GUI functionality, I'm having a hard time coming up with anything shorter than this which I feel really fits the original spirit of the challenge. (Or, at least, fits within the parameters several of us have assumed were implied.)

> **Changes from original:**
>
> * Removed window size definition. Apparently, it's optional and the default is plenty large enough.
> * Incorporated changes provided by SpellingD in comments. **Note: The window which spawns will hang - you'll need to kill PowerShell via Task Manager.**

---

## Alternative 20-Character Approach

Removing some assumed-implied requirements, we can also meet this challenge a-la Johannes Kuhn with this:

```
'Hello World';for(){}

```

Save as a .ps1 file. Make sure the system's ExecutionPolicy allows unsigned scripts. Right-click and select "Run with PowerShell".
> 3 votes

# Answer
# **AutoHotkey, 26**

```
GUI,Add,Text,,Hello World!

```
> 3 votes

# Answer
**AutoIt v3, 32**

```
ToolTip("Hello World")
Sleep(9^9)

```
> 3 votes

# Answer
# HTML, 11

```
Hello World

```

Screenshot:

I guess this shouldn't count, but I think it would be interesting to see such an answer here.
> 3 votes

# Answer
# Factor, 36 code + 23 imports = 59

```
USING: ui ui.gadgets ; "Hello World" <label> "" open-window

```

When this is run inside the listener, the imports will be brought in automatically. You only need them to deploy a standalone executable.
> 3 votes

# Answer
## Groovy, 68 27

Using console.

```
print"Hello World";for(;;);

```

Using Frame.

```
new java.awt.Frame(){{add new java.awt.Label("Hello World")}}.show()

```

Inspired by @swilliams Java answer.
> 2 votes

# Answer
## Ti84-Basic, 25

```
ClrHome
Disp "HELLO WORLD

```

## Arduino, 27

```
Serial.print("Hello World")

```

Place this in `void setup()`

## Game Maker Language, 40

```
show_message_ext("Hello World","","","")

```

I'm pretty sure this is the shortest way without adding any extension packages.
> 2 votes

# Answer
# Processing, 37 chars:

```
void draw(){text("Hello World",0,9);}

```

Various things used to reduce strokes:

* Sketch window is spawned by default; no need to manually create it
* Using `draw` is shorter than `setup` (although the text is then redrawn each frame)
* Uses default size, background, fill, font, and font size
* You don't actually need all 10 pixels height for the text
> 2 votes

# Answer
## C#, 93

```
u̶s̶i̶n̶g̶ ̶S̶y̶s̶t̶e̶m̶;̶c̶l̶a̶s̶s̶ ̶P̶r̶o̶g̶r̶a̶m̶{̶s̶t̶a̶t̶i̶c̶ ̶v̶o̶i̶d̶ ̶M̶a̶i̶n̶(̶)̶{̶C̶o̶n̶s̶o̶l̶e̶.̶O̶u̶t̶.̶W̶r̶i̶t̶e̶(̶"̶h̶e̶l̶l̶o̶ ̶w̶o̶r̶l̶d̶"̶)̶;̶C̶o̶n̶s̶o̶l̶e̶.̶R̶e̶a̶d̶K̶e̶y̶(̶)̶;̶}̶}̶

```

If you didn't need the screen to stay open, it'll be 81:

```
using System;class Program{static void Main(){Console.Out.Write("hello world");}}

```

As per shaming comment (so obvious, yet overlooked):

```
using System;class A{static void Main(){Console.Out.Write("hello world");Console.ReadKey();}}

```

Nice catch :)
> 2 votes

# Answer
**Bash** (36 chars)

`xmessage -buttons "" "Hello World!"`

Looks like crap, but works as requested.
> 2 votes

# Answer
# Ghostscript 50

```
0 0 moveto/Courier 20 selectfont(Hello World)show

```

Could make it 49 by using a 9-point font, but it's a little hard to read.

Can make a smaller window by invoking gs with a geometry argument for an additional 8 chars.

```
gs -g200x30 hello.ps

```
> 2 votes

# Answer
# C#, 72

```
class P{static int Main(){System.Console.Write("hello world");for(;;);}}

```

Based on the answer by @Noctis. I would have suggested it as a comment if I had enough Rep.
> 2 votes

# Answer
## Delphi - 73 62

```
uses Dialogs;begin MessageDlg('Hello World',mtCustom,[],0)end.

```

Edit after @manatwork and @Gareth 's suggestions. Which actually brings me to a character count of 62.
> 2 votes

# Answer
# Shell script: 56 character

```
convert -size 99x9 xc: -draw 'text 0,10 Hello\ World' x:

```

Sample output:
> 2 votes

# Answer
## Quomplex, 11

```
Hello World

```

When no output (`*`) is defined, Quomplex outputs the program's source code.
> 2 votes

# Answer
## Windows batch file, 18

```
@set/p=Hello World

```

Save as a batch file, and run by double clicking. Looks just how you'd expect.
> 2 votes

# Answer
# FLTK, 57 characters

```
Function{}{}{Fl_Window{}{}{Fl_Box{}{label{Hello World}}}}

```

Ungolfed:

```
Function {} {} {
    Fl_Window {} {} {
        Fl_Box {} {
            label {Hello World}
        }
    }
}

```

Sample output:
> 2 votes

# Answer
# Groovy, 77

```
import javax.swing.*
f=new JFrame()
f.add(new JLabel("Hello World"))
f.show()

```

Note: the window will be super tiny and you'll need to resize it to view the text.
> 1 votes

# Answer
# APLX, 44

```
'A' ⎕WI 'New' 'Document' 'text' 'Hello World'

```

You could probably get it down from there.
> 1 votes

# Answer
**Java - 157**

using DrawString

Ungolfed:

```
import java.awt.*;
class A extends Frame {
    public static void main(String[]a){
        new A().show();
    }
    public void paint(Graphics g)
    {
        g.drawString("Hello World",9,50);
    }
}

```

Golfed:

```
import java.awt.*;class A extends Frame{public static void main(String[]a){new A().show();}public void paint(Graphics g){g.drawString("Hello World",9,50);}}

```
> 1 votes

# Answer
## JavaScript, 32

```
open('javascript:"Hello World"')

```
> 1 votes

# Answer
# Python: 20 characters

```
input("Hello World")

```

Technically would be correct right? If you save it to a script and don't call it from a shell. Meh, I think the best python solution has been given already.
> 1 votes

# Answer
# C# 87

Ungolfed:

```
using s = System.Console;
class C
{
    static void Main()
    {
        s.Write("Hello World");
        s.Read();
    }
}

```

Golfed:

```
using s = System.Console;class C{static void Main(){s.Write("Hello World");s.Read();}}

```

Window will stay open until user inputs a carriage return
> 1 votes

# Answer
# C+xcb+Cairo 2540 (82 lines)

Not exactly short. :) This is literally the PNG hello world from the Cairo docs, with just enough xcb to open a window and find the parameters needed to register the window with Cairo.

```
//xcr.c
//cc -o xcr $(pkg-config --cflags --libs cairo xcb xcb-icccm) xcr.c -lcairo -lxcb -lxcb-icccm
#include <stdlib.h>
#include <string.h>
#include <cairo.h>
#include <cairo-xcb.h>
#include <xcb/xcb.h>
#include <xcb/xcb_image.h>
#include <xcb/xcb_aux.h>
#include <xcb/xcb_icccm.h>

int main (int argc, char *argv[])
{
    int width = 300, height = 400;
    int scrno;
    xcb_screen_t *scr;
    xcb_connection_t *connection;
    xcb_screen_iterator_t iter;
    xcb_drawable_t win;
    unsigned int white;
    xcb_visualtype_t *visual_type;
    xcb_depth_iterator_t depth_iter;

    connection = xcb_connect(NULL,&scrno);
    iter = xcb_setup_roots_iterator(xcb_get_setup(connection));
    for (; iter.rem; --scrno, xcb_screen_next(&iter))
        if (scrno == 0)
        {
            scr = iter.data;
            break;
        }
    win = xcb_generate_id(connection);
    white = scr->white_pixel;
    xcb_create_window(connection, XCB_COPY_FROM_PARENT,
            win, scr->root,
            0, 0,
            width, height,
            5,
            XCB_WINDOW_CLASS_INPUT_OUTPUT,
            scr->root_visual,
            XCB_CW_BACK_PIXEL,
            &white);
    xcb_icccm_set_wm_name(connection, win, XCB_ATOM_STRING, 8, strlen("xcr"), "xcr");
    xcb_map_window(connection, win);
    xcb_flush(connection);

    depth_iter = xcb_screen_allowed_depths_iterator(scr);
    for (; depth_iter.rem; xcb_depth_next(&depth_iter)) {
        xcb_visualtype_iterator_t visual_iter;

        visual_iter = xcb_depth_visuals_iterator(depth_iter.data);
        for (; visual_iter.rem; xcb_visualtype_next(&visual_iter)) {
            if (scr->root_visual == visual_iter.data->visual_id) {
                visual_type = visual_iter.data;
                goto visual_found;
            }
        }
    }
visual_found: ;

    {
        cairo_surface_t *surface =
            cairo_xcb_surface_create (connection, win, visual_type, width, height);
        cairo_t *cr = cairo_create (surface);

        cairo_select_font_face (cr, "serif", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
        cairo_set_font_size (cr, 32.0);
        cairo_set_source_rgb (cr, 0.0, 0.0, 1.0);
        cairo_move_to (cr, 10.0, 50.0);
        cairo_show_text (cr, "Hello, world");

        cairo_surface_flush(surface);
        xcb_flush(connection);

        sleep(100);

        cairo_destroy (cr);
        //cairo_surface_write_to_png (surface, "hello.png");
        cairo_surface_destroy (surface);
    }

    xcb_disconnect(connection);
    return 0;
}

```
> 1 votes

# Answer
# PureBasic

## Console Window - 42 bytes

```
OpenConsole()
Print("Hello World")
Input()

```

If console windows are not allowed, and actual GUI windows are required:

## GUI Window - 96 bytes

```
OpenWindow(0,0,0,99,99,"")
TextGadget(0,0,0,99,99,"Hello World")
While WindowEvent()<>13116:Wend

```
> 0 votes

# Answer
**Windows command shell, 24 characters**

Runs as is from command line or by saving to .cmd or .bat file.

```
start echo "Hello World"

```
> 0 votes

# Answer
# Lua + LÖVE: 57 characters

```
function love.draw()love.graphics.print("Hello World")end

```

Sample run:

```
bash-4.3$ ls -l
total 4
-rw-rw-r-- 1 manatwork manatwork 57 Aug  2 13:16 main.lua

bash-4.3$ love .

```

Sample output:
> 0 votes

# Answer
## HTML Application, 11

```
Hello World

```

Save the file as **something.hta** and run it. Unlike HTML viewed in a browser, an HTML Application does not add any extra chrome (e.g. adress bar) to the window.
> -1 votes

---
Tags: code-golf, graphical-output, hello-world
---


title: The jQuery showdown

text:
# Question
Title: The jQuery showdown
*Some time after this incident*

There are some of us who are against this defiling order of jQuery. It is an unholy presence, of which *must be exterminated*. I therefore call on you, the loyal to The New Kingdom of Reformation, to create a program that will eliminate such resistance. All code must be validated and searched for ANY and EVERY trace of jQuery. And, of course, your submission needs to be short (there has been another budget cut, and, unfortunately, it was in the storage department). And it cannot have defiling characters.

To get you up to speed, a **defiling character** is any of the following characters: `jJqQuUeErRyY$x0`. As has been said, the use of these characters is strictly prohibited, even in your own program. So don't use them. ALSO we're okay with dollar signs in numbers. So, anything of the form `n+(.nn)*$` is O.K. (You still shouldn't use `0`.)

Your program/code/etc. must validate an input program. If it contains any **defiling characters**, you must output `This programmer is guilty of Heresy. He must be burnt.`; if no such characters are found, you must output `Program validated. Clearance level 2 given.`.

# Bonuses and Penalties

* I personally admire the character the character `~`. For every two you use, I'll give you -1 byte. (i.e., every other `~` is free.)
* You may choose precisely one character from the excluded; you may then use this character in all of it's cases, HOWEVER: there is a +50% byte initial penalty, and then a +5 byte penalty for every instance of that character.
* -90% if you do not use any of the characters adjacent to `jquery` (just to be super safe) in your source code. These are (in addition): `iIkKpPsSzZXdDfF`
* -20% if, when given an invalid string, along with outputting the aforementioned text, you replace all invalid characters with `-` for a run of 1, `*` with a run less than 10, and `[]` with any longer run.
* -50 bytes if you do not find `JavaScript/i` or `Simplex` as having defiling characters.

---

# Reference Implementation

```
function validate() {
  var str = document.getElementById("input").value;
  var str2 = str.replace(/[jquery0]/gi,"").replace(/x/g,"").replace(/(\d+\.*\d*\d*\$)|\$/g,"$1"); // thanks Doorknob!
  var val;
  if (str2 == str) {
    val = "Program validated. Clearance level 2 given.";
  } else {
    val = "This programmer is guilty of Heresy. He must be burnt.";
  }
  document.getElementById("output").value = val;
}
```

```
textarea{width: 600px;}
```

```
<textarea id="input" onkeyup="validate()"></textarea>
<br><br>
<textarea id="output" disabled></textarea>
```

# Answer
# CJam, ~~160~~ ~~139~~ 13.4 bytes

```
0000000: 22 cf 97 d9 87 d1 85 82 89 8d d1 db 8d 80 a8 af b3 a3  ".................
0000012: b0 b7 82 8e 80 bd c3 ca 89 85 d6 89 84 80 b2 c6 c7 d1  ..................
0000024: 7e ce d0 cd c5 d0 bf cb cb c3 d0 7e c7 d1 7e c5 d3 c7  ~..........~..~...
0000036: ca d2 d7 7e cd c4 7e a6 c3 d0 c3 d1 d7 8c 7e a6 c3 7e  ...~..~.......~..~
0000048: cb d3 d1 d2 7e c0 c3 7e c0 d3 d0 cc d2 8c 80 80 ae d0  ....~..~..........
000005a: cd c5 d0 bf cb 7e d4 bf ca c7 c2 bf d2 c3 c2 8c 7e a1  .....~..........~.
000006c: ca c3 bf d0 bf cc c1 c3 7e ca c3 d4 c3 ca 7e 90 7e c5  ........~.....~.~.
000007e: c7 d4 c3 cc 8c 80 9d 22 7b 39 33 7e 2b 7d 25 7e        ......."{93~+}%~

```

The above is a hexdump that can be reversed with `xxd -r -c 18`. Try it online.

The code itself consists of **142 bytes**. It contains a total of sixteen **~** characters (**-8 bytes**), but no jQuery-adjacent characters (**-90%**).

### How it works

The match `n+(.nn)*$` really boils down to *a digit followed by a dollar sign*.

First of all,

```
"<bunch of characters>"{93~+}%~

```

adds **-94** to all code points of that string and evaluates the result.

The executed code is:

```
q       e# Read all input from STDIN.
9{      e# For each I in [0 ... 8]:
  )s    e#   Increment and cast to string.
  '$+   e#   Append a dollar sign.
  /s    e#   Split the input at occurrences. Flatten the result.
}/

"JQUERY$0"

_el+'x+ e# Append a lowercase copy and "x" to that string.
&       e# Intersect with the modified input.

"This programmer is guilty of Heresy. He must be burnt."
"Program validated. Clearance level 2 given."

?       e# Ternary if; select the corresponding message.

```
> 19 votes

# Answer
## Minkolang 0.9, 346-3 = 343 bytes

Longest program yet.

```
#66*68*d5*2:88*5+d5+d7+d1+d3+d4+6[3i+c48*+]2c"N"11-p(od4&k13w35*[dic=,5&kk11w] )
 725*35*48*68*3+5[66+c2~g2p]27*48*1-d2+d6+d8+5[9c2~g2p]37*67*d8+3[67+c2~g2p]55*57*2[77+c2~g2p]X11-2w
"This p og amm   is g ilt  of H   s . H  m st b  b  nt."(O).
 X2546*3[66+c2~g4p]44*d6+47*d3+d2+d8+6[9c2~g4p]X11-4w
"P og am validat d. Cl a anc  l v l 2 giv n."(O).

```

Try it here.

### Explanation

The first line does three things: 1) build up the stack with the forbidden characters, 2) put a much-needed `x` in the right place (the space at the end), and 3) loop through the input, jumping to the appropriate line.

The second and fourth lines do the same thing: replace every gap in the succeeding line with the appropriate character. They jump to the next line at the end.

The third and fifth lines simply push the required string on the stack and print it out.
> 7 votes

# Answer
# PHP, (204\*1.5 + 5) * .1 = 31.1

```
<?=eval(~šœ—.ß..š˜ ’ž‹œ—×ØÐ¤•ŽŠš.†££Û‡Ï¢Ð–ØÓ..š˜ .š.“žœš×ØÐ¤ÎÒÆ¢Ô×££Ñ¤ÎÒÆ¢„Í‚ÖÀ££ÛÐØÓÝÝÓÛž.˜‰¤Î¢ÖÖÀØ«—–Œß...˜.ž’’š.ß–Œß˜Š–“‹†ß.™ß·š.šŒ†Ñß·šß’ŠŒ‹ß.šß.Š.‘‹ÑØÅØ¯..˜.ž’ß‰ž“–›ž‹š›Ñß¼“šž.ž‘œšß“š‰š“ßÍß˜–‰š‘ÑØÄ);

```

This dump was made using gnuwin32 `hexdump`. Reverse with `hex2bin`.

```
00000000: 3C 3F 3D 65 76 61 6C 28 - 7E 9A 9C 97 90 DF 8F 8D |<?=eval(~       |
00000010: 9A 98 A0 92 9E 8B 9C 97 - D7 D8 D0 A4 95 8E 8A 9A |                |
00000020: 8D 86 A3 A3 DB 87 CF A2 - D0 96 D8 D3 8F 8D 9A 98 |                |
00000030: A0 8D 9A 8F 93 9E 9C 9A - D7 D8 D0 A4 CE D2 C6 A2 |                |
00000040: D4 D7 A3 A3 D1 A4 CE D2 - C6 A2 84 CD 82 D6 C0 A3 |                |
00000050: A3 DB D0 D8 D3 DD DD D3 - DB 9E 8D 98 89 A4 CE A2 |                |
00000060: D6 D6 C0 D8 AB 97 96 8C - DF 8F 8D 90 98 8D 9E 92 |                |
00000070: 92 9A 8D DF 96 8C DF 98 - 8A 96 93 8B 86 DF 90 99 |                |
00000080: DF B7 9A 8D 9A 8C 86 D1 - DF B7 9A DF 92 8A 8C 8B |                |
00000090: DF 9D 9A DF 9D 8A 8D 91 - 8B D1 D8 C5 D8 AF 8D 90 |                |
000000a0: 98 8D 9E 92 DF 89 9E 93 - 96 9B 9E 8B 9A 9B D1 DF |                |
000000b0: BC 93 9A 9E 8D 9E 91 9C - 9A DF 93 9A 89 9A 93 DF |                |
000000c0: CD DF 98 96 89 9A 91 D1 - D8 C4 29 3B             |          );|
000000cc;

```

(I'm confused about the order in which to apply the bonus/penalty, so I assumed order as written.)

Uses the character "e" in eval. Thanks to PHP string inversion magic, this manages to avoid all the other jquery and near-jquery characters.

The inverted string contains this code (formatted for clarity)

```
echo preg_match('/[jquery\\$x0]/i',
  preg_replace('/[1-9]+(\\.[1-9]{2})?\\$/',"", $argv[1]))
  ? 'This programmer is guilty of Heresy. He must be burnt.'
  : 'Program validated. Clearance level 2 given.';

```

Since this code doesn't have a return statement, `eval` returns null so `<?=eval` doesn't do anything. (It's just to avoid `<?php`)
> 5 votes

# Answer
# \>\<\>, 184 bytes

```
"/6VO+K;[.N'G|(p
~<.1+f9o*-21-*5-1' ';!?l<"K),4):.{%:/27:'67m{X/6:):-86{/6%6/{i{42%6-m"
f +1.>"m'-)&9{69{'(&.{6S{m"'"(6)6S{5,{"'"'/2&4{(2{)6..:)4,)+{(23G"8
!^ag?/i:1+?
p>l?!^1' '5*@@-a

```

This can be a *bit* shorter with unprintables, but here's a printable version just for fun. Won't work with the online interpreter since it does puts outside of the codebox.

This program encodes both strings as

```
G32({+),4):..6){2({4&2/'"{,5{S6)6("m{S6{.&('{96{9&)-'m
K),4):.{%:/27:'67m{X/6:):-86{/6%6/{i{42%6-m

```

which is each code point subtracted from 155. Similarly,

```
6V/O+K;[.N'G|(p

```

encodes the forbidden characters, with code points subtracted from 160.

The last line merely sets the coordinates `(forbidden char, 10)` to 1, forming a lookup table. The fourth line then checks each input char using the lookup table, outputting the heresy message if 1 else continuing on. On EOF, we move up to output the clearance message.
> 4 votes

# Answer
## "Javascript" 840\*2+14\*5=1750 ;)

I'm soooo close, just need to find a way to get rid of the r's

Stack isn't letting me paste the code in here as there are several non printing ASCII characters in the strings, so here's a hexdump from xxd

```
0000000: 6576 616c 2868 3d27 272c 643d 5b7b 613a  eval(h='',d=[{a:
0000010: 5b2e 2e2e 2770 5b6c 1a6d 375e 695d 6f67  [...'p[l.m7^i]og
0000020: 5f68 6e28 5d6c 5f5b 6e5f 3f66 5f67 5f68  _hn(]l_[n_?f_g_h
0000030: 6e22 1c6d 5d6c 6327 5d2c 623a 367d 2c7b  n".m]lc'],b:6},{
0000040: 613a 5b27 7e27 5d2c 623a 2d31 347d 2c7b  a:['~'],b:-14},{
0000050: 613a 5b2e 2e2e 276e 1c23 356d 286d 6c5d  a:[...'n.#5m(ml]
0000060: 371c 2929 5d69 5e5f 2864 6b6f 5f6c 7328  7.))]i^_(dko_ls(
0000070: 5d69 6729 646b 6f5f 6c73 5c27 2c28 2b28  ]ig)dko_ls\',(+(
0000080: 2e28 646d 1c26 5e69 5d6f 675f 686e 285c  .(dm.&^i]og_hn(\
0000090: 5c69 5e73 285b 275d 2c62 3a36 7d2c 7b61  \i^s(['],b:6},{a
00000a0: 3a5b 277e 272c 277e 275d 2c62 3a2d 3134  :['~','~'],b:-14
00000b0: 7d2c 7b61 3a5b 2e2e 2e27 5f68 5e3d 6263  },{a:[...'_h^=bc
00000c0: 665e 226d 2326 1e22 1c1d 696f 6e1c 2328  f^"m#&."..ion.#(
00000d0: 705b 6622 686f 6666 1b37 1e22 1c1d 6368  p[f"hoff.7."..ch
00000e0: 1c23 2870 5b66 2223 286d 275d 2c62 3a36  .#(p[f"#(m'],b:6
00000f0: 7d2c 7b61 3a5b 277e 275d 2c62 3a2d 3134  },{a:['~'],b:-14
0000100: 7d2c 7b61 3a5b 2e2e 2e27 6663 6e22 1c1c  },{a:[...'fcn"..
0000110: 2328 6c5f 705f 6c6d 5f22 2328 6469 6368  #(l_p_lm_"#(dich
0000120: 221c 1c23 2867 5b6e 5d62 2229 275d 2c62  "..#(g[n]b")'],b
0000130: 3a36 7d2c 7b61 3a5b 277e 275d 2c62 3a2d  :6},{a:['~'],b:-
0000140: 3335 7d2c 7b61 3a5b 2e2e 2e27 6444 6b4b  35},{a:[...'dDkK
0000150: 6f4f 5f3f 6c4c 7353 1e2a 7257 7656 1e22  oO_?lLsS.*rWvV."
0000160: 391b 2227 5d2c 623a 367d 2c7b 613a 5b2e  9."'],b:6},{a:[.
0000170: 2e2e 275b 312d 395d 5b31 2d39 5d5c 5c2e  ..'[1-9][1-9]\\.
0000180: 293f 5b27 5d2c 623a 312d 317d 2c7b 613a  )?['],b:1-1},{a:
0000190: 5b2e 2e2e 272b 5c27 3357 2329 6123 391c  [...'+\'3W#)a#9.
00001a0: 275d 2c62 3a36 7d2c 7b61 3a5b 277e 275d  '],b:6},{a:['~']
00001b0: 2c62 3a2d 3436 7d2c 7b61 3a5b 2e2e 2e27  ,b:-46},{a:[...'
00001c0: 6c69 616c 5b67 1a70 5b66 635e 5b6e 5f5e  lial[g.p[fc^[n_^
00001d0: 281a 3d66 5f5b 6c5b 685d 5f1a 665f 705f  (.=f_[l[h]_.f_p_
00001e0: 661a 2c1a 6163 705f 6828 1c34 1c4e 6263  f.,.acp_h(.4.Nbc
00001f0: 6d1a 275d 2c62 3a36 7d2c 7b61 3a5b 277e  m.'],b:6},{a:['~
0000200: 275d 2c62 3a2d 3134 7d2c 7b61 3a5b 2e2e  '],b:-14},{a:[..
0000210: 2e27 6c69 616c 5b67 675f 6c1a 636d 1a61  .'lial[gg_l.cm.a
0000220: 6f63 666e 731a 6960 1a42 5f6c 5f6d 7328  ocfns.i`.B_l_ms(
0000230: 1a42 5f1a 676f 6d6e 1a5c 5c5f 1a5c 5c6f  .B_.gomn.\\_.\\o
0000240: 6c68 6e28 1c23 275d 2c62 3a36 7d5d 2e6d  lhn(.#'],b:6}].m
0000250: 6170 2864 3d3e 2876 3d27 272c 773d 642e  ap(d=>(v='',w=d.
0000260: 612e 6d61 7028 633d 3e53 7472 696e 672e  a.map(c=>String.
0000270: 6672 6f6d 4368 6172 436f 6465 2863 2e63  fromCharCode(c.c
0000280: 6861 7243 6f64 6541 7428 292b 642e 6229  harCodeAt()+d.b)
0000290: 292c 772e 666f 7245 6163 6828 287a 2c69  ),w.forEach((z,i
00002a0: 2c61 293d 3e7b 6966 2869 2532 2976 3d76  ,a)=>{if(i%2)v=v
00002b0: 2e63 6f6e 6361 7428 615b 692d 315d 2e63  .concat(a[i-1].c
00002c0: 6f6e 6361 7428 7a29 297d 292c 762e 636f  oncat(z))}),v.co
00002d0: 6e63 6174 2877 2e6c 656e 6774 6825 323f  ncat(w.length%2?
00002e0: 772e 706f 7028 293a 2727 2929 292c 642e  w.pop():''))),d.
00002f0: 666f 7245 6163 6828 287a 2c69 2c61 293d  forEach((z,i,a)=
0000300: 3e7b 6966 2869 2532 2968 3d68 2e63 6f6e  >{if(i%2)h=h.con
0000310: 6361 7428 615b 692d 315d 2e63 6f6e 6361  cat(a[i-1].conca
0000320: 7428 7a29 297d 292c 682e 636f 6e63 6174  t(z))}),h.concat
0000330: 2864 2e6c 656e 6774 6825 323f 642e 706f  (d.length%2?d.po
0000340: 7028 293a 2727 2929 0a                   p():'')).

```
> 1 votes

---
Tags: code-golf, string, restricted-source
---