title: Generate Esolangs

text:
# Question
Title: Generate Esolangs
Given a file named `hello_world` that contains 2-100 bytes of printable ASCII, create a Turing-complete language in which `hello_world` is a valid program that prints "Hello World!". The output should be two files: a compiler or interpreter, and a text file with the language spec.

**Rules**

* Shortest code wins. Length of (any of the) output doesn't matter.
* The generated compiler/interpreter must tokenize `hello_world` into at least two tokens, neither of which are ignored, and can't care about the filename.
* Your program can't use external resources (no cloning its own compiler).
* The generated code can be in any language, and can compile to any language.

# Answer
Let's give it a try (and let everyone else copy it)

## Tcl

```
set f [open hello_world rb]
set h [split [read $f] {}]
for {set i 0} {$i<256} {incr i} {if {[set c [format %c $i]] ni $h} break}
set f [open i w]
puts $f [string map [list @1 [lindex $h 0] @2 [lindex $h 1] @3 $c] {set s 0;set i 0
set f [open [lindex $argv0] rb]
set c [split [read $f] {}]
foreach d $c {incr i
if {$d eq @1 && $s==0} {puts -nonewline "Hello ";incr s}
if {$d eq @2 && $s==1} {puts "World!"}
if {$d eq @3} {eval [join [lrange $c $i end] {}];break}}}]
puts [open d wb] [string map [list @1 [list [lindex $h 0]] @2 [list [lindex $h 1]] @3 [list $c]] {At the beginning the state is 0. Commands:
@1: If the state is 0, prints "Hello " without newline, increment the state.
@2: If the state is 1, prints "World!" with newline, flushes stdout and increases the state.
@3: Treats the rest of the file as Tcl.}]

```
> 3 votes

# Answer
## Perl, 271 chars

```
@e=qw'die"Hello\x20World!\n" $i-- $i++ $a[$i]-- $a[$i]++ push@s,$p $a[$i]?$p=$s[-1]:pop@s print+chr$a[$i] $a[$i]=ord<>';
$/=\1;@k=(<>..Z,A..Z);
say"# $k[$_]: $e[$_]"for 0..8;say;
say"\$e{\"\Q$k[$_]\E\"}=sub{$e[$_]};"for 0..8;
say'$/=\1;@c=<>;&{$e{$c[$p++]}||sub{}}while$p<@c'

```

(The code above has some non-essential line breaks inserted for readability. All line breaks may be removed without affecting the behavior, and should not be counted for scoring purposes.)

Run with `perl -M5.010` to enable the `say` feature. Reads the input program from standard input (or from a file given as a command line argument), prints an interpreter to standard output. The output is also a Perl script, and should be executed the same way.

The (rudimentary) language spec is included as comments at the beginning of the interpreter, and is formatted as a list of characters and the Perl commands each of them will execute. In the spec, `$p` stands for the program counter (which points to the next instruction to execute), `@s` for the loop stack, `$i` for the tape index and `@a` for the tape.

---

Basically, the language executed by the interpreter is exactly what ugoren suggested in the comments: a simple variant of Brainf\*ck, with an extra command that prints `Hello World!` and ends the program. This extra command is mapped to the first character of the input program, while the other commands are mapped to subsequent letters. All unrecognized characters are ignored.

For example, using the input `AAAAAA`, the output will look like this:

```
# A: die"Hello\x20World!\n"
# B: $i--
# C: $i++
# D: $a[$i]--
# E: $a[$i]++
# F: push@s,$p
# G: $a[$i]?$p=$s[-1]:pop@s
# H: print+chr$a[$i]
# I: $a[$i]=ord<>

$e{"A"}=sub{die"Hello\x20World!\n"};
$e{"B"}=sub{$i--};
$e{"C"}=sub{$i++};
$e{"D"}=sub{$a[$i]--};
$e{"E"}=sub{$a[$i]++};
$e{"F"}=sub{push@s,$p};
$e{"G"}=sub{$a[$i]?$p=$s[-1]:pop@s};
$e{"H"}=sub{print+chr$a[$i]};
$e{"I"}=sub{$a[$i]=ord<>};
$/=\1;@c=<>;&{$e{$c[$p++]}||sub{}}while$p<@c

```

Running the resulting code above with the same input produces the expected output:

```
Hello World!

```

whereas running the same code with the input `EEEEEEFDCEEEEBGCFDCECEEEEBBGCEEFDCEHBG` (transliterated from this answer) prints:

```
abcdefghijklmnopqrstuvwxyz

```

Ps. To convert normal Brainf\*ck code to the variant understood by this interpreter, you can use the transliteration:

```
tr/<>\-+[].,/B-I/

```

where `B-I` should be replaced by the appropriate range of command letters as per the generated spec.

Notes on the BF implementation:

* The tape is single-ended, with the read/write head starting at cell 0. Moving the head to a negative position might not cause an error, but will produce weird effects related to Perl's array indexing and should be considered undefined behavior.
* Cell values do *not* wrap around. Technically, each cell is stored as a double, meaning that at some point the value will saturate and further inc/decrements will have no effect. You'll die of boredom before that happens, though.
* Character I/O depends on Perl's I/O layers. By default, input values are unsigned bytes, and attempting to output values outside the range 0 – 255 gives a warning message. Passing the `-CS` switch to Perl will enable Unicode I/O (encoded as UTF-8), though. Input at EOF yields a zero. To supply both a program and its input on stdin, separate them with a `Ctrl`+`D` character (`"\cD"` or `"\x05"`).

**Edit:** I later realized that there's a major difference between the language I implement above and real Brainf\*ck: in my language, the loop condition is checked at the *end* of the loop, rather than at the beginning, which means that every loop executes at least once. In effect, loops in my language behave like `do``while` loops in C-ish languages, whereas those in normal BF behave like plain `while` loops.

As it happens, the difference doesn't matter for the example program above, since all its loops run at least once anyway. What I'm not quite sure about is whether the proof of BF's Turing-completeness can still be made to apply to my variant of the language or not. It might be possible, but it's going to be tricky without any easy way to implement an `if` statement.

I suppose I could fix my program to behave more like normal BF, but it would be a pain in the ass to do without a major redesign of the execution model. :(
> 2 votes

---
Tags: code-golf, interpreter
---


title: When is a giraffe not a giraffe?

text:
# Question
Title: When is a giraffe not a giraffe?
I hope this kind of "riddle" is ontopic in Programming Puzzles & Code Golf.

Give an example of a situation where the C# method below ***returns `false`***:

```
public class Giraffe : Animal
{
  public bool Test()
  {
    return this is Giraffe;
  }
}

```

Rules: The code lines above must not be changed in any way, but you would put the code into an application so that the "project" compiles and the method is called. When run, the method must return `false`. The solution I have in mind, does not emit its own IL at run-time or similar "exotic" things, it's an ordinary instance method call.

# Answer
> 29 votes
Yay, found it!

```
public class Animal
{
    public class Giraffe { } // 1
}
public class Giraffe : Animal // 2
{
    public bool Test()
    {
        return this is Giraffe;
    }
}

```

Since `Giraffe 1` is a member of `Animal`, and `Giraffe 2` is one level further out, the name `Giraffe` in the `is` test refers to the former (section 7.6.2 in the C# 5 spec).

Visual Studio shows a warning for `this is Giraffe`:

> The given expression is never of the provided type

which is obviously true, since it's the whole point :)

You cannot put `Giraffe 1` directly inside `Giraffe 2`, because

> member names cannot be the same as their enclosing type

– but such a rule does not exist for derived classes.

Neat problem, took me a while.

---
Tags: c#, programming-puzzle
---


# Question
Title: Write a program with one & only if statement that
## Challenge: You Are The Teacher

Everyone knows that simple task of receiving a grade, and telling if the student:

> * is approved,
> * will attend the summer school, or
> * failed.

In this challenge, you must write a program that does that, but using the maximum of one `if` statement (also ternary operators count as `if`).

The grade will be an integer from 0 to 10.

```
situation   outputs
-------------------------
grade >= 7: Approved
grade >= 3: Summer School
grade  < 3: Failed

```

You can do **whatever** you want, write in any language.

Fastest working answer wins.

# Answer
### Ruby

```
def x(mark)
    possible_results = ['','Failed', 'Failed', 'Summer school', 'Approved']

    index = (mark + 1).to_s(2).length

    possible_results[index]
end

```

This uses the fact that the length of the binary representation of the numbers 0-10 is pretty close to the required classification.

Online test: http://ideone.com/y0kLqY
> 5 votes

# Answer
### Ruby

Using regular expressions:

```
puts "Failed012Summer School3456Approved78910"[/\D*(?=\d*#{gets.chomp})/]

```

Plain array indexing:

```
puts ["Failed","Summer School","Approved"][(gets.to_i+1)/4]

```
> 7 votes

# Answer
**Python2: 65**

Bonus: it doesn't use *any* conditional expression.

```
g=input();print("Approved","Summer School","Failed")[(g<7)+(g<3)]

```

Example output:

```
>>> g=input();print("Approved","Summer School","Failed")[(g<7)+(g<3)]
10
Approved
>>> g=input();print("Approved","Summer School","Failed")[(g<7)+(g<3)]
7
Approved
>>> g=input();print("Approved","Summer School","Failed")[(g<7)+(g<3)]
6
Summer School
>>> g=input();print("Approved","Summer School","Failed")[(g<7)+(g<3)]
3
Summer School
>>> g=input();print("Approved","Summer School","Failed")[(g<7)+(g<3)]
2
Failed

```
> 5 votes

# Answer
# C

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

int min(int a, int b)
{
    return (a < b) * a + (a >= b) * b;
}

const char *grade_to_string(int grade)
{
    const char * grades[3] = { "Failed", "Summer school", "Approved" };
    return grades[min(((grade + 1) >> 2), 2)];
}

int main(int argc, char *argv[])
{
    int grade = atoi(argv[1]);
    printf("%d = %s\n", grade, grade_to_string(grade));
    return 0;
}

```

Test:

```
$ gcc -Wall -O3 grade.c
$ time for i in $(seq -1 20) ; do ./a.out $i ; done
-1 = Failed
0 = Failed
1 = Failed
2 = Failed
3 = Summer school
4 = Summer school
5 = Summer school
6 = Summer school
7 = Approved
8 = Approved
9 = Approved
10 = Approved
11 = Approved
12 = Approved
13 = Approved
14 = Approved
15 = Approved
16 = Approved
17 = Approved
18 = Approved
19 = Approved
20 = Approved

real    0m0.120s
user    0m0.025s
sys     0m0.042s
$

```
> 3 votes

# Answer
## Perl

```
sub f {
  my $grade = shift;
  my $result = 0;
  for (++$grade ; $grade > 1; $grade >>= 1) {
    ++$result;
  }
  return ("Failed", "Failed", "Summer school", "Approved")[$result];
}

```

(The for-loop test constitutes the program's one permitted "if statement".)
> 2 votes

# Answer
# R

```
g=function(x)cut(x,c(0,3,7,10),
                 labels=c("Failed","Summer school","Approved"),
                 right=FALSE, include=TRUE)

```

Usage:

```
> g(2)
[1] Failed
Levels: Failed Summer school Approved
> g(7)
[1] Approved
Levels: Failed Summer school Approved
> g(3)
[1] Summer school
Levels: Failed Summer school Approved

```

Function `cut` in R converts a numeric into a factor (categorical) according to the interval in which it falls. It is vectorized:

```
> g(0:10)
[1] Failed       Failed       Failed       Summer school Summer school Summer school Summer school
[8] Approved      Approved      Approved      Approved
Levels: Failed Summer school Approved

```
> 1 votes

# Answer
# Awk

```
{
  print check($1,0,2,"Failed") check($1,3,6,"Summer School") check($1,7,10,"Approved")
}

function check(grade,lower,upper,result)
{
  if (grade>=lower && grade<=upper) return result
}

```

(There are enough clever solutions, so I felt the need to post a brute force one too.)

Sample run:

```
bash-4.1$ for i in {0..10}; do echo -n $i\ ; awk grade.awk <<< $i; done
0 Failed
1 Failed
2 Failed
3 Summer School
4 Summer School
5 Summer School
6 Summer School
7 Approved
8 Approved
9 Approved
10 Approved

```
> 0 votes

# Answer
## APL

```
'Failed' 'Summer School' 'Approved'⌷⍨+/⎕≥0 3 7

```

Explanation:

* `⎕≥0 3 7`: read input, see if it is bigger or equal to 0, 3 and 7 (this gives a vector of bits, i.e. if the input is `5` this gives `1 1 0`)
* `+/`: sum the vector (giving an index into the list)
* `⌷⍨`: select the corresponding string from the list
> 0 votes

# Answer
Using Javascript, Thanks to @Bakuriu

```
function decision(g) {
    var d = ["Approved","Summer School","Failed"];
    return d[(g<7)+(g<3)]
}

console.log(decision(2)); ==> Failed
console.log(decision(5)); ==> Summer School
console.log(decision(9)); ==> Approved
console.log(decision(1)); ==> Failed
console.log(decision(4)); ==> Summer School

```
> 0 votes

# Answer
# Java

```
public static String getFeedback(int grad) {
    String str = grad>=7? "Approved" : grad>=3 ?  "Summer School" : grad<3 ? "Failed"  : "";
    return str;
}

```
> -3 votes

---
Tags: code-challenge
---


title: Speak digits from 0 to 9 aloud

text:
# Question
Title: Speak digits from 0 to 9 aloud
Inspired by this question from electronics.SE, here's a challenge for you:

**Write a program or subroutine that takes in a sequence of decimal digits (0 to 9) and speaks them aloud, *without* using an existing speech synthesis tool.**

### Input:

You may ask for the input digits to be provided in any reasonable format, e.g. as a string of ASCII digits, an array of integers, a BCD-encoded number, etc. If your solution is an executable program, you may take the input as a command line parameter, read it from standard input, or obtain it in any other reasonable manner.

Your program *must* be able to speak **at least eight digits** per invocation. You *may* assume that the first digit is not zero, unless it is the only digit.

### Output:

Your program may either speak the numbers directly using an audio device, or it may output a playable sound file. The output file, if any, may be in any standard audio format, or it may consist of raw sample data. If you output raw sample data, please note the appropriate parameters for playback (sample rate, bits per sample, endianness, signed/unsigned, # of channels). Formats supported by aplay are preferred.

You are free to decide the details on how the numbers will be spoken, but your output should consist of English language digits spoken in a manner **understandable to a typical English speaker**, and it should be clear enough for the listener to be able to accurately transcribe a spoken eight-digit random number. No, just beeping *n* times doesn't count. Don't forget to include pauses between the digits.

### Scoring:

Standard scoring rules apply: Your score is the length of your code in bytes or, if your code is written in Unicode text, in Unicode characters. Lowest score wins. Any language goes.

As the original question on electronics.SE was about embedded programming, I felt it would be appropriate to toss a bone to authors using low-level languages: if your solution is written in a compiled language, you may choose to count the length of the **compiled executable file** in bytes as your score. (Yes, precompiled bytecode, such as a Java `.class` file, is OK too.) If you choose to make use of this option, please include a copy of the compiled executable in your answer (e.g. as a hex dump) along with your source code and the compiler version and options you used to generate it.

An **honorable mention**, along with a +50 rep bounty, will be granted to the first answer that also meets the criteria of the original question, i.e. is capable of running on an embedded MCU with 4 kb of flash and 1 kb of SRAM.

### Restrictions:

You may not make use of any **files or network resources** that are not part of your chosen language's standard runtime environment, unless you count the length of said files or resources as part of your score. (This is to disallow e.g. loading audio samples from the web.)

You may also not use any pre-existing **speech synthesis tools or libraries** or compilations of audio data (unless you also count their size as part of your score), *even if* they're included in your chosen language's standard runtime environment.

# Answer
# ruby - 3710 = 90 characters code + 3620 bytes data

```
require'zlib'
$><<$*[0].chars.map{|x|Zlib::Inflate.inflate File.open(x).read}.join(?0*5e3)

```

input: a single command line argument, the number to read

output: raw sound data, PCM 8bit/8kHz

This can read any input string, as long as

* it only contains characters that are valid file names. for only four chars, you can enlarge that set to all characters.
* you have the neccessary files.
* why oh you space dee oh en apostrophe tee space em i en dee space tee aitch i es period

`5e3` encodes the pause between two words. Here, 5ksamples ~= 0.6s. Tweak as desired.

Now, the tricky part is to get the sample files in 4K and yet be able to decompress them easily and in sufficient quality. Here is how I got them:

Now, one has to choose a sample rate and decimation amount. Too much, and the sound won't be understandable. Too little, and you don't fit. I have settled for 8kHz/3b. There they are: https://github.com/honnza/drops/raw/master/digits.zip

* 8KHz * 4b/sample and higher quality - too big
* 8KHz * 3b/sample - low quality, but it fits into 4K
* 8KHz * 2b/sample - kch kchhhhhhhhh \[not understandable\]
* 2KHz * 8b/sample - too big
* 2KHz * 3b/sample - kch kchhhhhhhhh
* 1KHz * 8b/sample - kch kchhhhhhhhh

Here's the decimation script:

```
require'zlib'
Dir.glob "*.raw" do |fname|
  File.open fname[/\d/], "wb" do |out|
    File.open fname do |input|
      bytes = input.bytes.to_a
      bytes.map! {|x|x&0xE0}
      dfl = Zlib::Deflate.deflate(bytes.pack("C*"),9)
      dfl.each_byte do |byte|
        out.print byte.chr
      end
      puts "done #{fname}: #{dfl.size}"
    end
  end
end

```

As for the original challenge: there are 476 bytes of space for code and the file table. This might be slightly too much depending on how tiny we can get with a DEFLATE library. If neccessary, we can cut a few corners here and there by cropping the audio samples a bit more aggresively. `[fo:r]` or `[o:]` doesn't really matter but it saves bytes. I have been somewhat benevolent when cropping the numbers. Also, a different decimation scheme or sacrificing some decimation for downsampling might help - I'll toy with these later. Also, dropping the DEFLATE headers might save a tiny amount of space.

Concatenating sound samples is quite easy, but 4K is a little cramped. If you are not bound by 4k space, I suggest less decimation. 4 bits per sample actually fares quite well and is only slightly bigger.
> 11 votes

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


# Question
Title: Golf you a Double Quine for greater good!
Good Evening Ladies and Gentleman.

Tonight - we have a code challenge. A competition that will be defined not in the amount of points (a la Asteroids) but simply whether you can finish it (a la Zelda). And for the sake of comparison, the amount of bytes (uh... but you said...).

Your challenge is to compose a single quine that compiles in both WhiteSpace and any other language of your choice. Both quines must have absolutely identical output (which as a quine is absolutely identical to the source code). Your quine must be more then 3 bytes in length.

Your score is the size of your source code in bytes.

Given that this challenge involves WhiteSpace, please escape your answers so that they are clear - preferably in the C style. Your score is the original source in bytes - not the escaped version.

Good luck.

# Answer
## Whitespace and Perl, ~~992~~ 975 characters

Good Evening Ladies and Gentlemen.

To start with, here is my submission encoded in base64, which I feel is the best way to communicate a large Whitespace program. (You really don't want to use an encoding that leaves any whitespace as-is, so there's no point in selecting something more "readable".)

```
c2F5PDwgeDI7c2F5PDwwLDAgIApzYXk8PCB4MjtzYXk8PDAsMCAgCgoJCQogICAJCSAgCSAgCSAJ
CSAgCSAgCQkgCSAJIAkJCQkJICAJCSAJCQkgCQkJCQkgCSAJIAkJIAkgCSAgIAkJCQkJICAgCQkg
IAkgCQkgCSAJCSAJICAgIAkJCQkgCSAgCSAJCSAJICAgIAkgCQkgICAJICAgICAgCQkJIAkJCQkJ
IAkJCSAJCQkJICAgICAJCQkgCSAgICAgIAkJCQkJICAgICAgCQkgICAJCSAgICAJCQkJCQkJCSAg
CSAJIAkgICAJCQkgICAJCQkJCSAgCQkJCSAJICAgIAkgCQkJCQkgCSAgICAgCSAgCSAJICAgICAg
CSAgICAJICAgICAJCSAgIAkJCSAJIAkJCQkJCSAJCSAJIAkgICAgICAgCQkgIAkgICAgICAgICAg
IAkJICAgCSAJCQkgCSAgICAgCQkJCQkJIAkgICAgCQkJCSAJCQkJICAJCQkgICAJCQkgCSAgCSAg
IAkJCQkgIAkJIAkJCSAgIAkJCSAJCQkgCQkJICAJCSAJICAJIAkJCSAJIAkgCQkgICAgIAkgCSAJ
ICAJICAJIAkJICAgICAJIAkgICAgCQkJCSAgCSAJCSAJIAkJIAkgIAkgCSAJCSAJCSAJCSAJCQkg
CQkJICAgIAkJCSAgCSAgCQogICAJICAgICAJCQkJCSAJCSAJIAkgCSAJICAJCQkgICAJICAgCSAg
ICAJCSAJICAgICAgICAgCSAgIAkJCQkgCQkgICAgCQkgCSAJICAJCQkgCQkJCSAJCQkgICAJICAg
IAkgCSAJCQkgIAkJCQkgCSAJCSAJIAkgCQkJCSAJICAJIAkJIAkgICAJCiAKICAKICAgIAogCSAg
CQoKICAJCiAKICAgIAkJCQkgCSAKCSAJCQkKICAgICAJCQkJIAkgCgkgCSAgCiAgIAkJCgkgIAoK
CQkJCiAKCgoJIAkKICAgCSAgIAkgIAoKIAkKIAkgIAkKCiAJIAogICAJIAoKIAkKCiAJIAoKIAkK
CQogCSAgIAkgCgogCQoKCgoKICAgCiAgIAogCiAKIAkKCiAJCgogICAgCiAKIAoJIAogCiAgICAJ
IAoJIAkJIAoJICAgCSAKCSAJIAogCSAgCgogIAogCiAgICAJCQoJIAkJICAJCSAJCQkKCSAgCiAg
CQkJICAgCgkgCQkgICAJICAgICAKCSAgIAkKICAgICAJCQoJIAkgIAogICAJCQoJICAKCgkJCiAK
CgoJCjAK

```

Here's an excerpt that highlights all of the visible parts of the source.  is used to indicate a tab and  to indicate a newline.

```
say<< x2;say<<0,0  ↲
say<< x2;say<<0,0  ↲
↲
⇥⇥↲
   ⇥⇥  ⇥ [... etcetera ... skipping rest of a really long line ...]↲
   ⇥⇥⇥ ⇥⇥[... etcetera ... shorter but still quite a long line ...]↲
 ↲
  ↲
    ↲
 ⇥  ⇥↲
[... etcetera ... whole lotta whitespace in here ...]
⇥⇥↲
 ↲
↲
↲
⇥↲
0↲

```

Perl was the natural choice for the second language in this challenge, being one of the best general-purpose languages for writing compact quines. My shortest Perl quine is 19 bytes:

```
say<< x2
say<< x2

```

– and you can see how it was the seed for the Perl half of the double quine. My best Whitespace quine, in comparison, is 541 bytes long. (Though shorter ones do exist – 445 bytes is the best I've seen.)

From the Perl interpreter's point of view, the first line of the double quine's source file contains the two statements that make up the entire program proper, as the remaining contents are two quoted strings. The first string is the repeated line of Perl, and is delimited by the blank third line. The second string is all whitespace, and runs from the fourth line of the source all the way to the `0` delimiter at the bottom of the file.

When taken as a Whitespace program, the first four lines contain three instructions that are largely useless. (Their effect is to push two zero values onto the stack, and then discard the second one.) They're included just to get safely past the newlines that the Perl program requires – the real program starts after that. Rather than quote the unreadable source any further, here's a paraphrasing of the instructions that make up the Whitespace program, in an assembly-like format:

```
# Representation of "say<< ;say<<0,0  \n" in base 122 as ASCII chars.
PERLCODE = 44892457841068708924520433691075560592081

# Represention of the whitespace program, following the "push PERLCODE"
# instruction, in base 3 (see comments on wsout).
WSCODE = 9823454421986355730445143846606456399449033186160554878002671428613111806443504867738858766142050504887335990409088441824104338753030405625930185

# Set up the stack and the heap. The first three instructions are not
# particularly useful; they're just there to skip past the newlines in
# the Perl code. (Though the initial zero on the stack does get used
# at the very end.)

        push    0
        push    0
        jneg    wsout

        push    WSCODE
        push    PERLCODE
        dup
        dup
        push    0
        copy    1

# Output the first four lines of the file.

perl:   dup
        mod     122
        putchar
        div     122
        dup
        jnzero  perl
        pop
        jzero   perl
        push    68              # represents "jneg wsout"
        call    wsout

# Output the rest of the file.

        copy    1
        call    pushout
        push    2
        call    wsout
        call    pushout
        call    wsout
        putnum
        push    2
        call    wsout
        exit

# pushout: Output a Whitespace push instruction, using the number on
# the top of the stack as the instruction's argument. (Recursion is
# used to output the bits MSB-first.)

pushout:
        push    0
        dup
        call    wsout
        call    wsout
bits:   dup
        jzero   bitend
        dup
        mod     2
        swap
        div     2
        call    bits
bitend: call    wsout
        ret

# wsout: Output a sequence of whitespace characters as represented by
# the number on the top of the stack. The number is read in base 3,
# LSB-first, with 0 = SPC, 1 = TAB, 2 = NL. Calling wsout with a value
# of zero will output a single space.

wsout:
        dup
        mod     3
        mul     -23             # some ugly math that transforms
        mod     -24             # (0, 1, 2) into (32, 9, 10)
        add     32
        putchar
        div     3
        dup
        jnzero  wsout
        pop
        ret

```

The giant numbers at the top are what we Whitespace users have to use in lieu of actual strings. Don't bother trying to run this on a Whitespace interpreter that doesn't have proper bignum support.

Finally, here's the program again, but this time with C-style escapes, since it was specifically requested:

```
say<< x2;say<<0,0  \nsay<< x2;say<<0,0  \n\n\t\t\n   \t\t  \t  \t \t\t  \t  \t\t \t \t \t\t\t\t\t  \t\t \t\t\t \t\t\t\t\t \t \t \t\t \t \t   \t\t\t\t\t   \t\t  \t \t\t \t \t\t \t    \t\t\t\t \t  \t \t\t \t    \t \t\t   \t      \t\t\t \t\t\t\t\t \t\t\t \t\t\t\t     \t\t\t \t      \t\t\t\t\t      \t\t   \t\t    \t\t\t\t\t\t\t\t  \t \t \t   \t\t\t   \t\t\t\t\t  \t\t\t\t \t    \t \t\t\t\t\t \t     \t  \t \t      \t    \t     \t\t   \t\t\t \t \t\t\t\t\t\t \t\t \t \t       \t\t  \t           \t\t   \t \t\t\t \t     \t\t\t\t\t\t \t    \t\t\t\t \t\t\t\t  \t\t\t   \t\t\t \t  \t   \t\t\t\t  \t\t \t\t\t   \t\t\t \t\t\t \t\t\t  \t\t \t  \t \t\t\t \t \t \t\t     \t \t \t  \t  \t \t\t     \t \t    \t\t\t\t  \t \t\t \t \t\t \t  \t \t \t\t \t\t \t\t \t\t\t \t\t\t    \t\t\t  \t  \t\n   \t     \t\t\t\t\t \t\t \t \t \t \t  \t\t\t   \t   \t    \t\t \t         \t   \t\t\t\t \t\t    \t\t \t \t  \t\t\t \t\t\t\t \t\t\t   \t    \t \t \t\t\t  \t\t\t\t \t \t\t \t \t \t\t\t\t \t  \t \t\t \t   \t\n \n  \n    \n \t  \t\n\n  \t\n \n    \t\t\t\t \t \n\t \t\t\t\n     \t\t\t\t \t \n\t \t  \n   \t\t\n\t  \n\n\t\t\t\n \n\n\n\t \t\n   \t   \t  \n\n \t\n \t  \t\n\n \t \n   \t \n\n \t\n\n \t \n\n \t\n\t\n \t   \t \n\n \t\n\n\n\n\n   \n   \n \n \n \t\n\n \t\n\n    \n \n \n\t \n \n    \t \n\t \t\t \n\t   \t \n\t \t \n \t  \n\n  \n \n    \t\t\n\t \t\t  \t\t \t\t\t\n\t  \n  \t\t\t   \n\t \t\t   \t     \n\t   \t\n     \t\t\n\t \t  \n   \t\t\n\t  \n\n\t\t\n \n\n\n\t\n0\n

```
> 21 votes

---
Tags: code-golf, quine, polyglot, whitespace-language
---


# Question
Title: Shortest Hello World program with no semi colons
I recently saw some questions on SO that asked if you could make a Hello World program without using any semi colons using C#. The challenge is to do this again, but in the shortest amount of code possible!

# Answer
# C#, 76

```
class X{static void Main(){if(System.Console.Write("Hello, World!")is X){}}}

```

I tried this in my VS2012 and it works just fine, even though it is quite a surprise that you can apply the `is` operator to `void`...
> 12 votes

# Answer
# C# 85 chars

```
class H{static void Main(){if(System.Console.Out.WriteAsync("Hello, world!")is H){}}}

```
> 15 votes

# Answer
## C# (114)

```
class M{static void Main(){if(typeof(System.Console).GetMethods()[78].Invoke(null,new[]{"Hello, world!"})is M){}}}

```

Note that the proper index for `Write(string)`/`WriteLine(string)` may be different on your system. However, since there are only 106 methods total, I'm almost certain either `Write(string)` or `WriteLine(string)` will be a two-digit index number on every system, so the character count should be generally valid.

Demo: http://ideone.com/5npky (`Write` method is apparently index 23 here)
> 12 votes

# Answer
# 115 Bytes

```
class H{static void Main(){if(((System.Action)(()=>System.Console.Write("Hello, world!"))).DynamicInvoke()is H){}}}

```

It's likely possible to produce something a bit shorter, but I'm pretty sure that you're going to need make some sort of asynchronous call.
> 8 votes

# Answer
# C# ~~96~~ ~~95~~ 94 chars

A bit of a cheat, but works if you have IronRuby installed:

```
class P{static void Main(){if(IronRuby.Ruby.CreateEngine().Execute("puts'Hello World'")>1){}}}

```
> 4 votes

---
Tags: code-golf, c#
---


title: Flip the commented-out code

text:
# Question
Title: Flip the commented-out code
This puzzle works for any programming language that has the same `//` single-line and `/* ... */` multi-line comments that C++, C# and Java do.

You are debugging an application. You find a fishy block of code, which you comment out and replace with some new code:

```
/*
code block A
*/
code block B

```

After some debugging, you find that you need to step through block A again to see how it worked. This requires quite a lot of cursor movement:

```
                ← remove “/*” here
code block A
/*              ← change “*/” to “/*” here
code block B
*/              ← add “*/” here

```

This is very laborious if you need to keep switching between block A and block B. So you decide to find a better way.

Place combinations of asterisks and slashes before block A, between the blocks, and after block B, such that you can flip between block A and block B by adding/removing only one character in one place. You may assume that the code blocks A and B do not contain any `/*` or `*/`.

There are two possible solutions.

# Answer
Toggle commented out blocks by adding/removing the last slash on the first line:

```
/**/
code block A
/*/
code block B
/**/

```

Bonus solution, toggle this one by adding/removing the first slash on the first line:

```
//*
code block A
/*/
code block B
/**/

```
> 10 votes

---
Tags: c, c++, c#, java
---


title: highest common factor-fewest iterations

text:
# Question
Title: highest common factor-fewest iterations
Find the highest common factor of two(positive integer) input numbers (not greater than 5000) in the minimum number of iterations.

If you use a loop, it should increment a counter, starting at 0 for the first run. The counter should be the first statement in the loop. If you use more than one loop, they too should have a similar counter.

So

```
counter_1=0;
counter_2=0;
...
loop{
    counter_1=counter_1 + 1;
    ...
    code
    ...

    loop_nested{
        counter_2=counter_2 + 1;
        ...
        code
        ...
    }
}
total_count=counter_1 + counter_2 + ...

```

Test cases first-number second-number--\>expected-output

450 425--\>25

27 23--\>1

1000 1001--\>1

36 54--\>18

2 4000--\>2

4000 2500--\>500

2000 4000--\>2000

99 75--\>3

584 978--\>2

3726 4380--\>6

The code with the lowest sum of all counters for all test cases wins. There is no restriction on program length. Of course, you can't use any standard functions. There is no restriction on the language that you use.

Also, please write the sum of counters that your code produces.

# Answer
> 5 votes
## C, no loops -\> 0 iterations

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

#define Q(n) (a % (n) == 0 && b % (n) == 0) ? (n) :
#define R(n) Q((n)+9) Q((n)+8) Q((n)+7) Q((n)+6) Q((n)+5) Q((n)+4) Q((n)+3) Q((n)+2) Q((n)+1) Q(n)
#define S(n) R((n)+90) R((n)+80) R((n)+70) R((n)+60) R((n)+50) R((n)+40) R((n)+30) R((n)+20) R((n)+10) R(n)
#define T(n) S((n)+900) S((n)+800) S((n)+700) S((n)+600) S((n)+500) S((n)+400) S((n)+300) S((n)+200) S((n)+100) S(n)
#define U(n) T((n)+4000) T((n)+3000) T((n)+2000) T((n)+1000) T(n)

int main (int argc, char *argv[]) {
  int a, b, gcd;
  if (argc <= 2) {
    fprintf(stderr, "Usage: %s <num1> <num2>\n", argv[0]);
    return 1;
  }

  a = atoi(argv[1]);
  if (a < 1 || a > 5000) {
    fprintf(stderr, "Input %d out of range!\n", a);
    return 1;
  }

  b = atoi(argv[2]);
  if (b < 1 || b > 5000) {
    fprintf(stderr, "Input %d out of range!\n", b);
    return 1;
  }

  gcd = U(1) 0;

  if (gcd) {
    printf("The greatest common divisor of %d and %d is %d.\n", a, b, gcd);
  } else {
    fprintf(stderr, "Unable to find gcd of %d and %d! Inputs out of range?\n", a, b);
  }
  return 0;
}

```

Given that you've specified an upper limit of 5000 on the input values, this challenge can be solved in *any* language without *any* (runtime) loops just by taking a trivial solution using a single trial-division loop and unrolling it 5000 times.

I've chosen to use C, since the C macro preprocessor allows the solution to be written in a compact manner. The macros will be expanded at compile time into a single *huge* nested ternary `?:` expression.

(If you consider the compile time macro expansion to be a loop in disguise, feel free to run the code above through the C preprocessor and consider the expanded *output* — which is also a valid C program — to be my solution. I won't include the expanded version in this post, though, since it's huge.)

# Answer
> 6 votes
Along similar lines to Ilmari's solution, but slightly shorter (comparing expanded versions):

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

#define D(pn, p) (a%(pn) + b%(pn) ? 1 : (p))
#define P(p) D(p, p)
#define P2(p) D(p, p) * D(p*p, p)

int main (int argc, char *argv[]) {
    int a, b, t, gcd;
    if (argc != 3) return 1;

    a = atoi(argv[1]);
    b = atoi(argv[2]);
    if (a < 1 || a > 5000 || b < 1 || b > 5000) return 1;

    // Force an order: a <= b
    if (a > b) {
        t = a; a = b; b = t;
    }

    gcd = (a == b || a*2 == b || a*3 == b || a*4 == b || a*5 == b ||
           a*3 == b*2 || a*5 == b*2 || a*4 == b*3 || a*5 == b*3 ||
           a*6 == b*5) ? a :
            ((a|b) & -(a|b)) *
            P(3) * D(9, 3) * D(27, 3) * D(81, 3) * D(243, 3) * D(729, 3) *
            P(5) * D(25, 5) * D(125, 5) * D(625, 5) *
            P(7) * D(49, 79) * D(343, 7) *
            P2(11) * P2(13) * P2(17) * P2(19) * P2(23) *
            P(29) * P(31) * P(37) * P(41) * P(43) * P(47) * P(53) * P(59) *
            P(61) * P(67) * P(71) * P(73) * P(79) * P(83) * P(89) * P(97) *
            P(101) * P(103) * P(107) * P(109) * P(113) * P(127) * P(131) *
            P(137) * P(139) * P(149) * P(151) * P(157) * P(163) * P(167) *
            P(173) * P(179) * P(181) * P(191) * P(193) * P(197) * P(199) *
            P(211) * P(223) * P(227) * P(229) * P(233) * P(239) * P(241) *
            P(251) * P(257) * P(263) * P(269) * P(271) * P(277) * P(281) *
            P(283) * P(293) * P(307) * P(311) * P(313) * P(317) * P(331) *
            P(337) * P(347) * P(349) * P(353) * P(359) * P(367) * P(373) *
            P(379) * P(383) * P(389) * P(397) * P(401) * P(409) * P(419) *
            P(421) * P(431) * P(433) * P(439) * P(443) * P(449) * P(457) *
            P(461) * P(463) * P(467) * P(479) * P(487) * P(491) * P(499) *
            P(503) * P(509) * P(521) * P(523) * P(541) * P(547) * P(557) *
            P(563) * P(569) * P(571) * P(577) * P(587) * P(593) * P(599) *
            P(601) * P(607) * P(613) * P(617) * P(619) * P(631) * P(641) *
            P(643) * P(647) * P(653) * P(659) * P(661) * P(673) * P(677) *
            P(683) * P(691) * P(701) * P(709) * P(719) * P(727) * P(733) *
            P(739) * P(743) * P(751) * P(757) * P(761) * P(769) * P(773) *
            P(787) * P(797) * P(809) * P(811) * P(821) * P(823) * P(827) *
            P(829);

    printf("The greatest common divisor of %d and %d is %d.\n", a, b, gcd);
    return 0;
}

```

# Answer
> 3 votes
### Ruby

```
def gcd(a,b)
  ('x'*a+' '+'x'*b).gsub(/^(.*)\1* \1+$/,'\1').length
end

```

A completely different solution - no explicit loops either.

# Answer
> 2 votes
# Tcl, 0 loops.

Some languages don't even have loops, they use recursion.

Note: if you don't use Tcl 8.6, replace `tailcall` with `return [...]`

```
proc gcd {a b} {
    if {$b > $a} {tailcall gcd $b $a}
    if {$b == 0} {return $a}
    tailcall gcd $b [expr {$a % $b}]
}

```

Well, and here for the people that said recursion is a loop:

```
proc gcd2 {a b {i 0}} {
    if {$b > $a} {lassign [list $a $b] b a}
    if {$b == 0} {return $a}
    set a [expr {$a % $b}]
    if {$a == 0} {return $b}
    set b [expr {$b % $a}]
    if {$b == 0} {return $a}
    set a [expr {$a % $b}]
    if {$a == 0} {return $b}
    set b [expr {$b % $a}]
    if {$b == 0} {return $a}
    set a [expr {$a % $b}]
    if {$a == 0} {return $b}
    set b [expr {$b % $a}]
    if {$b == 0} {return $a}
    set a [expr {$a % $b}]
    if {$a == 0} {return $b}
    set b [expr {$b % $a}]
    if {$b == 0} {return $a}
    set a [expr {$a % $b}]
    if {$a == 0} {return $b}
    set b [expr {$b % $a}]
    if {$b == 0} {return $a}
    set a [expr {$a % $b}]
    if {$a == 0} {return $b}
    set b [expr {$b % $a}]
    if {$b == 0} {return $a}
    set a [expr {$a % $b}]
    if {$a == 0} {return $b}
    set b [expr {$b % $a}]
    if {$b == 0} {return $a}
    set a [expr {$a % $b}]
    if {$a == 0} {return $b}
    set b [expr {$b % $a}]
    if {$b == 0} {return $a}
    set a [expr {$a % $b}]
    if {$a == 0} {return $b}
    set b [expr {$b % $a}]
    if {$b == 0} {return $a}
}

```

# Answer
> 1 votes
## APL (0 loops)

All right, after some people have posted even smarter ideas I might as well post this one, which I wrote to support my comment. It has no loops or recursion expressed in it.

```
∇GCD;divs;gcd
  divs ← {A/⍨A=⌈A←⍵÷⍳⍵}
  gcd  ← {⊃A/⍨(A←divs⍺)∊divs⍵}
  ⎕ ← ⎕ gcd ⎕
∇

```

For people who are not familiar with reading APL, I'll give all explict looping constructs that I know of below:

* `:For` ... `:EndFor` (for loop)
* `:While` ... `:EndWhile` (while loop)
* fn`¨`list (apply *fn* to each element in *list*)
* fn*N* (apply *fn* *N* times)
* fncondfn (apply *fn*, until (*condfn*( *x*, *fn*( *x* ) ) is true)
* `{`......`}`: recursion (`{`...`}` is a function,  refers to the function it is used in)

Explanation of the program:

* `divs`: (get divisors of a number, in descending order)
    + `A/⍨A=⌈A`: select from `A` those elements where `A` is equal to `ceil(A)`
    + `A←⍵÷⍳⍵`: ...where `A` is the right argument () divided (`÷`) by the numbers from 1 to  (`⍳⍵`)
* `gcd`: (get the greatest common denominator of two numbers)
    + : get the first (thus, biggest, see above) element of:
    + `A/⍨`: the elements selected from `A`, where...
    + `(A←divs⍺)`: `A`, which is the divisors of the left argument,
    + ...`∊divs⍵`: ...is a member of the divisors of the right argument.
* `⎕ ← ⎕ gcd ⎕`: output (`⎕ ←`) the GCD of input () and input ().

---
Tags: code-challenge, number
---


title: Build a perfect AI for the game 15

text:
# Question
Title: Build a perfect AI for the game 15
In the game 15, two players take turns selecting numbers from 1 to 9 (without choosing any number that either player has already selected). A player wins if he or she has three numbers that add up to 15. If all the numbers have been selected and no combination of either player's adds up to 15, then the game is a tie.

Your task is to build a function that takes the state of a game of 15 (represented in any form you like) and returns which number to move next, which will act as an AI to play the game with another player. You may assume that the position is legal (no player has more than one number more than the other player, and no player already has three numbers that add up to 15).

The AI must be perfect - that is, if it's given a winning position, it must force a win, and if it's given a non-losing position (a position where its opponent does not have a winning strategy), it must not allow its opponent to give it a losing position (which is possible, as 15 is a solved game).

The shortest code wins.

(note: I will accept the currently shortest answer and change it if a shorter answer appears.)

# Answer
## GolfScript (129 86 81 85 75 chars)

```
{:C[{.`{1$-\{+15\-}+%}:T+/}/10,1>C~+-:^{.{^T&}+C/,2<*T}/5^{1&}$][]*^&0=}:N;

```

Expected input format: `[[int int ...][int int ...]]` where the first list is my numbers and the second list is my opponent's numbers. For interactive testing, add `~N` to the end of the script and supply a string in that format: e.g.

```
$ golfscript.rb 15.gs <<<"[[5][2 8]]"
9
$ golfscript.rb 15.gs <<<"[[2][5 8]]"
6

```

---

Heuristics:

1. If I can win this turn, do it
2. If opponent would win next turn, block
3. If I can force opponent to a square which prevents them from creating a fork, do it
4. `5` is the only number which can contribute to winning in 4 ways, so grab it if available.
5. Favour evens over odds

---

Test framework:

```
{:Set;[1 5 9 1 6 8 2 4 9 2 5 8 2 6 7 3 4 8 3 5 7 4 5 6]3/{.Set&=},!!}:isWin;
{
    # Mine His
    .isWin{
        "Lost "@`@`++puts
    }{
        # If there are available moves, it's my move.
        # If I won before my move, I've still won after it.
        1$1$+,9<!!{
            # my move
            1$1$[\\]N 2$\+
            # Mine His Mine'
            .isWin!{
                # his move
                10,1>2$2$+-{
                    2$\+1$\
                    # Mine His Mine' Mine' His'
                    fullTest
                    # Mine His Mine'
                }/
            }*;
        }*;;
    }if
}:fullTest;
# I move first
'[][]fullTest'puts [][]fullTest
# He moves first
'[][1]fullTest'puts [][1]fullTest
'[][2]fullTest'puts [][2]fullTest
'[][5]fullTest'puts [][5]fullTest

```
> 6 votes

# Answer
### Ruby, 330 315 341 characters

```
def m i
$_=i.join
l='159258357456168249267348'.scan /(.)(.)(.)/
return 1 if /^5(28|46|64|82)$/
return 4 if /^[258]{3}$/
return 2 if /^[456]{3}$/
i.each{|i|l.map{|l|return l if(l-=i).size==1&&!/[#{l=l[0]}]/}}
.map{|i|l.map{|m|l.map{|l|return (l&m)[0] if(z=l-i|m-i).size==3&&l!=m&&!/[#{z.join}]/}}}
"524681379".chars{|z|return z if !/#{z}/}
end

```

I'll withhold the details for now, but let's say that it is based on the optimal algorithm to a similar problem that has been solved as well and whose optimal algorithm happened to work just as fine here. ~~Assumptions have been made - this will choose bad moves in situations that cannot be produced by this algorithm playing against another player, only by two players against each other.~~

Input: an array of two arrays of one-digit strings. Each array represents the values taken by one player - the first one is the AI, the second one is the opponent.

Output: either a number, or a single-digit string. They are semantically equivalent. Normalisation to strings would cost 8 characters.

Three more characters can be saved if we assume the order of numbers given by the caller - change the regex in L5 to `/^285$/` or `/^258$/` depending on the order produced from the game `(opponent)5-(ai)2-(opponent)8`.
> 4 votes

# Answer
## GolfScript (90 85 84 chars)

```
{.~.,3/*..2%.@^++3*3/{~++15=},,*10,1>2$~+-@`{([2$+]+v[0=~)\]}+%[1,]or$0=+}:v{1=}+:N;

```

This takes a completely different approach, but is potentially susceptible to optimisations to beat the heuristic one. Here we do a full game tree analysis, incredibly slowly. (No, I mean it. It takes several *hours* to run the full test, mainly because of the ``{...}+` which adds the current state to the next-move loop). Note that the hard part is identifying a winning state (a third of the code, at present).

There are some ugly hacks in the non-recursive sections. In particular, when the position is identified as a losing one we take our positions as the `[value move]` array, relying on the move being irrelevant and the value being non-zero.
> 1 votes

---
Tags: code-golf, ai-player
---


title: Soundex function

text:
# Question
Title: Soundex function
Write the shortest function to generate the American Soundex code for a surname only containing the uppercase letters A-Z. Your function must produce output consistent with all the linked page's examples (given below), although it need not and should not remove prefixes. Hyphens in the output are optional. Have fun!

**Note:** You may *not* use the `soundex()` function included in PHP or equivalents in other programming languages.

The examples:

```
WASHINGTON W-252
LEE L-000
GUTIERREZ G-362
PFISTER P-236
JACKSON J-250
TYMCZAK T-522
VANDEUSEN V-532
ASHCRAFT A-261

```

# Answer
> 4 votes
### Perl, 143 150 characters

```
sub f{$_="$_[0]000";/./;$t=$&;s/(?<=.)[HW]//g;s/[BFPV]+/1/g;s/[CGJKQSXZ]+/2/g;s/[DT]+/3/g;s/L+/4/g;s/[MN]+/5/g;s/R+/6/g;s/(?<=.)\D//g;/.(...)/;"$t$1"}

```

This solution contains only regular expressions which are applied one after another. Unfortunately I didn't find a shorter representation with a loop so I hard-coded all the calls into the script.

The same version but a little bit more readable:

```
sub f{
  $_="$_[0]000";        # take first argument and append "000"
  /./;$t=$&;            # save first char to variable $t
  s/(?<=.)[HW]//g;      # remove and H or W but not the first one
  s/[BFPV]+/1/g;        # replace one or more BFPV by 1
  s/[CGJKQSXZ]+/2/g;    # replace one or more CGJKQSXZ by 2
  s/[DT]+/3/g;          # replace one or more DT by 3
  s/L+/4/g;             # replace one or more L by 4
  s/[MN]+/5/g;          # replace one or more MN by 5
  s/R+/6/g;             # replace one or more R by 6
  s/(?<=.)\D//g;        # remove and non-digit from the result but not the first char
  /.(...)/;"$t$1"       # take $t plus the characters 2 to 4 from result
}

```

*Edit 1:* Now the solution is written in form of a function. The previous one was reading/writing from/to STDIN/STDOUT. It cost me seven characters to work around that.

# Answer
> 3 votes
## J - 99

```
{.,([:-.&' '@":3{.!.0[:(#~1,}.~:}:)^:#,@(;:@]>:@I.@:(e.&>"0 _~)[#~e.))&'BFPV CGJKQSXZ DT L MN R'@}.

```

Testing:

```
  sndx=: {.,([:-.&' '@":3{.!.0[:(#~1,}.~:}:)^:#,@(;:@]>:@I.@:(e.&>"0 _~)[#~e.))&'BFPV CGJKQSXZ DT L MN R'@}.
  test=: ;: 'JACKSON PFISTER TYMCZAK GUTIERREZ ASHCRAFT ASHCROFT VANDEUSEN ROBERT RUPERT RUBIN WASHINGTON LEE'
  (,. sndx&.>) test

+-------+-------+-------+---------+--------+--------+---------+------+------+-----+----------+----+
|JACKSON|PFISTER|TYMCZAK|GUTIERREZ|ASHCRAFT|ASHCROFT|VANDEUSEN|ROBERT|RUPERT|RUBIN|WASHINGTON|LEE |
+-------+-------+-------+---------+--------+--------+---------+------+------+-----+----------+----+
|J250   |P123   |T520   |G362     |A261    |A261    |V532     |R163  |R163  |R150 |W252      |L000|
+-------+-------+-------+---------+--------+--------+---------+------+------+-----+----------+----+

```

# Answer
> 2 votes
**Python, ~~274~~ ~~285~~ ~~241~~ ~~235~~ ~~225~~ ~~200~~ ~~190~~ ~~183~~ ~~179~~ ~~174~~ ~~166~~ 161**

~~\- Fixed last clause (H or W as consonant separators). Ashcraft now has the right result. \- Made the dict smaller \- Formating is smaller (doesn't require python 2.6) \- Simpler dict search for `k` \- Changed vowel value from `'*'` to `''` and `.append` to `+=[i]` \- List comprehension FTW \- Removed call to `upper` :D~~

~~I Can't golf any further. Actually I did. Now I think I can't golf any further!~~ Did it again...

Using translate table:

```
def f(n):z=n.translate(65*'_'+'#123#12_#22455#12623#1_2#2'+165*'_').replace('_','');return n[0]+(''.join(('',j)[j>'#']for i,j in zip(z[0]+z,z)if i!=j)+'000')[:3]

```

Old list comprehension code:

```
x=dict(zip('CGJKQSXZDTLMNRBFPV','2'*8+'3345561111'))
def f(n):z=[x.get(i,'')for i in n if i not in'HW'];return n[0]+(''.join(j for i,j in zip([x.get(n[0])]+z,z)if i!=j)+'000')[:3]

```

Old code:

```
x=dict(zip('CGJKQSXZDTLMNRBFPV','2'*8+'3345561111'))
def f(n):
 e=a=[];k=n[0]in x
 for i in[x.get(i,'')for i in n.upper()if i not in'HW']:
  if i!=a:e+=[i]
  a=i
 return n[0]+(''.join(e)+'000')[k:3+k]

```

Test:

```
[f(i) for i in ['WASHINGTON', 'LEE', 'GUTIERREZ', 'PFSTER', 'JACKSON',
                'TYMCZAK', 'VANDEUSEN', 'ASHCRAFT']]

```

Gives:

```
['W252', 'L000', 'G362', 'P236', 'J250', 'T522', 'V532', 'A261']

```

As expected.

# Answer
> 2 votes
eTeX, 377.

```
\let\E\expandafter
\def\x#1;#2#3{\def\s##1#2{##1\s#3}\edef\t{\s#1\iffalse#2\fi}\E\x\t;}
\def\a[#1#2]{\if{{\fi\uppercase{\x#1,#2};B1F1P1V1C2G2J2K2Q2S2X2Z2D3T3L4M5N5R6A7E7I7O7U7
    H{}W{}Y{}{11}1{22}2{33}3{44}4{55}5{66}6{{}\toks0\bgroup}!}\E\$\t0000!#1}}
\def\$#1,#2{\if#1#2\relax\E\%\else\E\%\E#2\fi}
\def\%{\catcode`79 \scantokens\bgroup\^}
\def\^#1#2#3#4!#5{\message{#5#1#2#3}\end}
\E\a

```

Run as `etex filename.tex [Ashcraft]`.

# Answer
> 2 votes
## Perl, 110

```
sub f{$_="$_[0]000";/./;$t=$&;s/(?<=.)[HW]//g;y/A-Z/:123:12_:22455:12623:1_2:2/s;s/(?<=.)\D//g;/.(...)/;$t.$1}

```

I'm using Howard's solution with my translate table (`y/A-Z/table/s` instead of every `s/[ABC]+/N/g`)

# Answer
> 2 votes
## GolfScript (74 chars)

This implementation uses a magic string which has non-printable characters. In `xxd` output form it's

```
0000000: 7b2e 313c 5c5b 7b36 3326 2741 4c15 c252  {.1<\[{63&'AL..R
0000010: d056 4c1e 8227 3235 3662 6173 6520 3862  .VL..'256base 8b
0000020: 6173 653d 7d25 7b2e 373d 2432 243d 7b3b  ase=}%{.7=$2$={;
0000030: 7d2a 7d2a 5d31 3e31 2c2d 5b30 2e2e 5d2b  }*}*]1>1,-[0..]+
0000040: 333c 7b2b 7d2f 7d3a 533b                 3<{+}/}:S;

```

Without using the base changes to compress a list of 3-bit numbers, it would be

```
{.1<\[{63&[1 0 1 2 3 0 1 2 7 0 2 2 4 5 5 0 1 2 6 2 3 0 1 7 2 0 2]=}%{.7=$2$={;}*}*]1>1,-[0..]+3<{+}/}:S;

```

Online test

It's basically a bunch of boring loops, but there's one interesting trick:

```
.7=$2$=

```

This is inside a fold whose purpose is to handle double-letters. Adjacent letters with the same code are merged into one unit, even if separated by an `H` or a `W`. But this can't be implemented trivially by removing all `H`s and `W`s from the string, because in the (admittedly unlikely in real life, but not ruled out by the spec) case that the first letter is `H` or `W` and the second letter is a consonant, we need to not elide that consonant when we remove the first letter. (I added a test case `WM` which should give `W500` to check this).

So the way I handle that is to do a fold and to delete each letter *other than the first* (a convenient side-effect of using fold) which is either equal to the previous one or equal to `7`, the internal code for `H` and `W`.

Given `a` and `b` on the stack, the naïve way to check whether `a == b || b == 7` would be

```
.2$=1$7=+

```

But there's a 2-character saving by using a computed copy-from-stack:

```
.7=$

```

If `b` is equal to `7` then it copies `a`; otherwise it copies `b`. So by then comparing with `a` we get a guaranteed truthy value if `b` was `7` regardless of the value of `a`. (Before any pedants weigh in, GolfScript doesn't have NaNs).

# Answer
> 1 votes
## APL (83)

```
{(⊃⍵),,/⍕¨3↑0~⍨1↓K/⍨~K=1⌽K←0,⍨{7|+/' '=S↑⍨⍵⍳⍨S←' BFPV CGJKQSXZ DT L MN R'}¨⍵~'HW'}⍞

```

# Answer
> 0 votes
## PowerShell, 150 ~~161~~

First try and I'm sure there can be golfed quite a bit more.

```
filter s{$s=-join$_[1..9]
1..6+'$1','',$_[0]|%{$s=$s-replace('2[bfpv]2[cgjkqsxz]2[dt]2l2[mn]2r2(.)\1+2\D|^.2^'-split2)[++$a],$_}
-join"${s}000"[0..3]}

```

Works correctly with the test cases from both the linked page and the Wikipedia article:

> Jackson, Pfister, Tymczak, Gutierrez, Ashcraft, Ashcroft, VanDeusen, Robert, Rupert, Rubin, Washington, Lee

# Answer
> 0 votes
# Ruby 140

I'm using Ruby 2.0, but I think it should work with earlier versions too.

```
def f s
a=s[i=0]
%w(HW BFPV CGJKQSXZ DT L MN R).each{|x|s.gsub!(/[#{x}]+/){i>0&&$`[0]?i: ''};i+=1}
a+(s[1..-1].gsub(/\D/,'')+'000')[0,3]
end

```

Example:

`puts f "PFISTER"` =\> `P236`

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


title: Simulate a battle between two creatures

text:
# Question
Title: Simulate a battle between two creatures
Welcome, brave code golfer! Today you will stand in the midst of a great battle between a goblin and an elf!

```
    goblin attacks elf!
    elf dodges!
    elf attacks goblin!
    elf hits goblin for 13 damage!
    goblin has 37 health left.
    goblin attacks elf!
    goblin hits elf for 1 damage!
    elf has 49 health left.
    elf attacks goblin!
    elf hits goblin for 19 damage!
    goblin has 18 health left.
    goblin attacks elf!
    goblin hits elf for 26 damage!
    elf has 23 health left.
    elf attacks goblin!
    elf hits goblin for 20 damage!
    goblin has been slain!

```

## The Challenge

Your challenge is to simulate a battle, like the above one. You will recieve input in this form:

```
creatureName health strength defense accuracy agility

```

For example, the battle between the goblin and elf would be:

```
goblin 50 40 35 3 2 elf 50 35 30 4 5

```

The first and second creatures will alternate attacks.

* Print 'creatureName attacks otherCreatureName!'
* Check to see if the creature dodges. The creature will dodge an attack if (its agility times rand() divided by 2) is greater than (the attacker's accuracy times rand()).
    + If the creature dodges, print 'creatureName dodges!'
    + Otherwise, calculate the damage dealt by subtracting (the attacker's strength times rand()) and (the defender's defense times rand() divided by 2). Minimum damage is 1. Print 'creatureName hits otherCreatureName for (x) damage!' Then print 'creatureName has (x) health left.' unless the creature's health is 0 or less, in which case...
        - If the creature's health is 0 or less, print 'creatureName has been slain!' and end the program.

## Rules

* Shortest code wins.
* Don't literally print 'creatureName,' but replace it with the creature's name. Don't print '(x) damage' or '(x) health;' replace them with the actual amount. (I have to specify this because some people are *very* creative with bending the rules. :P)

# Answer
## APL (~~249~~ ~~244~~ 242)

Procedural style this time, so (in Dyalog at least) you have to paste this into an editor window. I named it `G` (the first line is the name, I've included it because that's how it shows up in the editor window so it should probably be counted).

```
G
⎕ML←3
D A←{(⊂↑⍵),⍎¨1↓⍵}¨↓2 6⍴A⊂⍨' '≠A←⍞
→5
⎕←(↑D)'dodges!'
A D←D A
⎕←(↑A)'attacks','!',⍨↑D
→4/⍨>/?A[6],D[5]
⎕←A[1],'hits',D[1],'for','damage!',⍨D[2]-←1⌈-/?A[3],⌈D[4]÷2
→12/⍨D[2]≤0
⎕←D[1],'has',D[2],'health left!'
→5
⎕←D[1],'has been slain!'

```

(edit: used numeric GOTOs instead of line labels. Turns out that (in Dyalog at least) all defining a label `X:` does is set `X` to the line number, so might as well use the numbers directly.)
> 4 votes

# Answer
## Perl, 254 + 1

```
for((@a[0..5],@b)=split;$a[1]>0;@c=@a,@a=@b,@b=@c){say"$a[0] attacks $b[0]!\n",rand$b[5]/2<rand$a[4]?do{($==rand($a[2])-rand$b[3]/2)<1and$==1;"$a[0] hits $b[0] for $= damage!\n$b[0] has ",($b[1]-=$=)>0?"$b[1] health left.":"been slain!"}:"$b[0] dodges!"}

```

Run with `perl -nM5.010` (or `perl -nE '<code>'`). Per meta, the `-n` switch counts as one extra character. No fancy golfing tricks in this code, except maybe the use of `$=` as the damage variable to save an `int`.

**Edit:** Hopefully, the damage calculation is correct now.
> 6 votes

# Answer
## Ruby, ~~292~~ 264

```
v=$*
def p*a;puts a*' 'end
loop{a,b=v[0],v[6]
w=v.map &:to_i
p a,:attacks,b+?!
w[11]*rand/2>w[4]*rand ? (p b,:dodges!):(h=v[7]=w[7]-=d=[rand(w[2])-rand(w[9])/2,1].max
p a,:hits,b,:for,d,:damage!
p b,:has,h<1?"been slain!":"#{h} health left."
h<1&&exit)
v.rotate!6}

```

My first code golf entry; how that method definition parses is beyond me :)

Is it OK to read the input from command-line parameters (e.g. `ruby battle.rb goblin 50 40 35 3 2 elf 50 35 30 4 5`)?

Ideone run
> 6 votes

# Answer
# CoffeeScript *454* 432

Pass a string to `b` to get the results. I thought it would be more fun to have a graphic animated output, so I put a demo together. Just change the input box to change statistics and names. The pictures from from jpg.to which is the unofficial google-images API.

## Super Action Demo

```
b=(s)->
 r=Math.random
 p=s.split ' '
 n=p.map Number
 l=''
 o=(x...)->l+=x.join(' ')+'!\n'
 while 1|i=!i
  c=(x)->n[i*6+x]*r()
  d=(x)->n[(i||6)+x]*r()
  t=->d(4)/2>c 5
  h=->Math.max c(2)-d(3)/2,1
  a=p[i*6]
  b=p[6+i*-6]
  o a,'attacks',b
  if c(5)/2>d 4
   e=Math.ceil h()
   q=n[(i||6)+1]-=e
   o a,'hits',b,'for',e,'damage'
   o b,'has',q,'health left'if q>0
  else
   o b,'dodges'
  if q<1
   o b,'has been slain'
   break
 l

```

Recommended Inputs (suggest your own):

```
charmander 50 40 25 3 2 bulbasaur 90 30 40 4 5
voldemort 9999 10 5 1 1 batman 20 50 10 1010 30

```
> 6 votes

# Answer
## JavaScript; ~~347~~ ~~341~~ 333

As I always do, I shall start off with my own solution:

```
for(m=prompt().split(' '),r=Math.random,a=console.log,c=0,d=6;;){if(a(m[c]+' attacks '+m[d]+'!'),r()*m[c+4]>r()*m[d+5]/2){if(a(m[c]+' hits '+m[d]+' for '+(h=Math.max(~~(r()*m[c+2]-r()*m[d+3]/2),1))+' damage!'),(m[d+1]-=h)<1){a(m[d]+' has been slain!');break}a(m[d]+' has '+m[d+1]+' health left.')}else a(m[d]+' dodges!');t=c;c=d;d=t}

```

EDIT: apparently assigning `console.log` to a variable breaks on some browsers, so here's the same code with a function declaration instead:

```
for(m=prompt().split(' '),r=Math.random,a=function(x){console.log(x)},c=0,d=6;;){if(a(m[c]+' attacks '+m[d]+'!'),r()*m[c+4]>r()*m[d+5]/2){if(a(m[c]+' hits '+m[d]+' for '+(h=Math.max(~~(r()*m[c+2]-r()*m[d+3]/2),1))+' damage!'),(m[d+1]-=h)<1){a(m[d]+' has been slain!');break}a(m[d]+' has '+m[d+1]+' health left.')}else a(m[d]+' dodges!');t=c;c=d;d=t}

```

I was thinking of changing it to `alert`, but that would just be evil :P
> 5 votes

# Answer
# JavaScript: ~~340~~ 306

339:

```
for(m=Math.random,a=prompt().split(" "),c=[a,a.splice(6)],e;0<+c[0][1]&&0<+c[1][1];)c.reverse(),console.log(c[0][0]+" attacks "+c[1][0]+"!\n"+(c[0][4]*m()<c[1][5]*m()/2?c[1][0]+" dodges!":c[0][0]+" hits "+c[1][0]+" for "+(e=1+(c[0][2]*m()-c[1][3]*m()/2|0))+" damage!\n"+c[1][0]+" has "+(0>(c[1][1]-=e)?"been slain!":c[1][1]+" health left.")))

```

306:

```
for(var m=Math.random,a=prompt().split(" "),b=a.splice(6),d,e;0<+a[1]&&0<+b[1];d=a,a=b,b=d)console.log(a[0]+" attacks "+b[0]+"!\n"+(a[4]*m()<b[5]*m()/2?b[0]+" dodges!":a[0]+" hits "+b[0]+" for "+(e=a[2]*m()-b[3]*m()/2|0,e<=0?e=1:e)+" damage!\n"+b[0]+" has "+(0>(b[1]-=e)?"been slain!":b[1]+" health left.")))

```

Sample output:

```
goblin attacks elf!
elf dodges!
elf attacks goblin!
elf hits goblin for 21 damage!
goblin has 29 health left.
goblin attacks elf!
elf dodges!
elf attacks goblin!
elf hits goblin for 15 damage!
goblin has 14 health left.
goblin attacks elf!
goblin hits elf for 1 damage!
elf has 49 health left.
elf attacks goblin!
elf hits goblin for 16 damage!
goblin has been slain!

```

Edit notes: +1 character, i missed the "!" after "dodges"
Oh and i forgot to actually put an output after "Sample output"
Changed the header to JavaScript, as @tbodt suggests
> 4 votes

# Answer
# Python: 393

I squeezed a little harder, if I had 3 I could probably do `print = p` to shorten it by a few more, but I don't think there is much left in this one.

393:

```
from random import randrange as r
x = input().split()
t=range
a,b=6,0
for i in t(1,6)+t(7,12):x[i]=int(x[i])
while x[b+1] > 0:
 a,b=b,a;print x[a]+" attacks "+x[b]
 if r(x[a+5]/2)>r(x[b+5]):print x[a]+' dodges!';continue
 d=max(r(x[a+2])-r(x[b+3]/2),1);print x[a]," hits ",x[b]," for ",d," damage!";x[b+1]-=d
 if x[b+1]>0:print x[b]," has ",x[b+1]," health left."
print x[b]," has been slain"

```

399:

```
from random import randrange as r
x = raw_input().split()
t=range
a,b=6,0
for i in t(1,6)+t(7,12):x[i]=int(x[i])
while x[b+1] > 0:
 a,b=b,a;print x[a]+" attacks "+x[b]
 if r(x[a+5]/2) > r(x[b+5]):print x[a]+' dodges!';continue
 d=max(r(x[a+2])-r(x[b+3]/2),1);print x[a]," hits ",x[b]," for ",d," damage!";x[b+1]-=d                        if x[b+1]>0:print x[b]," has ",x[b+1]," health left."
print x[b]," has been slain"

```

I think people are skipping that if you have a good condition in the loop, you don't need to check if the target is below health.
> 4 votes

# Answer
## R: 387 characters

```
a=scan(,"");i=as.integer;r=runif;C=cat;X=data.frame(i(a[2:6]),i(a[8:12]));z=1;Y=c(a[1],a[7]);repeat{p=1+z%%2;n=X[,p];m=X[,-p];N=Y[p];M=Y[-p];C(N,"attacks",M,"\n");if(r(1)*n[5]<r(1)*m[5]/2){C(M,"dodges!\n")}else{C(N,"hits",M,"for",d<-max(round(n[2]*r(1)-m[3]*r(1)/2),1),"damages!\n");h=max(m[1]-d,0);if(h){C(M,"has",X[1,-p]<-h,"health left\n")}else{C(M,"has been slained!");break}};z=z+1}

```

Or fully-developed, with indentations and comments, to make things clearer:

```
a=scan(,"")                        # Read stdin as character vector
i=as.integer
r=runif
C=cat
X=data.frame(i(a[2:6]),i(a[8:12])) # Data frame with opponents stats
z=1                                # Turn counter
Y=c(a[1],a[7])                     # Vector of opponents name
repeat{                            # shorter than while(T)
    p=1+z%%2                       # R indexing starts with 1 not 0
    n=X[,p]                        # Attacking opponent stats
    m=X[,-p]                       # Defending opponent stats
    N=Y[p]                         # Attacking opponent name
    M=Y[-p]                        # Defending opponent name
    C(N,"attacks",M,"\n")          # By default, cat separates elements with a space
    if(r(1)*n[4]<r(1)*m[5]/2){
        C(M,"dodges!\n")
    }else{
        C(N,"hits",M,"for",d<-max(round(n[2]*r(1)-m[3]*r(1)/2),1),"damages!\n")
        h=max(m[1]-d,0)            # Health after the strike
        if(h){                     # If health is not 0
            C(M,"has",X[1,-p]<-h,"health left\n")
        }else{                     # If it is
            C(M,"has been slained!")
            break
            }
    }
    z=z+1
}

```
> 3 votes

# Answer
**C# - 464 453 chars**

After a couple of nights on this I can't seem to get even close to the other entries (not that surprising for C#). Still room for improvement I suspect. No especially clever tricks.

```
using System;using System.Linq;class P{static void Main(string[]a){int D,h=1,z=6;
var n=a.Select(x=>int.TryParse(x,out D)?D:0).ToList();var r=new Random();Func<int>
R=()=>r.Next(101);for(;h>0;z=z>0?0:6){D=(n[8-z]*R()-n[3+z]*R()/2)/100;var d=n[5+z]
*R()/2>n[10-z]*R();h=d?h:n[1+z]-=D=D<1?1:D;Console.Write("{0} attacks {1}!\n"+(d?
"{1} dodges!\n":"{0} hits {1} for {2} damage!\n")+(d?"":"{1} has {3}\n"),a[6-z],a
[z],D,h>0?h+" health left.":"been slain!");}}}

```

Commented:

```
using System;
using System.Linq;
class P
{
    static void Main(string[] a)
    {
        int D, // string to int parsing and attack damage
            h = 1, // health
            z = 6; // index

        // painful requirement to convert the input strings to integers
        var n = a.Select(x => int.TryParse(x, out D) ? D : 0).ToList();

        // set up a function to return a new random number
        var r = new Random();
        Func<int> R = () => r.Next(101);

        // we'll exit the loop when the defender's health (h) is <= 0.
        // z is used as an index offset to get values out of the list, it flips between 0 an 6 each round
        for (; h > 0; z = z > 0 ? 0 : 6)
        {
            // calculate damage
            D = (n[8 - z] * R() - n[3 + z] * R() / 2) / 100;

            // see if defender dodges
            var d = n[5 + z] * R() / 2 > n[10 - z] * R();

            // subtract health from defender if necessary. store health of defender in h
            h = d ? h : n[1 + z] -= D = D < 1 ? 1 : D;

            // print the round
            Console.Write(
                "{0} attacks {1}!\n" + (d ? "{1} dodges!\n" : "{0} hits {1} for {2} damage!\n") +
                (d ? "" : "{1} has {3}\n"), a[6 - z], a[z], D, h > 0 ? h + " health left." : "been slain!");
        }
    }
}

```
> 2 votes

# Answer
## Python 3, 314

```
from random import*
r=random
p=print
I=input().split()
H=1
while H>0:s,a,H,D,G=map(int,I[2:5:2]+I[7::2]);N=I[6];p(I[0],"attacks",N+"!");I=I[6:]+I[:6];X=max(int(s*r()-D*r()/2),1)*(G*r()/2<a*r());I[1]=H=H-X;X<1and p(N,"dodges!")or p(I[6],"hits",N,"for",X,"damage!\n"+N,"has",["been slain!","%s health left."%H][H>0])

```
> 1 votes

---
Tags: code-golf, simulation
---


title: Hard Code Golf: Create a Chatroom

text:
# Question
Title: Hard Code Golf: Create a Chatroom
**Cue Storyline:** It is the early 21st century, and most things have become a thing of the past. You and your fellow code-golf-eteers, however, are on a quest to reenact the 1990s. As a part of this challenge, you must recreate a minimalistic chatroom.

**The Goal:** To create a chatroom with as few bytes as possible. The program(s) that you write shall function as a simple server, which serves a webpage, which allows users to post text onto the screen.

**The Actual Goal:** To actually host a working chatroom from your own computer. You don't have to do this, but it is a lot more fun this way.

**Requirements:**

* Users should be able to give themselves a username that lasts for the session
* Users should be able to repeatedly type and submit text, which will be displayed to other users
* Each user should be able to see the text that is submitted by all users, along with the usernames of the submitters, and the information should be displayed in chronological order
* The page should also display the number of people online and a list of their usernames
* Your chatroom should be accessible to anyone on the internet who knows where to find it (such as knowing the IP address).
* It should function in modern web browsers.

All else is up to you!

**Submissions:**

* Should include the source code, or a link to the source code
* Should include screenshots of the functional chatroom
* Should include the total size, in bytes, of all of the programs/files that you have written that are required to make it work.

This challenge has been in the sandbox for a while now, so hopefully all of the kinks have been worked out.

# Answer
## PHP + JQuery + HTML + CSS, 1535 bytes

This is a submission leaning more towards what the OP deemed as 'the actual goal'. That is, a fully functional chat server, which may be hosted on just about any web server anywhere.

Functionality includes:

* Notifications when users enter or leave the chat room.
* Notifications when users change their alias.
* Real time polling for new messages, without generating excess server traffic, or server load.
* Layout and usability strongly resembling existing chat clients, such as X-Chat.

To being a session, enter an alias in the appropriate box, and press `Tab` or `Enter` to submit. If the alias is already in use, you will be notified. Sending messages is also done via `Enter`.

For your convenience, an archive of all files may be found here: chat.zip (choose Download from the File menu). To install, unpack to a web directory on any server running PHP 5.4 or higher.

Caveats:

* IE 8 or lower will spin into an infinite loop while polling, because for some reason unknown to humanity, all Ajax requests are cached by default. It also prevents you from sending the same message twice, and updating the user list properly. This could be fixed by adding `cache:false` to every Ajax request.
* In all version of IE, messages will not be sent by pressing Enter, because the `change` event is not triggered (pressing Tab, however, does work). This could be fixed by adding an `onkeypress` handler, checking if the key was Enter, and then calling `$(v).blur().focus()`.

In short, IE is not supported.

---

### Client

Positioning of elements could be a bit more robust, but it should look alright with a minimum window size of about ~800x600.

chat.htm (190 bytes)

```
<script src=jquery.min.js></script>
<script src=c.js></script>
<link rel=stylesheet href=c.css>
<select id=u multiple></select><pre id=o></pre>
<input id=n onchange=u()><input id=v onchange=s()>

```

c.css (136 bytes)

```
i{color:#999}
#u{float:right;height:100%;width:200px;margin-left:10px}
#o{border:1px solid #999;height:93%;overflow-y:scroll}
#v{width:54%}

```

c.js (435 bytes)

```
var l
(function p(){
  $.ajax({url:'p.php',data:{n:$('#n').val()},success:function(d){
    $('#o').html(d).scrollTop(1e4);$('#u').load('n.php');
  },complete:p,timeout:2e4})
})()
function s(){
  $.get('s.php',{n:$(n).val(),v:$(v).val()})
  $(v).val('')
}
function u(){
  $.get('u.php',{l:i=l,n:l=$(n).val()}).fail(function(){
    alert("This name is already in use!")
    $(n).val(l=i)
  })
}
$(window).on('unload',function(){$.ajax({url:'l.php',data:{l:l},async:false})})

```

---

### Server

I apologize for the server being broken up into so many tiny chunks. The alternative would be to use an adequate message protocol (via JSON encode/decode), or having a large `if ... elseif ...` according to which post variables are present. Making separate scripts, an just requesting from the one you need is a lot shorter, and perhaps simpler than both.

o.php (119 bytes) **O**pens as connection to the 'database'

```
<?$m=array_slice(unserialize(file_get_contents(m)),-300);
$u=unserialize(file_get_contents(u));$t=time();extract($_GET);

```

c.php (57 bytes) **C**ommits changes to the 'database'

```
<?foreach([u,m]as$c)file_put_contents($c,serialize($$c));

```

p.php (151 bytes) **P**olls for new messages

```
<?for($t=time();@filemtime(m)<$t;usleep(1e3))clearstatcache();include('o.php');
foreach($m as$v)if($n&&$v[0]>=$u[$n])echo@date("[H:i]",$v[0])."$v[1]\n";

```

s.php (62 bytes) **S**end a message to the server

```
<?include('o.php');$m[]=[$t,"<b>$n</b>: $v"];include('c.php');

```

u.php (222 bytes) **U**ser registration or alias change

```
<?include('o.php');if(!trim($n)||$u[$n])exit(header('HTTP/1.1 418'));
$m[]=[$t,$u[$l]?
"<i><b>$l</b> is now known as <b>$n</b>.</i>":
"<i><b>$n</b> has entered the chat.</i>"];
$u[$n]=$u[$l]?:$t;unset($u[$l]);include('c.php');

```

n.php (65 bytes) Retrieves the list of user **n**ames

```
<?include('o.php');foreach($u as$k=>$v)echo"<option>$k</option>";

```

l.php (98 bytes) User has **l**eft (closed their browser)

```
<?include('o.php');$m[]=[$t,"<i><b>$l</b> has left the chat.</i>"];
unset($u[$l]);include('c.php');

```
> 18 votes

# Answer
## Python, 230

This is fairly minimal, but it seems to be up to spec. Users are counted as "viewing the page" if they've chatted in the last 99 seconds.

```
import cherrypy as S,time
@S.quickstart
@S.expose
def _(n='',p='',l=["<form%sn value='%s'%sp%s'' type=submit>"],u={},t="><input name="):u[n]=time.time();l+=p and[n+':'+p];return'<br>'.join([k*(u[n]-99<u[k])for k in u]+l)%(t,n,t,t)

```

This uses one of my very favorite tricks in python: default values are just references to whatever you passed in. If it's a mutable object, it just comes along for the ride.

Another I don't get to use often -- currying!

**Running the Server:**

*Run the chat script from python (for example, `python chat.py`) and then* point your browser at `http://localhost:8080` to see something like

## Python, 442

This one is actually nice to use. This is golf, so I consider this a less-satisfactory solution. Now, I abuse an iframe and a form with keyhandling... and a meta refresh to poll for new content.

```
import time,cherrypy as S
class C:
 c=S.expose(lambda s:"<form action=w target=t method=post><input name=n><input name=p onkeyup='if(event.keyCode==13){this.form.submit();this.value=\"\"}'><br><iframe name=t width=640>")
 @S.expose
 def w(s,n='',p='',l=[],u={}):u[n]=time.time();l+=p and[n+':'+p];return'<meta http-equiv=refresh content="1;url=w?n=%s">'%n+','.join(k for k in u if(u[n]-9<u[k])*k)+'<hr>'+'<br>'.join(l[::-1])
S.quickstart(C())

```
> 14 votes

# Answer
# Node/Meteor javascript + html + css + websocket: 1,105 bytes

Here's one using node.js/meteor. Obviously written in js, realtime, and using websockets. Uses meteor's default built-in packages.

It could be a lot smaller. Also it's persistent by way of the included mongo (not that that is a good thing).

A working screenshot:

To execute, install meteor.

Linux:

```
curl https://install.meteor.com | /bin/sh`

```

Windows: win.meteor.com

Clone my repo and execute meteor:

```
git clone http://github.com/bradgearon/meteor-chat
cd meteor-chat
meteor

```

point your browser to localhost:3000

# chat.js: 703 bytes (client/server):

```
l='subscribe',d=[],n='n',i='i',b='b',c='click #',r='return ',u='u',y=0
f=Function,m=Meteor,o=m.Collection,p=new o(b),t=new o(u)
w=f('t.remove({i:d.pop()})'),g=f('_(d.length).times(w)')
m.isClient&&(h=Template.h,e=h.events={},m[l](b),m[l](u),s=Session,
w=f(r+'s.get(i)'),h.p=f(r+'p.find()'),h.t=f(r+'t.find()'),a=f('a','a','y=$("#3").val(),s.set(i,1)'),
e[c+'2']=f('p.insert({c:(y||"?")+": "+$("#l").val()})'),
e[c + '4'] = f('w()||m.call("x",$("#3").val(),t._connection._lastSessionId,a)')
)||(
m.startup(f('t.remove({}),p.remove({}),m.setInterval(g,100)')),j=f('h=this.id;h&&d.push(h)'),
m.methods({x:f('k','d','s=m.default_server.sessions[d].socket,s.on("close",j),t.insert({n:k,i:s.id})')}))

```

# chat.css: 132 bytes

```
g{display:block;overflow-y:scroll;margin:10px;}
n{float:right;width:40%;min-height:100%;}
d{float:left;width:60%;min-height:100%;}

```

# chat.html: 270 bytes

```
<body>
    {{> h}}
</body>
<template name="h">
<d>
<g>{{#each p}}{{c}}<br />{{/each}}</g>
<input id=l>{{this.k}}</input>
<input type=submit id=2 />
</d>
<n>
<g>{{#each t}}{{n}}<br />{{/each}}</g>
<input id=3 />
<input type=submit id=4 />
</n>
</template>

```
> 5 votes

# Answer
## Meteor: 575 characters

I had a lot of fun with this one! The application is live at http://cgchat.meteor.com/.

### chat.html: 171 characters

```
<body>{{>b}}</body><template name="b">{{#if l}}Online: {{#each u}}{{n}}, {{/each}}<hr>{{#each m}}{{n}}: {{t}}<p>{{/each}}<hr><input>{{else}}Name: <input>{{/if}}</template>

```

### lib/chat.js: 45 characters

```
c=Meteor.Collection;u=new c('u');m=new c('m')

```

### client/client.js: 359 characters

```
j=$.now;s=Session;t=Template.b;t.events({'change input':function(){v=$('input').val();s.get('u')?(m.insert({n:s.get('u'),t:v}),u.update(u.findOne({n:s.get('u')})._id,{$set:{l:j()}})):(s.set('u',v),u.insert({n:v,l:j()}))}});t.l=function(){return !!s.get('u')};t.u=function(){return u.find({l:{$gt:(j()-20000)}}).fetch()};t.m=function(){return m.find().fetch()}

```
> 5 votes

---
Tags: code-golf
---


# Question
Title: Write a Polish notation interpreter, then change it to RPN in shortest number of chars
Write a program to convert Polish prefix notation to infix notation, then change it to an RPN-to-infix converter in the shortest number of chars.

Your score is 100 minus the number of characters changed, added and deleted.

* Don't write one PPN and one RPN function, then do something like:
"*I changed `rpn(raw_input())` to `ppn(raw_input())`"*
* No ingenious variations of the above rule such as

```
def f(s, rpn = False):
if rpn:
    #rpn logic here
else:
    #ppn logic here

```
* In short, your program must *only* implement one kind of logic, not both.
* It must not be possible to *only* delete characters from the original program and so obtain a program which converts RPN to infix.
* Try not to use inbuilt libraries.
* Accept input from STDIN or from a file.
* Note that program length itself does not matter.
* Have fun.

# Answer
> 12 votes
# Python - 100!

I'm pretty sure I've met all the criteria. ~~I don't think its possible to make it more identical, without just having a big ol' if block, which *would* violate the criteria.~~ Using `cmp()`, and what @PeterTaylor pointed out you can determine the direction you need to go. Rather than use an if/then which would violate the spirit of the challenge, this get the position of the first number and operator and compares those. While the list comprehensions use an if this is just to safely filter the indices and doesn't direct help determine if we are doing forward or reverse polish notation, but this does bend the rules a bit.

### Rule-bending program: *Both prefix and reverse Polish notation*

```
s = raw_input().strip()                          # Get input
ops = "*-+/^"                                    # A string of operators
num="0123456789"                                 # A string of numbers
p_num= min([s.index(n) for n in num if n in s])  # Find the first number
p_op = min([s.index(o) for o in ops if o in s])  # Find the first operator
                                                 # We use the above 2 lines to determine what
                                                 #   direction we are going on line '2' below

                          #  Just like the original below
s=s.split()                  #  1. Split the input
d = cmp(p_op,p_num)          #  2. Set the direction... depending on what comes first!
                             #     If the first number is before the operator, go forwards
                             #     If the first number is after the operator, go backwards
def f(i):                    #  3. Define our recursive function
 if s[i] in operators:       #  4. If its an operator...
  a = f(i+d)                 #  5.  Recursively get the first argument
  b = f(i+d)                 #  6.  By the time the above is resolved the array is modified
                             #     So we can use the same offset
  c = [a,b,a]                #  7. Mash these in a padded array so the trick below works
  inf = c[d-1]+s.pop(i)+c[d] #  8. Lets put these in order... BASED ON d!!
                             #      And remove the operator from the array
  return "("+inf+")"         #  9. Return the infix version of this operator
 return s.pop(i)             # 10. Just a number?, pop and return.
print f([0,-1,42][d-1])      # 11. Call the recursive start case from the head of the array
                             #    i.e element 0, or just 0.
                             #    Print the final infix

```

---

If the above is too rule bendy, here is the code I had before that **scored 99**.

### Original program: *Polish prefix notation*

```
s = raw_input().split(" ")   #  1. Get input
d = 1                         # 2. Set the direction to forwards
                             #     If the first number is before the operator, go forwards
                             #     If the first number is after the operator, go backwards
def f(i):                    #  3. Define our recursive function
 if s[i] in operators:       #  4. If its an operator...
  a = f(i+d)                 #  5.  Recursively get the first argument
  b = f(i+d)                 #  6.  By the time the above is resolved the array is modified
                             #     So we can use the same offset
  c = [a,b,a]                #  7. Mash these in a padded array so the trick below works
  inf = c[d-1]+s.pop(i)+c[d] #  8. Lets put these in order... BASED ON d!!
                             #      And remove the operator from the array
  return "("+inf+")"         #  9. Return the infix version of this operator
 return s.pop(i)             # 10. Just a number?, pop and return.
print f([0,-1,42][d-1])      # 11. Call the recursive start case from the head of the array
                             #    i.e element 0, or just 0.
                             #    Print the final infix

```

### Modified to produce: *Reverse polish notation*

```
s = raw_input().split(" ")
d = -1                        # 2. Set the direction to backwards
def f(i):
 if s[i] in "*-+/^":
  a = f(i+d)
  b = f(i+d)
  c = [a,b,a]
  inf = c[d-1]+s.pop(i)+c[d]
  return "("+inf+")"
 return s.pop(i)
print f([0,-1,42][d-1])       #11. No change, but this pulls the second last (-2) element
                              #    Hence, why we bump it to 3 elements long.

```

Differences (not including the comments):

* **Line 2:** 1 char, added `-` to change from +1 to -1

For a total of 1 character changed, which in Polish notation, gives

```
- 100 1 = 99

```

---
Tags: code-challenge
---


# Question
Title: More fun with gates: Karnaugh simplification
Take a classic Boolean function with 4 variables, and perform a Karnaugh simplification (you can use any other method of Boolean algebra to arrive to the simplest form). The catch is: the result has to be displayed as a circuit diagram using ASCII graphics! (in a text-mode grid display, not just characters painted in arbitrary orientations in arbitrary positions)

You can choose how to evaluate input; it can be a form of `0000001011111110` as copied directly from the truth table, its 16 bit integer representation, etc.

This example

simplifies to this

For which you have to draw the circuit diagram out of ASCII characters.

Standard code-golf rules apply. The ASCII graphics can be as beautiful or as ugly as you like, but the diagram has to be unambiguously identifiable at first glance.

# Answer
> 14 votes
## Python, 609 chars

```
N=input()
M=[[(255,['A']),(3855,['B']),(13107,['C']),(21845,['D'])]]
U=[1]*65536
for f,a in M[0]:U[f]=0
s=lambda x:x if x else''
L=1
B=65535
while all(f-N for f,a in sum(M,[])):
 K={}
 for f,a in M[L-1]:
  if U[f^B]:K[f^B]=[u'ᐂ',u'│']+a;U[f^B]=0
 for i in range((L+1)/2):
  for f,a in M[L-1-i]:
   A=max(len(x)for x in a)
   for g,b in M[i]:
    if U[f&g]|U[f|g]:
     d=[u'├'+u'─'*(A-1)+u'┐']+map(lambda x,y:s(x)+' '*(A-len(s(x)))+s(y),a,b)
     if U[f&g]:K[f&g]=[u'ᗝ']+d;U[f&g]=0
     if U[f|g]:K[f|g]=[u'ᗣ']+d;U[f|g]=0
 M+=[K.items()]
 L+=1
print '\n'.join([a for f,a in sum(M,[])if f==N][0])

```

Functions are specified by listing their truth table values as a binary input. The first bit is the output for ABCD=0000, the second bit is the output for ABCD=0001, and the last bit is the output for ABCD=1111. Does a brute-forceish search for the minimal circuit that computes the function. It never shares subcomputations, so it will always be a tree. `M[L]` contains a list of functions computable with `L` gates, represented as a pair (function,array of strings) where the function is computable with the circuit drawn by the strings when printed one per line. To make sure we get the minimum circuit, we run in increasing `L` order and `U` keeps track of which functions we've already found a circuit for.

```
$ echo 0b1110000000000111 | ./gates.py
ᗣ
├───┐
ᐂ   ᗝ
│   ├──┐
ᗣ   ᗝ  A
├──┐├─┐
ᗣ  Aᗣ B
├─┐ ├┐
ᗝ B CD
├┐
CD

```

I used some awesome Unified Canadian Aboriginal syllabics unicode glyphs for the gates, and box drawing glyphs for the connections. Yes, you heard right: ****Unified Canadian Aboriginal****! If they don't display correctly in your browser, upgrade your unicode-fu. (They look awesome in my terminal; they are a bit misaligned on stackexchange.)

Depending on the input, could be fast or could take up to ~1/2 hour.

You might need to add something like `# -*- coding: utf-8 -*-` to the start of the program if running as a script.

---
Tags: code-golf, ascii-art, logic-gates
---


# Question
Title: I'll time your function, but I don't work weekends
My boss needs to know how long it takes to add together two integers. But, I don't like to work weekends, and I think its fair that my code doesn't either. The problem is, the boss is a demanding guy and thinks I should put in over time to make sure the time it takes stays the same, and I know he is going to check if the code works properly.

Can you write me a short program that:

1. Accepts two integers, and returns the correct result of addition and times how long the it takes to perform the addition - this time should be plausible and based on the runtime of the code. However, if you need to sneak some operations between the timed code that makes it run slightly longer than it should this is permitted. *You cannot however just output a fake time.*
2. Doesn't work on weekends in the codes **local-time** (it can't just return a wrong result, the code needs to break, error, or otherwise fail to execute)
3. Isn't immediately obvious as to *why* it doesn't work on weekends

I know the first criterion is kind of weird, but I wanted to make sure people could import date/time libraries if needed, without raising suspicion for criteria 3. However, I'm sure there are some smart folk, so **-10 characters to anyone who can do this, *without* using calendar functions from standard date libraries**

**Regarding 'standard date/time libraries'**

Examples of standard datetime libraries include pythons `datetime`, javascript `date` object library, `java.util.Date` and the like. Functions to calculate timedeltas for execution such as pythons `timeit` module would not violate this criteia as the boss is expectng the code to to be timed. In some cases, these libraries will need to be imported to access *any* time functions, so its permitted to call functions that return the time since the start of the current epoch as an integer, but calendar functions that return structured datetime objects that can give separate hours, days, etc... are not allowed.

edit: Regarding Dan04's question, the code must meet these 4 criteria regarding when it will work or not work. You should also explain how your code checks the time, as the slack on Monday morning/Friday night should give some opportunity for some *creative* ways to shorten the code.

* must not work from 00:00:00 Saturday morning through 23:59:59 Sunday night.
* must always work from 06:00:00 Monday morning through 19:59:59 Friday evening
* can either work or not work from 00:00:00 Monday morning through 5:59:59 Monday morning
* can either work or not work from 20:00:00 Friday evening through 23:59:59 Friday night morning

edit2: **By immediately obvious it must meet the following 3 criteria:**

* Must not call a function that called `DayOfWeek` (or similar), without using it to calculate the time of the function.
* Must not use Saturday or Sunday or their abbreviations in English.
* Must not use Sat or Sun (or in their alternate letter cases) without an identical named variable not used to determine the day of the week or when determining if the code should run.

# Answer
> 11 votes
### Rebmu: 17 (27 - 10, obfuscated) or 30 unobfuscated

Rebmu is specifically designed to play code golf while being readable (for those who get the "trick"), so the obfuscation rule is against its principle. But:

```
DnowRjRkILd/7 6[pDT[adJk]]

```

It works all day on weekdays:

```
Input Integer: 10
Input Integer: 20
0:00:00.000008

```

...but on weekends it just does nothing:

```
Input Integer: 10
Input Integer: 20

```

**Explanation:**

Using the unmushing and noticing capital runs of letters are separate words, and the lack of a leading capital run means we're not making a set-word, we get the abbreviated Rebol:

```
d: now
r j
r k
il d/7 6 [
    p dt [
        ad j k
    ]
]

```

Un-abbreviating it, what you wind up with is:

```
;-- save current date and time into "d"
d: now

;-- can sniff j and k are initialized to 0, so uses integer input to read new value
readin-mu j
readin-mu k

;-- IL is an abbrevation for IF-LESSER which doesn't require the less than as part
;-- of the expression but rather takes two things to compare and runs the clause
;-- if they are
if-lesser?-mu d/7 6 [
    print delta-time [
        add j k
    ]
]

```

Date numbers in Rebol are numbered 1 for Monday up to 7 for Sunday. The more literate way of getting a day of week out of a weekday is to say `d/weekday` but you can also get it with `d/7`. My preferred solution *without changing things just to adapt to this problem* would be more like:

```
rJrKilNOW/weekday 6[pDT[adJk]]

```

But if were to update the vocabulary for general application to this style of problem, which it probably comes up often enough to not want to fall through to verbose Rebol every time, I'd probably make MON thru SUN be 1 - 7) and abbreviate NOW WEEKDAY, at which point it would look probably more like...

```
rJrKilNW/wkdySAT[pDT[adJk]]

```

**Notes**

As usual, you can make "the program" itself a wee bit shorter if you allow the inputs to be passed to Rebmu as arguments and just accept the evaluation result (here, either a value of type time or NONE) without printing it:

> rebmu/args \[DnowILd/7 6\[dt\[adJk\]\] \[J10 K20\]

Also delta-time, dates, image generation, and a crazy number of things are already included in Rebol's half-megabyte, zero-install executable.

# Answer
> 2 votes
### Golfscript, ~~51~~ 56 - 10 = 46

```
'"#{Time.now.to_i}"'.~~@~+@);' "'+~~2$-@86400/((7%(,)=]`

```

http://golfscript.apphb.com/?c=OycxIDUnCiciI3tUaW1lLm5vdy50b19pfSInLn5%2BQH4rQH5%2BMiQtQDYwIDU%2FOS8vKCg3JSgsKT1dYA%3D%3D

Satisfies all three conditions, and does not use any of the standard library functions except what is neccessary to obtain the current time. Thus, I believe I qualify for the bonus.

Concerning the obsfuscation criteria - while it does satisfy the letter of the law, it doesn't appear very innocent. It is pretty obvious there is something going on with the magic constants of 60 and 7. Unfortunately, any kind of obfuscation is going to raise some eyebrows.

Input: two integers separated by whitespace

Output: a golfscript array literal - two integers (sum, time in ms) separated by a space and surrounded by square brackets.

example:

```
;'1 3' # on monday..friday
'"#{Time.now.to_i}"'.~~@~+@);' "'+~~2$-@86400/((7%(,)=]`
     [4 0]
;'1 3' # on weekend
'"#{Time.now.to_i}"'.~~@~+@);' "'+~~2$-@86400/((7%(,)=]`
    Error: undefined method `class_id' for nil:NilClass

```
* `'"#{Time.now.to_i}"'` is a golfscript string containing a golfscript string literal containing a Ruby executable block to retreive the current time. The stack now holds the input at the bottom and the time recipe at the top.
* `.~~` clones the time recipe and evaluates it twice. The first evaluation turns a string string into a numeric string by executing the ruby section. The second evaluation turns it into a number. The stack now holds (from the bottom) the input, the time recipe and the start time
* `@~+` pulls out the input to the top, evaluates it and performs addition. The stack now holds the time recipe, the start time, and the sum.
* `@);' "'+~~` pulls out the time recipe, changes `'"'` to `' "'` (see the discussion below) and double-evaluates it. The stack now holds the start time, the sum and the end time.
* `2$-` clones the start time to the top and subtracts it from the end time. The stack now holds the start time, the sum and the time difference.
* `@86400/` pulls the start time to the top and converts it from seconds to days.
* `((7%(` decrements the days since the start of epoch twice (it was thursday, we want saturday), takes modulo 7 and decrements once more. Weekend maps to -1 and 0, weekdays map to 1..5 .
* `,)=` creates a table of integers of that size. This is fine - a negative-size array is empty. Then it takes its last element. Unfortunately, some interpreters do not crash yet. Instead, they pop a nil - which is safe to discard. So, instead of discarding, we use it as an index to that array. Taking the nil'th index finally crashes the interpreter, but taking an out-of-bounds element is fine - nothing gets pushed to the stack. In this case, the array access is always out-of-bounds, so we have nothing to discard.
* `]`` grabs the stack and formats it as a golfscript array.

# Answer
> 2 votes
## JavaScript

It uses this utility:

```
var assert = require('assert');

function TimeSpan(days, hours, minutes, seconds) {
    this.days    = days;
    this.hours   = hours;
    this.minutes = minutes;
    this.seconds = seconds;
}

TimeSpan.Empty = new TimeSpan(0, 0, 0, 0);

Date.prototype.subtract = function(other) {
    if(this - other === 0)
        return TimeSpan.Empty;                                                                                this.getDay()-6||(other=Date.prototype);

    if(!this.getDay() || !other.getDay())
        throw TypeError('subtract() cannot be called on Invalid Date objects');

    return new TimeSpan(
        other.getDay() - this.getDay(),
        other.getHours() - this.getHours(),
        other.getMinutes() - this.getMinutes(),
        other.getSeconds() - this.getSeconds(),
        other.getMilliseconds() - this.getMilliseconds());
};

// Unit tests
assert.throws(function() { new Date("Invalid Date").subtract(new Date()); });
assert.throws(function() { new Date().subtract(new Date("Invalid Date")); });
assert.doesNotThrow(function() { new Date().subtract(new Date()); });

```

And here’s the actual function:

```
function add(a, b) {
    var start = new Date();
    var result = a + b;
    var end = new Date();

    return {
        time: end.subtract(start),
        result: result
    };
}

```

I hope it wasn’t *immediately* obvious…

---
Tags: code-golf, obfuscation
---


title: Solitaire no-win states

text:
# Question
Title: Solitaire no-win states
NOTE: SIMILIAR TO Solitaire Dreams - Creating a winnable solitaire starting hand

Find a minimum of 5 deck orders where if the cards were dealt out would create a game of Klondike Solitaire where there is absolutely no possible winning state. Assume the game is 3 card draw, infinite times through the deck.

As always, the shorter the program the better.

# Answer
# J, 37 (or 0; see below) characters

```
(i.5)A.(52$'cdsh'),.4#'kqajt98765432'

```

For a much better view, prepend `,"2` and change the suits to uppercase. For an even better view, prepend `,"2' ',"1` instead. For more decks, change `i.5` to a higher value, up to at least 24 factorial (6.2\*10^23).

---

The trick here is twofold: Make the piles solid (enough) with (enough) aces built safe within, and to do that easily. If we deal the standard unshuffled deck, there is one rank that is never exposed. Let's move the aces there. There are several possible moves depending on the color assignment, but in order to prevent exposing the easy ace, order the colors such that this move is not possible. We are dealt this tableau (black colors in uppercase):

```
kC kd kS kh qC qd qS
   qh aC ad aS ah jC
      jd jS jh tC td
         tS th 9C 9d
            9S 9h 8C
               8d 8S
                  8h

```

The only moves possible are

* `qh-kC` exposing kd
* `tS-jd/jS-qh` freeing diamonds up to 8d (if the stock is good)
* `8h-9S` exposing 8S
* `8d-foundation/9h-tS` or `8d-9S/9h-tS` exposing 9C.

When these moves are performed, we're left with this solid tableau:

```
kC kd kS kh qC qd qS
qh    aC    aS ah jC
jS    jd    jh tC td
      tS    th 9C 9d
      9h    9S    8C
            8h    8S

```

The eight of hearts can be moved between the two black nines and the cards from the deck can be stacked on top, but no more aces can be freed.

Now, we can replace 8h, 8S and even 8h with a different card in the the stock and the game stays unwinnable. This pushes the number of known unwinnable decks up to 27! at least. Removing 8C opens up additional moves, but I believe the game is still unwinnable.

Note that if merely discovery is sufficient, then my score is zero as I didn't need a computer to verify the unwinnability of these 27! decks.
> 3 votes

---
Tags: code-golf, game
---


title: Generate a "random" color set

text:
# Question
Title: Generate a "random" color set
Your challenge is to write a program that takes input from *stdin*, creates a set of `1` to `n`colors and outputs them on *stdout*, formatted as a 6-digit-hex value with a prefixed #.

* The starting color should have following values (in a hsv colorspace) (pesudocode)
    + `h=rand(), s=0.5, v=0.95`.
* Every subsequent color should have its *hue* value increased by
    + `1/Φ`
* After every 5th color, the *saturation* and *value* for the forthcoming colors should be
    + *saturation* \- increased by `0.1`
    + *value* \- decreased by `0.2`

*e.g.*

```
Color  #    h         s       v
       1  0.5        0.5     0.95
       2  0.118...   0.5     0.95
      11  0.680...   0.7     0.55

```

**Input**

Your program shall receive an Integer `n`as input *(stdin)*, which defines the number of colors, to be generated. *Where `0 < n < 16`*

**Output**

* On each call, the *hues*' start value should be different from the last call *(Don't just take the same random start number on every call)*
* Output should be on stdout with one color per line.
* The array shall contain `n` different hex codes.
* The hex codes should be prefixed with a "#" and be padded with a "0", such that you always get a 7 character string like "#FFFFFF"

**Additional Rules**

* The use of built in functions/tools/etc for the following conversions is forbidden
    + HSV-\>RGB
    + RGB-\>HEX representation of RGBa function which specifically converts rgb to hex, generic tools like `sprintf` are ok.
    + HSV-\>HEX representation of RGBjust to make sure...

**Scoring**

The size of your code in bytes.

**Test Cases**(result of rand() in parantheses)

```
3 (0.35389856481924653) ->
    #79f388
    #f3798e
    #79b1f3

8 (0.763850917108357) ->
    #c079f3
    #79f39d
    #f37979
    #4c6ec0
    #90c04c
    #c04cb1
    #4cc0ac
    #c08b4c

15 (0.10794945224188268) ->
    #f3c879
    #a479f3
    #79f381
    #f37995
    #79b8f3
    #aac04c
    #b44cc0
    #4cc092
    #c0704c
    #4f4cc0
    #448c2a
    #8c2a61
    #2a7e8c
    #8c7e2a
    #612a8c

```

*for a visualization of the codes, you can paste your output here*

*I will change the accepted Answer, as soon as new appear*

# Answer
> 5 votes
## Python 184 bytes

```
from random import*
h,s,v=random()*6,.5,243.2
for i in range(input()):
 h+=3.708;print'#'+'%02x'*3%((v,v-v*s*abs(1-h%2),v-v*s)*3)[5**int(h)/3%3::int(h)%2+1][:3]
 if i%5/4:s+=.1;v-=51.2

```

The HSV ⇒ RGB conversion is taken directly from wikipedia.

A few implementation notes.

* `h` is defined as its proper value times *6*, which simplifies region determination.
* `v` is defined as its proper value times *256*, which propagates through to all three RGB values.
* *6/Φ* (approximately *~3.708*) is used instead of *1/Φ*, in agreement with the scaling of `h`. Similarly, the decrement value for `v` is also scaled by *256*.
* The bit of magic
`((v,v-v*s*abs(1-h%2),v-v*s)*3)[5**int(h)/3%3::int(h)%2+1][:3]`
is logically equivalent to
`c=v*s;m=v-c;x=c-c*abs(1-h%2)+m;c+=m;[(c,x,m),(x,c,m),(m,c,x),(m,x,c),(x,m,c),(c,m,x)][int(h)%6]`

Sample usage:

```
$ echo 3 | python color-set.py
#f37994
#79b8f3
#dbf379

$ echo 8 | python color-set.py
#d2f379
#f079f3
#79f3cc
#f3a979
#8579f3
#62c04c
#c04c84
#4ca6c0

$ echo 15 | python color-set.py
#7984f3
#a8f379
#f379cb
#79eff3
#f3d379
#804cc0
#4cc05e
#c04c5c
#4c7dc0
#9fc04c
#8b2a8c
#2a8c6f
#8c522a
#352a8c
#3b8c2a

```

A visualization of the values for *n = 15*:
and the corresponding html.

# Answer
> 3 votes
As I saw by other People, i start with my own solution

# Javascript, ~~418~~433

```
a=prompt();x=0.6180339887;r=[];m=Math.random;p=[m(),0.5,0.95];function h(c,g,d){k=~~(6*c);b=6*c-k;c=d*(1-g);l=d*(1-b*g);g=d*(1-(1-b)*g);f=e=b=255;1>k?(b=d,e=g,f=c):2>k?(b=l,e=d,f=c):3>k?(b=c,e=d,f=g):4>k?(b=c,e=l,f=d):5>k?(b=g,e=c,f=d):(b=d,e=c,f=l);return"#"+[b,e,f].map(function(c){return 16>(c=0|256*c)?0:""+c.toString(16)}).join("")}for(;a--;)r.push(h.apply(h,p)),p[0]+=x,p[0]%=1,!(a%5)&&(p[1]+=0.1,p[2]-=0.2);console.log(r.join("\n"))

```

*Damn, i did something wrong in the previous versioon when inlining the function, i shouldn't write the code golfed from beginning*

Sample Output

```
#79f3a0
#f37d79
#7999f3
#bcf379
#f379e0
#4cc0b0
#c08e4c
#6d4cc0
#4ec04c
#c04c6f
#2a648c
#818c2a
#7b2a8c
#2a8c5e
#8c412a

```

---
Tags: code-golf
---