text:
Pretty-printing polynomials
A polynomial over a variable x is a function of the form

p(x) = anxn + an-1xn-1 + ... + a1x + a0

where a0 ... an are the coefficients. In the simplest
case, the coefficients are integers, e.g.

p1(x) = 3x2 + 4x + 1

By allowing the coefficients to be polynomials over another variable, we can define
polynomials over multiple variables. For example, here is a polynomial over x whose coefficients are
polynomials over y with integer coefficients.

p2(x,y) = (2y + 1)x2 + (3y2 - 5y + 1)x + (-4y + 7)

However, we often prefer to write these fully expanded as

p2(x,y) = 2x2y + x2 + 3xy2 - 5xy + x - 4y + 7

Your task is to write a program that will pretty-print a given polynomial in this format.
Input
Your program will receive a single line on standard input* describing a polynomial over multiple variables
in the following format.
<name> <variables> <coefficients>

<name> is one or more arbitrary non-whitespace characters.
<variables> is one or more characters between a and z inclusive, each representing a variable. There are no duplicates, but note that the order is significant, as it affects how the terms should be ordered in the output.
<coefficients> is one or more coefficients, separated by spaces, in order of increasing degree.

Each coefficient is either an integer in the usual base 10 notation, or another list of coefficients between
square brackets. The different variables correspond to the nesting level of the coefficients, with the
"outermost" list corresponding to the first variable and so on. The number of nesting levels will never
exceed the number of variables.
For example, the polynomials p1 and p2 above can be represented as follows.
p1 x 1 4 3
p2 xy [7 -4] [1 -5 3] [1 2]

Since constant polynomials can be interpreted as polynomials over any set of variables, some polynomials
may be written in multiple ways. For example, the coefficients of p3(x,y,z) = 4 can be written as 4, [4]
or [[4]].
Output
Your program should pretty-print the input polynomial on standard output* in the following format.
<name>(<variables>) = <terms>

<name> is the name of the polynomial as received.
<variables> is the list of variables in the order received, interspersed with commas.
<terms> are the terms of the fully expanded polynomial, formatted according to the rules below.
Each term is an integer coefficient followed by powers of each variable in the order defined in the input,
all separated by a single space. The general format is <variable>^<exponent>.
The terms are sorted by the exponents of the variables in decreasing lexicographical order. For example, 3 x^2 y^4 z^3 should come before 9 x^2 y z^13 because 2 4 3 > 2 1 13 lexicographically.
Omit terms where the integer coefficient is zero, unless the whole polynomial is zero.
Omit the integer coefficient if its absolute value is one, i.e. write x instead of 1 x, unless this is a constant term.
When the exponent of a variable in a term is zero, omit the variable from that term.
Similarly, when the exponent of a variable is one, omit the exponent.
The terms should be separated by + or - signs, with a space on each side, according to the sign of
the integer coefficient. Similarly, include the sign in front of the first term if it's negative.

Examples
Input                             Output
================================  =======================================================
p1 x 1 4 3                        p1(x) = 3 x^2 + 4 x + 1
p2 xy [7 -4] [1 -5 3] [1 2]       p2(x,y) = 2 x^2 y + x^2 + 3 x y^2 - 5 x y + x - 4 y + 7
p3 xyz [4]                        p3(x,y,z) = 4
foo bar [0 2 [0 1]] [[3] [5 -1]]  foo(b,a,r) = - b a r + 5 b a + 3 b + a^2 r + 2 a
quux y 0 0 0 0 0 1337             quux(y) = 1337 y^5
cheese xyz [[0 1]]                cheese(x,y,z) = z
zero x 0                          zero(x) = 0

Winning criteria
This is code golf. The shortest program wins. Standard code golf rules apply.
Bonus challenge
Write another program which does the reverse operation, i.e. takes the pretty-printed output of your original program and gives you back one of the possible corresponding inputs. This is purely for bragging rights and has no effect on
your score.
* If your chosen programming language doesn't support standard input/output, you may specify how I/O is handled.

Did I misunderstand or is the bonus challenge impossible? There are many ways to ugly-print a pretty polynomial.

@Superbest: Any ugly version of the polynomial will do.  I've added a clarification.

Does appending "+1-1" not constitute a trivial solution?

@Superbest: Read the specification of the input format (which your current program doesn't support).

Your p1 and quux examples are inconsistent.  p1 doesn't have brackets and quux does.  Which is right?

@KeithRandall: Fixed. p1 is correct. There are no brackets around the outermost set of coefficients.

Mathematica:
Expand[Input[]] // TraditionalForm

will produce the expanded form.
Example input:
(2y + 1)x^2 + (3y^2 - 5y + 1)x + (-4y + 7)

Into the input prompt, click OK. Observe pretty output.

Python, 323 chars
I=raw_input().split()
print'%s(%s) ='%(I[0],','.join(I[1])),
def P(L,p,f):
 if type(L)==list:
  for i in range(len(L))[::-1]:P(L[i],p+[i],f);f=0
 elif L or f:A=abs(L);print'+-\0-'[2*f+(L<0)]+[(' %d '%A)[f:],' '][A==1and sum(p)>0]+' '.join([v,v+'^%d'%e][e>1]for v,e in zip(I[1],p)if e),
P(eval('['+','.join(I[2:])+']'),[],1)

Your sorting is wrong: p yx [0 1] 1 gives y x, should be x y. Also spaces aren't 100% - p x 1 -2 gives p(x) = -2 x + 1, p x 0 1 gives p(x) =  x.

Python, 252 460 chars
Significantly longer than Keith Randall's, but matches the specifications better.
I copied type(o)==list from Keith. There are other similarities, but they were reached independently.
Sensitive to whitespace in the input. Particularly, space after [ or before ] breaks it.
e=lambda o,v,p:type(o)==list and[x for y in [e(c,v[1:],p+[(v[0],i)])for i,c in enumerate(o)]for x in y]or[(o,p)]
def f(x,y):z=" ".join(("%s^%d"%(a,b),a)[b<2]for a,b in y if b);return "+-"[x<0]+(" %d "%abs(x)," ")[z>"" and abs(x)==1]+z
l=raw_input().split()
t=" ".join(f(*x)for x in sorted(e(eval("["+",".join(l[2:])+"]"),l[1],[]),key=lambda x:[-dict(x[1]).get(a,0)for a in l[1]])if x[0])or'0'
print"%s(%s) = %s"%(l[0],",".join(l[1]),t[2*(t[0]=='+'):])

Logic:
Build a list of numbers/lists by replacing whitespace with commas and using eval (so 1 [2 3] becomes eval("[1,[2,3]]").
e converts the nested lists to a single list, with elements list (3,[('x',2),('y',1)]) (for 3 x^2 y).
I sort the list, with a key function that converts ('x',2),('y',1) to 2,1, by lexicographical order.
f prints each element in the list, preceded with +/-, and considering ones and zeros.
Just before printing, a preceding + is removed.


text:
Minimal Sudoku Generator
Ask questions if you need to, I'll elaborate on anything that needs clarified.
My challenge is to unsolve a sudoku to a minimal state. Basically take a supplied, solved, sudoku board and unsolve it as far as possible while keeping the solution unique.
I'll leave input up to you, I don't like forcing anything which would make some solutions longer.
Output can be anything reasonable, as long as it spans the nine lines it'll take to display the sudoku board, for example:
{[0,0,0], [0,0,0], [0,1,0]} ┐
{[4,0,0], [0,1,0], [0,0,0]} ├ Easily understood to me
{[1,2,0], [0,0,0], [0,0,0]} ┘

000000010 ┐
400010000 ├ A-OKAY
120000000 ┘

000, 000, 010 ┐
400, 010, 000 ├ Perfectly fine
120, 000, 000 ┘

000000010400010000120000000 <-- Not okay!

Example
input:
693 784 512
487 512 936
125 963 874

932 651 487
568 247 391
741 398 625

319 475 268
856 129 743
274 836 159

output:

000 000 010
400 000 000
020 000 000

000 050 407
008 000 300
001 090 000

300 400 200
050 100 000
000 806 000

Most minimal answer in shortest time is the winner.

So we should take in a sudoku board with some entries filled in, and output another sudoku board with some more entries filled in, such that it has a unique solution?

Changed challenge a bit, will add puzzles for input.

Is it required that the output board be solvable without brute force (i.e. using some polynomial-time strategy)? And what does "as far as possible" mean? Is a local minimum acceptable even if it isn't a global minimum?

As far as your program can take it, and as long as it has a solution that requires no guessing/backtracking.

A Sudoku board contains 81 digits (3x3 boxes, 3x3 digits each), your examples have 27 only.

That seems to allow too much flexibility to constitute a real spec. I can make my program only know really simple rules, and then it won't get very far; whereas a program with Nishio in its ruleset could get further, but would be longer.

@ugoren those examples are demonstrative of how output should be while being succinct. Example input and output show 81.

@PeterTaylor changed it to a code challenge, most minimal answer is the goal, shortest time is second goal.

@Rob, Problem isn't finding a program which generates a valid (solvable) sudoku puzzle.  The problem is proving it is as minimal as you can get.  I think that in of itself makes this a polynomial-order problem, which makes the solution to this problem work in polynomial speed or otherwise it is merely an approximation.

@Neil: From wikipedia: "The problem of determining if a partially filled square can be completed to form a Latin square is NP-complete.[6]".

A single sudoku instance might have multiple minimal "unsolved" states.  Do we have to return them all, or just give one?

Less technical question -- "Most minimal answer in shortest time is the winner." -- Doesn't that just mean the first person to answer will win, whatever the length of the solution?

This would be a good [tag:code-golf].

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Shortest ELF for "Hello world\n"?
Is it possible to write (pack) a shorter than 145 bytes version of a program with "Hello world" (plus new line) output if the length of the program is measured as a number of bytes in program's ELF (x86) representation? Reduction technique in mind is described here:

http://timelessname.com/elfbin/
http://www.muppetlabs.com/~breadbox/software/tiny/teensy.html

Please reply with providing a code example. Note, 1 says "Hi world" and [2] returns 42 instead of an output, hence I assume current solution to be 142 + (len("Hello") - len("Hi")) which is 145.
[EDIT]
Limits of ELF: syntactically a program translated into ELF is determined by its interpreter (libc), which is a combination of:

Target architecture (Generic, AMD64, ARM, IA-32, MIPS, etc.)
OS kernel (which communicates with implementation of ELF interpreter and often is itself packed into an ELF binary)

From TIS spec. 1.2

There is one valid program interpreter for programs conforming to the
  ELF specification for the Intel architecture: /usr/lib/libc.so.1

In theory - all clear - multiple combinations times version differences (Arch, OS) are possible. In practice - because standard is less strict than any BNF for CFG or other finer (smaller) formal language - there can be implementation differences (options) including shorter length of the program.
On one hand, because ELF is not that precise (one naturally expects) it is much more difficult to do code-golf with it. Hence a "Hello world\n" program is expected to be by default in TIS ELF 1.2, x86 (Generic Intel), Linux 2.6.(20+). On the other hand having a shorter ELF that runs e.g. on *BSD seems like an extremely valuable knowledge to me!
For example ELF64 (latest draft) is much more interesting incl. the differences with ELF(x86). So, please share a solution that can be accepted with correction to specific configuration.
Motivation: It is the practical part that is interesting for me and code-golf is a very nice way to show how tricky it is to come up with any machine- (or even byte) code in general and why ELF does apparently such a good job (in my understanding). Thus a golf solution is not only cool per say but also can provide a practical knowledge of unexpected interpretation differences of ELF (if an alternative combination is given).

It's trivial to modify Adam Rosenfield's 116-byte ELF file to include a newline, giving a 117-byte executable that prints "Hello world\n" in a Linux terminal window. The byte-sequence is 7F 45 4C 46 01 01 01 00 00 00 00 00 00 00 00 00 02 00 03 00 01 00 00 00 54 80 04 08 34 00 00 00 00 00 00 00 00 00 00 00 34 00 20 00 01 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 80 04 08 00 80 04 08 74 00 00 00 74 00 00 00 05 00 00 00 00 10 00 00 B0 04 31 DB 43 B9 69 80 04 08 31 D2 B2 0C CD 80 31 C0 40 CD 80 48 65 6C 6C 6F 20 77 6F 72 6C 64 0A.

Thanks for pointing out the duplication. I was not aware of it. @FUZxxl What is the problem of having a more precisely asked question? I see the redundancy with the previous question but I don't like the way it is asked at all, e.g. it says nothing about code-golf. If "less than 20 byte" is just an olympic puzzle then there is no duplication per say. Another matter - are you really an opinion that simply closing creates a better Q&A knowledge base? I have not even found "less than 20 byte" question. IMHO wikipedia achieves something similar with redirects - much more constructive.

If it is not obvious enough - my current question is about "studying" ELF only which has normally longer header due to lot of metadata. E.g. going via asm code solution does here no good. Coming up with a new shorter execution format special designed for this question is also not accepted. It's about limits of ELF. Thus modification of Adam Rosenfield's 116-byte ELF file is the best answer so far.

The scope of the question seems basically limited to x86 machines running an operating system that uses the ELF standard. Would that be virtually all x86 non-Windows machines? (BTW, I find that the executable mentioned in my previous comment -- just copy/paste/save the binary using a hex editor -- runs successfully on my x86-64 under both 32- and 64-bit versions of Ubuntu. Isn't that unexpected?)

Since we typically have tags for language-specific questions, I went and created an [tag:executable-binary] tag for this question. I decided not to create [tag:x86] or [tag:elf] yet -- let's see if we get more questions like this first.

@FUZxxl: Duplicate of an SO question doesn't really count, does it? I wouldn't search SO before asking a question, too.

@r.e.s. Linux for amd64 has code that can run programs compiled for x86, provided that all libraries the program needs are available for x86 as well. Actually, you can even use the old int $0x80 method to call the operating system - even from amd64 code!

Another issue for the OP: I think the question should make it clear whether the desired "shortest ELF" executable binary is required to adhere to the ELF standard. (The cited tutorial admittedly violates it eventually, whereas the posting linked in my "answer" claims adherence to it.)

ELF (x86) files are not compatible between operating systems. NetBSD might require a longer solution than Linux.

Sorry, for not being precise enough after all @r.e.s. I hope new correction is much clearer. Asking code-golf about binary executable can be valid and reasonable but only if expected configuration is clearly stated (by OP or AP).

@Mego Hi Mego, I am not sure it if mine question is a duplicate. It was asked in 2012 not in 2015. But you have to figure it out yourself. It is really not about comparing programming languages in general. It is a very concrete task requiring knowledge of the machine code i.e. ELF dialect. I would not accept solution in ruby or perl. So no it is not really a duplicate.

Even if you require full adherence to the ELF specification, you can squeeze it into 98 bytes:
            org     0x04B34000
            db      0x7F, "ELF", 1, 1, 1, 0 ; e_ident
            dd      0, 0
            dw      2                       ; e_type
            dw      3                       ; e_machine
            dd      1                       ; e_version
            dd      _start                  ; e_entry
            dd      phdr - $$               ; e_phoff
            dd      0                       ; e_shoff
            dd      0                       ; e_flags
            dw      0x34                    ; e_ehsize
            dw      0x20                    ; e_phentsize
phdr:       dd      1                       ; e_phnum       ; p_type
                                            ; e_shentsize
            dd      0                       ; e_shnum       ; p_offset
                                            ; e_shstrndx
            db      0                                       ; p_vaddr
_start:     inc     eax
            mov     bl, 4
            mov     dl, 12                                  ; p_paddr
            jmp     short part2
            dd      filesize                                ; p_filesz
            dd      filesize                                ; p_memsz
            dd      5                                       ; p_flags
            dd      0x1000                                  ; p_align
str:        db      'Hello world', 10
part2:      mov     ecx, str
again:      xchg    eax, ebx
            int     0x80
            jmp     short again
filesize    equ     $ - $$

Or if you prefer hex bytes:
7F 45 4C 46 01 01 01 00 00 00 00 00 00 00 00 00 02 00 03 00 01 00 00 00 35 40 B3 04 2C 00 00 00 00 00 00 00 00 00 00 00 34 00 20 00 01 00 00 00 00 00 00 00 00 40 B3 04 B2 0C EB 1C 62 00 00 00 62 00 00 00 05 00 00 00 00 10 00 00 48 65 6C 6C 6F 20 77 6F 72 6C 64 0A B9 4C 40 B3 04 93 CD 80 EB FB
The ELF specification explicitly permits different sections to overlap, so it is perfectly legal to let the program segment header table share bytes with the ELF header. Furthermore, the x86 version of the ELF standard states that the p_paddr field is ignored, as opposed to merely being unused (which typically comes with the requirement that it be set to zero. Thus it is safe to contain arbitrary bytes.
Finally, three more bytes are saved by overlapping the code with the load address.

Direct from the source ;) The xchg/jmp is particularly clever.

to make it work on amd64, I've added BITS 32 at the very top. It doesn't change the byte count in the executable.

Try it online!

Looking at link [2] A Whirlwind Tutorial on Creating Really Teensy ELF Executables for Linux, by appending the literal string 'Hello, world!' to the end (instead of letting the last 7 bytes auto fill with zeros), you should be able to squeeze it to 59 bytes, assuming your print logic isn't longer than 8 bytes.
In fact, the user 'breadbox', who I assume to be the writer of the post, has posted a 57 byte version on anarchy golf. It might be useful to look at some of his other post mortems: they seem to be all ELF format.
EDIT: 61 bytes
Using breadbox's nested header approach, I was able to produce this 61 byte solution:
BITS 32
        org     0x05000000
        db      0x7F, "ELF"
        dd      1
        dd      0
        dd      $$
        dw      2
        dw      3
        dd      0x0500001B
        dd      0x0500001B
        dd      4
        mov     dl, 12
        mov     ecx, msg
        int     0x80
        db      0x25
        dw      0x20
        dw      0x01
        inc     eax
        int     0x80
msg     db      'Hello world', 10

Assemble as:
nasm -fbin hello.asm
chmod +x hello
./hello

Producing:
00000000  7f 45 4c 46 01 00 00 00  00 00 00 00 00 00 00 05  |.ELF............|
00000010  02 00 03 00 1b 00 00 05  1b 00 00 05 04 00 00 00  |................|
00000020  b2 0c b9 31 00 00 05 cd  80 25 20 00 01 00 40 cd  |...1.....% ...@.|
00000030  80 48 65 6c 6c 6f 20 77  6f 72 6c 64 0a           |.Hello world.|

The code begins at 0x001B:
0540000000      add     eax, 0x00000004    ;sys_write
B20C            mov     dl,  12            ;message length
B92E000005      mov     ecx, msg           ;message pointer
CD80            int     0x80               ;syscall
2520000100      and     eax, 0x00010020    ;clears eax
40              inc     eax                ;sys_exit
CD80            int     0x80               ;syscall

The 32-bit add is necessary (instead of mov al, 4 for example), because it's also used as the program header offset, and needs to be exactly 4 (where the program header starts in the above code). The and later on is used to clear eax, because 0x20 and 0x01 are unavoidable header values.
EDIT: 111 bytes (with proper headers)
If, on the other hand, you'd rather your headers adhere to the ELF specifications (even if your kernel ignores them), you could use this instead:
BITS 32
            org     0x08048000
ehdr:                                               ; Elf32_Ehdr
            db      0x7F, "ELF", 1, 1, 1, 0         ;   e_ident
    times 8 db      0
            dw      2                               ;   e_type
            dw      3                               ;   e_machine
            dd      1                               ;   e_version
            dd      _start                          ;   e_entry
            dd      phdr - $$                       ;   e_phoff
            dd      0                               ;   e_shoff
            dd      0                               ;   e_flags
            dw      ehdrsize                        ;   e_ehsize
            dw      phdrsize                        ;   e_phentsize
            dw      1                               ;   e_phnum
            dw      0                               ;   e_shentsize
            dw      0                               ;   e_shnum
            dw      0                               ;   e_shstrndx
ehdrsize    equ     $ - ehdr

phdr:                                               ; Elf32_Phdr
            dd      1                               ;   p_type
            dd      0                               ;   p_offset
            dd      $$                              ;   p_vaddr
            dd      $$                              ;   p_paddr
            dd      filesize                        ;   p_filesz
            dd      filesize                        ;   p_memsz
            dd      5                               ;   p_flags
            dd      0x1000                          ;   p_align
phdrsize    equ     $ - phdr

_start:     mov     al, 4
            mov     dl, msg_len
            mov     ecx, msg
            int     0x80
            mov     al, 1
            int     0x80

msg         db      'Hello world', 10
msg_len     equ     $ - msg

filesize    equ     $ - $$

It's tempting to overlap the last 8 bytes of the ehdr with the first 8 bytes of the phdr, since they are identical (and therefore, all headers would be correct), but in the spirit of being proper, I decided not to.
This assembles to a 111 byte solution:
00000000  7f 45 4c 46 01 01 01 00  00 00 00 00 00 00 00 00  |.ELF............|
00000010  02 00 03 00 01 00 00 00  54 80 04 08 34 00 00 00  |........T...4...|
00000020  00 00 00 00 00 00 00 00  34 00 20 00 01 00 00 00  |........4. .....|
00000030  00 00 00 00 01 00 00 00  00 00 00 00 00 80 04 08  |................|
00000040  00 80 04 08 6f 00 00 00  6f 00 00 00 05 00 00 00  |....o...o.......|
00000050  00 10 00 00 b0 04 b2 0c  b9 63 80 04 08 cd 80 b0  |.........c......|
00000060  01 cd 80 48 65 6c 6c 6f  20 77 6f 72 6c 64 0a     |...Hello world.|

That tutorial says "half of the values in this file violate some part of the ELF standard", whereas Adam says his is "the minimal possible ELF without doing any sneaky trickery from that article". Since the tutorial is cited by the OP, it looks like I misread the present question as requiring adherence to the ELF standard. OTOH, the OP says in a comment that it's "about limits of ELF", so I'm not sure.

On my x86-64 machine running 32-bit Ubuntu, the 60-byte executable outputs "Hello, world!\n", then causes a "Segmentation fault" message. (Neverminding the run-time error, the OP requires just "Hello world\n" -- saving you two more bytes.)

This was the result of a missing system exit call, and I've corrected for this at the cost of 3 bytes. I've also added a 111 'clean' version, in which all of the headers are set correctly.

I haven't actually read the ELF standard, but I'd be surprised if it explicitly said that the headers can't overlap (as long as all the values are still set according to spec). So I'd guess the 8 byte saving ought to be fine.

The 61-byte solution given here is largely equivalent to the 62-byte solution I have on my page, the extra char being the comma that's missing from this version. The 57-byte version only works on certain versions of the 2.4 kernel; by loading to address zero, it allows for greater interspersing of code inside the header fields. (See the above web page for a link and more details.)

I did specifically state that I was basing my result on your tutorial. Had I known of the link you just posted, I would have posted that instead.

Indeed you did. I just want to make it perfectly clear that the 57-character version is NOT original with me; the original author indicated on my web page (whoever they are) deserve all the credit.

@primo : and for armel ?

I ran it on tio and get no output

@i4m2 nasm -fbin hello.asm \ chmod +x hello \ ./hello

Still no

Checked locally it works, not sure why not on tio

It doesn't appear to be respecting the virtual address. Perhaps a sandboxing issue?

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
PHP golfing tips: Reading/writing files and the CLI
I have been participating in a number of PHP code golf challenges recently and some of the techniques that are used to read data from a file such as fopen() and fread() or file_get_contents() really give my code a beating on the char count. Especially the methods provided for reading in command line input.
My question is, what is the fastest way (least keystrokes) to read and write to the contents of a file, and what is the fastest way (least keystrokes) to read a line from the prompt?
(Note: As this is code golf, I can't use any external libraries.)

You can read a line from STDIN in 13 characters:
fgets(STDIN);

as seen here.
Reading from a file:
file('filename')

returns an array of lines of the file.
Using fputs instead of fwrite will save a character on writing, but I can't think of a shorter way than:
fputs(fopen('filename','w')); //use 'a' if you're appending to a file instead of overwriting

which is marginally shorter than:
file_put_contents('filename');

Great! Do you have any advice on writing to a file?

@DanPrince I've added a bit on writing. Can't see anything shorter on that at the moment though.

Depending on the input format, fgetcsv and fscanf can often be byte savers as well.
For example, assume each line of your input consists of two space separated integers. To read these values into an array, you could use one of:
$x=split(' ',fgets(STDIN)); // 27 bytes
$x=fgetcsv(STDIN,0,' ');    // 24 bytes
$x=fscanf(STDIN,'%d%d');    // 24 bytes

Or if you wanted to read each of them into a different variable:
list($a,$b)=split(' ',fgets(STDIN)); // 36 bytes
list($a,$b)=fgetcsv(STDIN,0,' ');    // 33 bytes
fscanf(STDIN,'%d%d',$a,$b);          // 27 bytes

To read non-physical files (read input)
If you have a single line input, use -F and $argn to read from STDIN. This is only 5 bytes and a lot shorter than other methods.
Example: Try it online!
Basically -F runs your code once for every single line of the input and fills $argn with string of that input line. More information: https://www.php.net/manual/en/features.commandline.options.php

If you have a multi line input, use $argv. $argv is an array which starting from index 1 contains all arguments you pass to your code. So you can use $argv[1] and so on, which is only 8 bytes. You can pass multiple arguments too and loop on them with for(;$a=$argv[++$i];) which usually is shorter than other methods.
Example 1: Try it online!
Example 2: Try it online!
More information: https://www.php.net/manual/en/reserved.variables.argv.php


text:
Sort an array with values of integer
There is an array of integer values to be sorted.During the sorting process, the places of two numbers can be interchanged. Each interchange has a cost, which is the sum of the two numbers involved.
You must write a program that determines the minimal cost to sort the sequence of numbers.

First of all please read the faq. Your puzzle should have an objective primary winning criterion. Have a look around to see many well-specified questions. You may also read the comments below your last puzzle as those also address the same questions.

We must? You should change site...

Are the integers equally distributed, or normal distributed, or somehow else? How many of them and how big? Do you have some sample input, something like for i in {1..100}; do echo $((RANDOM%256)); done for example.

They are not equally distrubuted

Scala:
def minimalCostToSortArray (daArray: Array[Int]) = 0

Why is the cost always zero? Because I don't change numbers at all:
def arrsort (a: Array[Int], pos:Int = 0): Array[Int] = {
  if (pos >= a.length -1) a else {
    if (a(pos) > a(pos+1)) {
      val diff = a(pos) - a(pos+1)
      a (pos) -= diff
      a (pos+1) += diff
      arrsort (a)
    } else arrsort (a, pos+1)
  }
}

For the challenge to make sense at all, I'd interpret it as saying that the only operation we're allowed to use to modify the array is swapping two numbers. Still, +1 for thinking outside the box (and -1 for cheating, which leaves the total at ±0).

I read ... the places can be interchanged as optional, but more so, as badly prepared question. I understand my answer more as a criticism on a badly prepared question.


text:
Executable haiku that outputs a haiku
Puzzle:
Write a short, three-line program which:

has 5/7/5 syllables per line when read aloud
outputs a haiku when run.

An example of a program having the correct structure, but non-haiku output, is (Python):
>>> for x in range(3):
...     print "EXTERMINATE HUMANS"
... # I am a Dalek.
...
EXTERMINATE HUMANS
EXTERMINATE HUMANS
EXTERMINATE HUMANS

(The comment is a bit of a cop-out.)
This reads aloud as:

for x in range three
print EXTERMINATE HUMANS!
I am a Dalek.

Any language is acceptable. For the purposes of reading aloud, symbols like !@#$%^&*()_+ can be ignored if you want, or pronounced aloud, admitting something like Waka Waka Bang Splat. (I'm sure there will be a Perl entry like !***(!:, )(*@@@#, )_(*)!.)
Extra points if either the code or the output is especially funny, or especially zen.

Edit: If your language requires boilerplate before it can do anything interesting (#include <iostream>?) then I'm happy to ignore the boilerplate.

I've accepted Paul Richter's Common Lisp haiku on the grounds that it made me laugh for a good five minutes.
Honorable mention for Timwi's creative rule-bending (compiler output?!) and for the extremely memorable line "Static void. I long for you."

Now this question ends;
Many more haikus await.
Continue posting!

I would strongly suggest you prevent the use of cat-like languages...

"Dalek Simulator" is 6 syllables (or maybe "# Dalek Simulator" is 7 syllables ?) - either way, shouldn't it be 5 syllables for the third line ?

@PaulR: You're right. Edited to something that's 5 syllables. ;)

Bonus to a Piet solution?

@ugoren: If you can make a Piet program look like a haiku, I'm pretty sure that would win the Grand Prize. ;)

I though about adding "haiku outputting haiku" to the sandbox, but searched first...

Common Lisp
Parentheses are silent!
Program:
((lambda (&rest foo)
   (list foo (cons 'truly foo) foo))
 'this 'is 'lisp 'haiku)

Read as:
lambda and rest foo
list foo cons truly foo foo
this is lisp haiku

Output:
((THIS IS LISP HAIKU) (TRULY THIS IS LISP HAIKU) (THIS IS LISP HAIKU))

This cracked me up for a good five minutes. Well done!

C#
Program:
#warning Lonesome
class _{
    static void Eye(long forYou='
        ){ /* My program ends here. */ ;}}

Read:
Warning: Lonesome class.
Static void. I long for you.
My program ends here.

Compiler output:
#warning: 'Lonesome'        (read: hash warning lonesome)
Empty character literal     (read: empty character lit’ral)
Newline in constant

Compiler output?! Creative interpretation of the rules - I like it. It's also strangely zen...

This is compiler poetry... +1!

I wish I could upvote this more than once.

@Gareth ditto!!

I literally laughed out loud at the poetry of the compiler's loneliness. Am I sadic?
Newline in constant.

Piet, 867 executing color blocks
Grand Prize, you say?  This has codel size of 2.

Output:
SPRING EVER RETURNS
NEVER EXACTLY THE SAME
THIS IS NOT A QUINE

This challenge was fun!  I've written a Piet instruction encoder that takes instructions and translates them into a Piet script.  It's short work from there to generate code to print a given string.  I put a small (but effective) amount of effort into golfing the Piet code while only using single-codel instructions.
I then made a pixel font.  For every pixel in a character, I blow it up into 4 codels: 2 black, and 2 executed.  The first codel encountered is non-executing, so if a segment of a character has n pixels, for example, that corresponds to 2*n*-1 instructions.
The lines down the sides reverse the direction pointer and move it down by 2 pixels, taking it to the next row.  Thus, instructions are reversed on every other line.
Once I had code to produce "text embedded in text", it gets fun.  I probably wrote 20 haiku along the way, but I eventually settled.  By tweaking the font; adding / removing serifs, rounding corners, changing height / width, etc., I was able to alter the total number of nonwhite pixels in the image such that the Piet code fit exactly into the image text.
Bonus!  You can make your own quinelike haiku!  http://pastebin.com/zxc9V3UX

Is there anywhere online I can test this? If it works it's definitely worth a +1.

I found one here, but the program gave no output :-(

@Gareth, Piet is rather notorious for its lousy editors / interpreters, and I wasn't able to get npiet's online editor to produce output for anything.  The posted script works on PietIDE.

Unfortunately, that one's totally borked in Chrome on my Mac. I'll see if I can download one that works tomorrow.

@Gareth, sad.  There's a interpreter in python that I've also been able to use.  Unfortunately, it doesn't seem to check for termination, so you have to kill it or wait for the 100k step cutoff.

I heard you like haiku, so I put a haiku in your picture of a haiku so you get a haiku when you haiku.

# piet quinelike haiku / this is in public domain/ make war not poems This is GENIUS.

@Boothby: consider sending this to David Morgan-Mar for inclusion in the Piet Hall of Fame.. (I see you already have one entry there. ;) )

already have ;)

Perl
$_
= "Repeating myself"
;print"$_\nis like $_.\n$_.\n";

How to read it out loud:
dollar underscore
equals repeating myself
print nis like line noise.

Output:
Repeating myself
is like Repeating myself.
Repeating myself.

Isn't it a cop out to read the dollar underscore aloud in the first line but then skip it (along with quite a few other characters) on the third line?

Yes, it is really :)

INTERCAL
INTERCAL has limited output capabilities, but "limited capabilities" has never stopped me from writing an INTERCAL program!
DO READ OUT #18
+#3301
+#214
PLEASE GIVE UP

Please read [out] this as:
Do read out eighteen,
Three thousand three hundred one,
Two hundred fourteen.

(Note that my boilerplate is at the end of the program instead of at the beginning.)
The program produces the output:
XVIII

MMMCCCI

CCXIV

Which, when spoken aloud, goes:
Ex vee eye eye eye,
Em em em cee cee cee eye,
Cee cee ex eye vee.

I think you need therapy.

CoffeeScript
With tongue firmly in cheek, I present CoffeeScript:
here = "my haiku"
were_doomed() unless 1 is 1
alert Date.now()

Pronounced:
Here is my haiku
We're doomed unless one is one
alert date dot now

If your timing is right (!), your output might be e.g. 1337181872717, pronounced:
one three three seven
one eight one eight seven two
seven one seven

Considering my first run at this was one microsecond out from a valid haiku response, I think that's zen enough to qualify!
NB: I'd be happy to hear sufficiently zen alternatives for my first two (admittedly weak) lines.

+1 for "if your timing is right" and "one three three seven"

J
Program:
p:i.4
*:*:*:i.3
!8

Read (substituting verb names):
Prime Integers Four
Square Square Square Integers 3
Factorial Eight

Output (read numbers out loud):
2 3 5 7
0 1 256                          (Read: Zero One Two-Fifty-Six)
40320                            (Read: Forty Three-Twenty)

Python
Code:
for _ in range(1,3):
    print 'Hi ' * 5, 'there ' *  2 * (-1+_)
print 'I now', 'go ' * 3

How to read:
for in range one three
print hi five there two one plus
print i now go three

Output:
Hi Hi Hi Hi Hi
Hi Hi Hi Hi Hi  there there
I now go go go

Working sample: http://ideone.com/hDniW

logo
Here's a Haiku procedure that's also a quine procedure (easy because of logo's introspection capability)
to better_yourself
  printout "better_yourself
end ; as you began

Read as

To better yourself
  Print out quote better yourself
  End as you began

I read "Logo" and thought "This is going to involve a turtle writing a Haiku, isn't it?!" +1 even though there was no PEN UP or PEN DOWN. :)

JavaScript (doesn't work in Firefox)
             (function haiku() { with (
console) log ((('' + haiku). // output
replace)     (/[ !-@{-~[-^]+/gim, ' ')); void haiku })()

works except for mozilla
javascript engine and shows
spelling after ran

Ruby
"A ruby haiku.
Why, yes, it is."; print open(
__FILE__).read #this now, please.

Read as:
A ruby haiku.
Why, yes, it is. Print open
file. Read this now, please.

It doesn't flow very well, unfortunately. In my defense, it is 12:50am...

Cheating quine?

Python
(Only read the first level of parentheses (not the second)).
Code and how to read:
for e in range(3):                      # for e in range three
    if True is False: what = then       # if true is false, what is then?
    print "oh " * (5 + 2 * (e & 1))     # print oh times _seven_

Output, probably most basic haiku in the world:
oh oh oh oh oh
oh oh oh oh oh oh oh
oh oh oh oh oh

You could probably just replace True == False with True is False to make the program code more like how you'd read it.

@LegoStormtroopr agreed. Edit: I had forgot about this one. As stupid as the output is, I find it strangely satisfying to read it out loud in my most serious "peotry voice".

At least in Python 3, what = then could also be replaced witn what is then.

Python (2 entries)
Entry 1:  A haiku in time
You need to save this in a file and run it from the same directory. This haiku very slowly prints itself out to screen, a poem in words and time.
from time import sleep
for line in open(__file__):
  print line; sleep(len(line))

Entry 2: A haiku without symbolism
This is similar to the above, but was an attempt to write a Python haiku that used just keywords and minimal brackets or substitutions of symbols (eg. = pronounced as "is").
if __file__ is not None:
 for line in open(__file__):
  print not False and line

Tcl
Here's a self-documenting, self-outputting, example:
catch {me as I make}
proc unknown args {puts [read $args]}
[open [info script]]

Vim
ia0 <esc><c-x>
YpA-<esc>
px5<c-x><c-x>

read as
i a zero x
Y p A hyphen escape
p x five x x

Writes:
a-1
a-1-
-7

read as:
a negative one
a minus one negative
negative seven

Python 3
print(print.__doc__[:15])
print(print.__doc__[13:][:13])
print(print.__doc__[32])

Read as:
print print doc one five
print print doc one three one three
print print doc three two

Prints:
print(value, ..
..., sep=' ',
\

Read as:
print value dot dot
ellipses, sep equals blank
reverse solidus


text:
Build a typing speed test / measuring CPM
The Rules
It's time to build a typing speed test in your language of choice!
1. You provide a file with a dictionary of choice (every 'word' in it must be newline delimited). Pipe it in via stdin or provide it's name as a command line argument.

a
able
about
above
absence
...

2. Pick 10 random words from the file (no duplicates must be allowed) and print them out in the following manner:

-> direct
-> ground
-> next
-> five
...

3. Start measuring the time spent from now on!
4. Let the user type all of the ten words as fast as possible (ended with a carriage return). Print OK when you have a match, print WRONG when we have a typing mistake (or the word was already succesfully typed in this run).
5. Stop the clocks! Now print the CPM (Characters per minute) benchmark, which is calculated as follows: (sum of the characters of the chosen words / time spent typing (seconds)) * 60. Round to the nearest integer and reproduce the following (sample) output:

--> You have scored 344 CPM!

A sample run

-> settle
-> side
-> open
-> minister
-> risk
-> color
-> ship
-> same
-> size
-> sword
settle
OK
side
OK
open
OK
# ...................... some lines snipped ......................
word
WRONG
sword
OK
--> You have scored 298 CPM!

The winner
This is code colf, the shortest entry (in source code character count) wins, have fun!

I think the winner should partly be scored by the person with the highest CPM ;)

How precisely do we need to measure the time? Is one second resolution OK?

@Ilmari Karonen: a one second resolution would be fine for this specific contest.

K, 146
Assumes a dictionary file called 'd' in the current working directory.
{b:+/#:'a:10?_0:`:d;-1"-> ",/:a;s:.z.t;while[#a;$[(,/0:0)~*a;[a:1_a;-1"OK"];-1"WRONG"]];-1"--> You have scored ",($(60000*b)%"i"$.z.t-s)," CPM!";}

Very nice and short, first entry in K I've seen (here on codegolf.se)...

Thanks, all of my answers here are in Q or (increasingly) in K.

I don't quite get why this only got a single upvote (mine)!

Bash - 217 212 199 196 chars
Not gonna win but it was fun
declare -A W
for w in `shuf -n10`;do C+=$w;echo -\> $w;W[$w]=OK;done
SECONDS=0
for((;${#W[*]};));do read r;echo ${W[$r]-WRONG};unset W[$r];done
echo --\> You have scored $((60*${#C}/SECONDS)) CPM!

Under 200 chars now!
Takes wordlist file as an argument
Now takes word list on standard input. Paste it in the terminal and press ^D
Implemented suggestion from manatwork

Not gonna win but it was fun - I think the same when I post my C# solutions :)

You could use the $SECONDS shell variable to simplify calculating the elapsed time.

You can remove 2 more characters: 1) the : in the default value parameter expansion; 2) the $ in front of SECONDS in the arithmetic evaluation. Actually there is another extra character, the newline at the and of file.

Ruby (189 178 171 168)
$><<t=['',d=[*$<.lines].sample(10)]*'-> '
s=Time.now
puts d.delete($stdin.gets)?:OK:'WRONG'while d[0]
puts'--> You have scored %i CPM!'%((t.size-40)/(Time.now-s)*60)

Pretty basic, I'm sure there are improvements to be made.  Takes the filename of the dictionary as a command-line argument.
EDIT: A few minor tweaks, mainly around retaining the newlines from the dictionary.  As a result the file will need a trailing newline to work correctly.

C, 305 309 347 chars
char*stdin,w[11][99];long i,t;main(int n,char**v){v=fopen(v[1],"r");
for(srand(time(&t));fgets(w[i++>9?(n=rand()%i)>10?0:n:i],99,v););
for(i=n=0;i<10;n+=printf("-> %s",w[++i])-4);
for(;i;puts(!strcmp(*w,w[11-i])?--i,"OK":"WRONG"))fgets(*w,99,stdin);
printf("--> You have scored %ld CPM!\n",n*60/(time(0)-t));}

Thanks to @ugoren for the improvement hints. Using an "11th word" to discard incoming dictionary entries was a big win over my previous strcpy-if-chosen approach.
Here's the ungolfed source:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

static char words[11][99];
static long i, t;

int main(int argc, char *argv[])
{
    FILE *fp;
    int n;

    fp = fopen(argv[1], "r");
    srand(time(0));
    for (i = 0 ; fgets(words[0], sizeof words[0], fp) ; ++i) {
        n = i < 10 ? i : rand() % i;
        if (n < 10)
            strcpy(words[n + 1], words[0]);
    }
    fclose(fp);

    n = 0;
    for (i = 1 ; i <= 10 ; ++i)
        n += printf("-> %s", words[i]) - 4;
    t = time(0);
    i = 1;
    while (i <= 10 && fgets(words[0], sizeof words[0], stdin)) {
        if (strcmp(words[0], words[i])) {
            puts("WRONG");
        } else {
            puts("OK");
            ++i;
        }
    }
    if (i > 9)
        printf("-> You have scored %ld CPM!\n", n * 60 / (time(0) - t));

    return argc - argc;
}

Some improvements: 1. K&R declaration: main(n,v)char**v;{.... 2. stdin can be char *. fgets(buf,len,stdin)=gets(buf) (never mind the buffer overruns). 3. What's wrong with rand()%i? RAND_MAX isn't needed. 4. Why long?

Also: 1) t=time(0)->time(&t). 2) n*60/(time(0)-t) has parentheses that must go - *60 can be moved to n+=60*printf, then n/=time(0)-t. 3) Replace b with an extra element in w, replace strcpy with read directly into w.

Replacing fgets() with gets() needs extra code to deal with the newlines in the dictionary; this wound up being shorter. rand()%i isn't sufficient; the actual calculation is (double)i*rand()/RAND_MAX. Moving the *60 to the printf also means changing the the -4 to -240 so it ultimately winds up a loss. Your other points are valid ones, though (I believe). Oh, and long is because time_t is traditionally a long. Just because we're golfing doesn't mean we can't be portable.

I missed 4->240... Portability and golf don't go well together. But defining i,t; (implicitly int) is OK up to MAX_INT seconds (if you don't use time(&t)). With rand(), all you need is a 10/i chance, and rand()%i<10 does it.

Your random selection is somewhat flawed (not that absolute fairness is required). The 11th line should have a 10/11 chance to be selected, but you do rand()%10>10, which gives it 100%. rand()%(i+1)>9 is better (but instead if %(i+1) do i++>9?. Also move *stdin to be first and save a space.

It's already flawed by using rand()%i instead of floating-point -- but you're right, there's a serious bug there. It does need to be >10 though. It's not obvious, but the code is (meant to be) taking advantage of the fact that w[0] is the trashbucket entry, so rand()%11>10 still has a 10/11 chance to be selected. The bug is due to me making logic changes to already-golfed code; fortunately, the fix will actually make it smaller.

You're right about >10. The tricky part is that you can fall in bucket 0 if rand()%i is either >10 or 0. About distribution - any random function which returns a finite representation cant give perfect 11-way distribution. Floating point isn't better than fixed.

Scala(319 306 304 302)
var s=util.Random.shuffle(io.Source.fromFile(args(0)).getLines.toSet)take 10
def?(a:Any)=println(a)
var l=(0/:s){_+_.size}
s map{"-> "+_}map?
def n=System.nanoTime
val t=n
while(s.size!=0){val m=readLine
if(s contains m)?("OK")else?("WRONG");s-=m}
?("--> You have scored "+l*60000000000L/(n-t)+" CPM!")

C# 401
void T(){
Action<string>C=Console.WriteLine;Func<string>R=Console.ReadLine;
var w=new List<string>();
for(var l=R();l!="";l=R())w.Add(l);
var s=w.OrderBy(_=>Guid.NewGuid()).Take(10).ToList();
s.ForEach(x=>C("=> "+x));
var t=s.Select(x=>x.Length).Sum();
var c=Stopwatch.StartNew();
while(s.Any()){C(s.Remove(R())?"OK":"WRONG");}
c.Stop();
C("--> You have scored "+c.Elapsed.TotalSeconds*60/t+" CPM!");}

Running version here: http://ideone.com/Nt6Id

PHP 187 bytes
Newlines have been added for clarity:
<?$s=file($argv[1]);
for(shuffle($s);$i++<10;$l+=strlen($$i))echo~ÒÁß,$$i=$s[$i];
for($t=time();$j++<10;)echo$$j==fgets(STDIN)?OK:WRONG,~õ?>
--> You have scored <?=0|$l/(time()-$t)*60?> CPM!

Accepts the dictionary filename as a command line argument. The dictionary file must end with a newline.

Python (256 235)
import time as t,random as r
def p(x):print x
c=r.sample(input().split("\n"),10)
z=lambda x:p(("WRONG","OK")[raw_input()==x])or len(x)
p("--> "+"\n--> ".join(c))
_=t.time()
p("--> You have scored %d CPM!"%(sum(map(z,c))/(t.time()-_)*60))

This is in python 2.x, in 3.x I can shave off 4 more characters by using the print function.
Newlines included

"Question: Do newlines count?"  We usually go by "necessary characters".  In the case of Python, yes, the newlines need to be counted, since removing them will keep the program from working.

I think you can change z=lambda x: to def z(x):.

@JoeyAdams: I could if only needed to return none, but I need to return len(x) and def z(x):return is 5 more charaters :/

I think you can win some characters by piping in the input (allowed in the question) and using input() instead of sys.argv[1].read()

@JoelCornett: Whoops, you're right.

@ChristopheD: Good idea!

[Wolfram Language (Mathematica)], 212 bytes
n=10;Print["-> "<>#]&/@(w=RandomWord@n);c=1;t=First@AbsoluteTiming[While[c<=n,Print@If[Echo@InputString[]==w[[c]],c++;"OK","WRONG"]]];Print["--> You have scored "<>ToString@⌊60Total@StringLength@w/t⌋<>" CPM!"]

Interesting challenge for WM.
Works only on desktop!
Using internal dictionary of common words instead of file.
Ungolfed version:
num = 10; Print["-> " <> #] & /@ (words = RandomWord@num);
size = Total@StringLength@words;
count = 1;
timing = First@AbsoluteTiming[
    While[count <= num,
     Print[
      If[Echo@InputString[] == words[[count]],
       count++; "OK",
       "WRONG"]
      ]
     ]];
result = ToString@⌊60 size/timing⌋;
Print["--> You have scored " <> result <> " CPM!"]

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Josephus problem (counting out)
The challenge
Write a function that takes two positive integers \$n\$ and \$k\$ as arguments and returns the number of the last person remaining out of \$n\$ after counting out each \$k\$-th person.
This is a code-golf challenge, so the shortest code wins.
The problem
\$n\$ people (numbered from \$1\$ to \$n\$) are standing in a circle and each \$k\$-th is counted out until a single person is remaining (see the corresponding wikipedia article). Determine the number of this last person.
E.g. for \$k=3\$ two people will be skipped and the third will be counted out. I.e. for \$n=7\$ the numbers will be counted out in the order \$3 \, 6 \, 2 \, 7 \, 5 \, 1\$ (in detail \$\require{cancel}1 \, 2 \, \cancel{3} \, 4 \, 5 \, \cancel{6} \, 7 \, 1 \, \cancel{2} \, 4 \, 5 \, \cancel{7} \, 1 \, 4 \, \cancel{5} \, 1 \, 4 \, \cancel{1} \, 4\$) and thus the answer is \$4\$.
Examples
J(7,1) = 7      // people are counted out in order 1 2 3 4 5 6 [7]
J(7,2) = 7      // people are counted out in order 2 4 6 1 5 3 [7]
J(7,3) = 4      // see above
J(7,11) = 1
J(77,8) = 1
J(123,12) = 21

GolfScript, 17 bytes
{{@+\)%}+\,*)}:f;

Takes n k on the stack, and leaves the result on the stack.
Dissection
This uses the recurrence g(n,k) = (g(n-1,k) + k) % n with g(1, k) = 0 (as described in the Wikipedia article) with the recursion replaced by a fold.
{          # Function declaration
           # Stack: n k
  {        # Stack: g(i-1,k) i-1 k
    @+\)%  # Stack: g(i,k)
  }+       # Add, giving stack: n {k block}
  \,*      # Fold {k block} over [0 1 ... n-1]
  )        # Increment to move from 0-based to 1-based indexing
}:f;

Can you add an explanation, please?

@Sherlock9, I managed to figure out what I was doing despite almost 3.5 years having passed. Who says that GolfScript is read-only? ;)

Ahem. s/read/write/

Sorry. I've only started learning Golfscript two or three days ago and I every time I read your code, I kept thinking I'd missed something. ... Ok, I'm still missing something, how does folding {k block} over [0..n-1] get you g(0,k) 0 k to start with? Sorry, if I'm posting these questions in the wrong place.

@Sherlock9, fold works pairwise, so the first thing it does is evaluate 0 1 block. Very conveniently, that happens to be g(1, k) (2-1) block. So it's starting at g(1,k) 1 rather than g(0,k) 0. Then after executing the block, it pushes the next item from the array (2) and executes the block again, etc.

OH! Ok that makes sense. Thanks @Peter Taylor

Minsky Register Machine (25 non-halt states)
Not technically a function, but it's in a computing paradigm which doesn't have functions per se...
This is a slight variation on the main test case of my first MRM interpretation challenge:

Input in registers n and k; output in register r; it is assumed that r=i=t=0 on entry. The first two halt instructions are error cases.

I think you have to adjust your machine slightly. If I read it correctly the output is zero-indexed, isn't it?

I was thinking the other way: if k=1 then r=0. Hmm, I have to think about this one again...

As I read your diagram, i is simply counting from 2 to n while r is the register which accumulates the result.

@Howard, I looked up the comments I made when I first wrote this and you're right. Whoops. Now corrected (I believe - will test more thoroughly later).

Python, 36
I also used the formula from wikipedia:
J=lambda n,k:n<2or(J(n-1,k)+k-1)%n+1

Examples:
>>> J(7,3)
4
>>> J(77,8)
1
>>> J(123,12)
21

Mathematica, 38 36 bytes
Same Wikipedia formula:
1~f~_=1
n_~f~k_:=Mod[f[n-1,k]+k,n,1]

If[#<2,1,Mod[#0[#-1,#2]+#2,#,1]]&

C, 40 chars
This is pretty much just the formula that the above-linked wikipedia article gives:
j(n,k){return n>1?(j(n-1,k)+k-1)%n+1:1;}

For variety, here's an implementation that actually runs the simulation (99 chars):
j(n,k,c,i,r){char o[999];memset(o,1,n);for(c=k,i=0;r;++i)(c-=o[i%=n])||(o[i]=!r--,c=k);
return i;}

Save a character: j(n,k){return--n?(j(n,k)+k-1)%-~n+1:1;}.

dc, 27 bytes
[d1-d1<glk+r%1+]dsg?1-skrxp

Uses the recurrence from the Wikipedia article. Explanation:
# comment shows what is on the stack and any other effect the instructions have
[   # n
d   # n, n
1-  # n-1, n
d   # n-1, n-1, n
1<g # g(n-1), n ; g is executed only if n > 1, conveniently g(1) = 1
lk+ # g(n-1)+(k-1), n; remember, k register holds k-1
r%  # g(n-1)+(k-1) mod n
1+  # (g(n-1)+(k-1) mod n)+1
]
dsg # code for g; code also stored in g
?   # read user input => k, n, code for g
1-  # k-1, n, code for g
sk  # n, code for g; k-1 stored in register k
r   # code for g, n
x   # g(n)
p   # prints g(n)

J, 45 characters
j=.[:{.@{:]([:}.]|.~<:@[|~#@])^:(<:@#)>:@i.@[

Runs the simulation.
Alternatively, using the formula (31 characters):
j=.1:`(1+[|1-~]+<:@[$:])@.(1<[)

I hope Howard doesn't mind that I've adjusted the input format slightly to suit a dyadic verb in J.
Usage:
   7 j 3
4
   123 j 12
21

GolfScript, 32 24 bytes
:k;0:^;(,{))^k+\%:^;}/^)

Usage:
Expects the two parameters n and k to be in the stack and leaves the output value.
(thanks to Peter Taylor for suggesting an iterative approach and many other tips)
The old (recursive) approach of 32 chars:
{1$1>{1$(1$^1$(+2$%)}1if@@;;}:^;

This is my first GolfScript, so please let me know your criticisms.

1- has special opcode (. Similarly 1+ is ). You don't have to use alphabetic characters for storage, so you could use e.g. ^ instead of J and not need a space after it. You have far more $s than are usual in a well-golfed program: consider whether you can reduce them using some combination of \@..

@PeterTaylor Thanks a lot for these great tips! It's pretty hard to grasp all the Golfscript operators and I overlooked these two very straightforward one. Only by applying the first two suggestions I manage to shorten the code by 5 chars. I'll also try to remove the $ references.

Also, recursion isn't really GolfScript's thing. Try flipping it round and doing a loop. I can get it down to 19 chars (albeit untested code) that way. Hint: unroll the function g from the Wikipedia article, and use , and /.

Actually, make that 21. I forgot to pop k at the end.

@Peter Taylor: Actually, you can build a 19 chars solution (not using each but fold).

@Howard, cunning. Nice one.

@PeterTaylor Thanks, the iterative solution is much better than the recursive one in GS. I'm still thinking of ways to get this shorter.

{,{\2$+\)%}*)\;}:f; Make sure you understand why it works ;)

One final trick: rather than using 2 characters to access k inside the loop and then 2 more to discard it at the end, we can pull it inside using + to get down to 17 characters: {{@+\)%}+\,*)}:f; I doubt that can be improved.

@PeterTaylor These things are a work of art. I really liked the second example that adds the 3 and the code block together to make a code block that uses the 3.

In the 19 chars I think there should be a \\ at the beginning (it seems to expect the parameters in the opposite order).

One more thing: isn't is OK for the purpose of this site to leave out the function wrapper? For example, I think {@+\)%}+\,*) might be acceptable (the usage being that it expects two params in the stack and leaves the result at the end)

Yes. As I said: untested code. I've tested the 17-char one, though, because I thought it up on the way home from work. In general, when the question asks for a function, give a function; when it asks for a program, give a program; and when it doesn't specify, pick whatever's in your favour but state what you picked.

@PeterTaylor If you want to post your solution as answer I'd accept it as the currently shortest one.

Groovy, 36 bytes
def j(n,k){n>1?(j(n-1,k)+k-1)%n+1:1}

R, 48
J=function(n,k)ifelse(n<2,1,(J(n-1,k)+k-1)%%n+1)

Running Version with examples: http://ideone.com/i7wae

Scala, 53 bytes
def?(n:Int,k:Int):Int=if(n<2)1 else(?(n-1,k)+k-1)%n+1

Haskell, 68
j n=q$cycle[0..n]
q l@(i:h:_)k|h/=i=q(drop(k-1)$filter(/=i)l)k|1>0=i

Does the actual simulation. Demonstration:

GHCi> j 7 1
  7
  GHCi> j 7 2
  7
  GHCi> j 7 3
  4
  GHCi> j 7 11
  1
  GHCi> j 77 8
  1
  GHCi> j 123 12
  21

Ruby, 39 bytes
def J(n,k)
n<2?1:(J(n-1,k)+k-1)%n+1
end

Running version with test cases: http://ideone.com/pXOUc

C, 88 chars
Does the simulation, doesn't calculate the formula.
Much longer than the formula, but shorter than the other C simulation.
j(n,k){
    int i=0,c=k,r=n,*p=calloc(n,8);
    for(;p[i=i%n+1]||--c?1:--r?p[i]=c=k:0;);
    return i;
}

Notes:
1. Allocates memory and never releases.
2. Allocates n*8 instead of n*4, because I use p[n]. Could allocate (n+1)*4, but it's more characters.

Q, 34 bytes
f:{$[x=1;1;1+mod[;x]f[x-1;y]+y-1]}

Usage:
q)f .'(7 1;7 2;7 3;7 11;77 8;123 12)
7 7 4 1 1 21

Ruby, 34 bytes
J=->n,k{n<2?1:(J(n-1,k)+k-1)%n+1}

C++, 166 bytes

Golfed:
#include<iostream>
#include <list>
int j(int n,int k){if(n>1){return(j(n-1,k)+k-1)%n+1;}else{return 1;}}
int main(){intn,k;std::cin>>n>>k;std::cout<<j(n,k);return 0;}

Ungolfed:
#include<iostream>
#include <list>
int j(int n,int k){
    if (n > 1){
        return (j(n-1,k)+k-1)%n+1;
    } else {
        return 1;
    }
}
int main()
{
    int n, k;
    std::cin>>n>>k;
    std::cout<<j(n,k);
    return 0;
}

You could save bytes on the J function, by using the ternary operator.

intn in your golfed version won't compile

you can remove space in #include <list>

Powershell, 56 bytes
param($n,$k)if($n-lt2){1}else{((.\f($n-1)$k)+$k-1)%$n+1}

Important! The script calls itself recursively. So save the script as f.ps1 file in the current directory. Also you can call a script block variable instead script file (see the test script below). That calls has same length.
Test script:
$f = {

param($n,$k)if($n-lt2){1}else{((&$f($n-1)$k)+$k-1)%$n+1}

}

@(
    ,(7, 1, 7)
    ,(7, 2, 7)
    ,(7, 3, 4)
    ,(7, 11, 1)
    ,(77, 8, 1)
    ,(123,12, 21)
) | % {
    $n,$k,$expected = $_
    $result = &$f $n $k
    "$($result-eq$expected): $result"
}

Output:
True: 7
True: 7
True: 4
True: 1
True: 1
True: 21

Nibbles, 6 bytes
+~/\,@0%+_@

Attempt This Online!
Uses the formula as described on Wikipedia:
\$J(n,k) = g(n,k) + 1\$, where
$$\begin{align}g(1,k) &= 0 \\ g(n,k) &= (g(n-1,k)+k) \bmod n\end{align}$$
+~/\,@0%+_@
+~          Add 1
  /          fold right
   \          reverse
    ,          range from 1 to
     @          n
      0       with initial value 0
       %      modulo
        +      add
         _      k
          @     accumutalor
               item

Haskell, 29
Using the formula from wikipedia.
1#_=1
n#k=mod((n-1)#k+k-1)n+1

JavaScript (ECMAScript 5), 48 bytes
Using ECMAScript 5 since that was the latest version of JavaScript at the time this question was asked.
function f(a,b){return a<2?1:(f(a-1,b)+b-1)%a+1}

ES6 version (non-competing), 33 bytes
f=(a,b)=>a<2?1:(f(a-1,b)+b-1)%a+1

Explanation
Not much to say here. I'm just implementing the function the Wikipedia article gives me.

05AB1E, 11 bytes
L[Dg#²<FÀ}¦

Try it online!
L           # Range 1 .. n
 [Dg#       # Until the array has a length of 1:
     ²<F }  #   k - 1 times do:
        À   #     Rotate the array
          ¦ #   remove the first element

8th, 82 bytes
Code
: j >r >r a:new ( a:push ) 1 r> loop ( r@ n:+ swap n:mod ) 0 a:reduce n:1+ rdrop ;

SED (Stack Effect Diagram) is: n k -- m
Usage and explanation
The algorithm uses an array of integers like this: if people value is 5 then the array will be [1,2,3,4,5]
: j \ n k -- m
    >r                               \ save k
    >r a:new ( a:push ) 1 r> loop    \ make array[1:n]
    ( r@ n:+ swap n:mod ) 0 a:reduce \ translation of recursive formula with folding using an array with values ranging from 1 to n
    n:1+                             \ increment to move from 0-based to 1-based indexing
    rdrop                            \ clean r-stack
;

ok> 7 1 j . cr
7
ok> 7 2 j . cr
7
ok> 7 3 j . cr
4
ok> 7 11 j . cr
1
ok> 77 8 j . cr
1
ok> 123 12 j . cr
21

J, 24 bytes
1+1{1([:|/\+)/@,.1|.!.0#

Try it online!
An iterative approach based on the dynamic programming solution.
Explanation
1+1{1([:|/\+)/@,.1|.!.0#  Input: n (LHS), k (RHS)
                       #  Make n copies of k
                 1|.!.0   Shift left by 1 and fill with zero
    1          ,.         Interleave with 1
             /@           Reduce using
           +                Addition
        |/\                 Cumulative reduce using modulo
  1{                      Select value at index 1
1+                        Add 1

J, 19 bytes
1+(}:@|.^:({:@])i.)

Try it online!
How it works
1+(}:@|.^:({:@])i.)   Left: k, Right: n
                i.    Generate [0..n-1]
        ^:            Repeat:
   }:@|.                Rotate left k items, and remove the last item
          ({:@])        n-1 (tail of [0..n-1]) times
1+                    Add one to make the result one-based

Dart, 33 bytes
f(n,k)=>n<2?1:(f(n-1,k)+k-1)%n+1;

Try it online!

Japt, 15 bytes
_é1-V Å}h[Uõ] Ì

Try it online!
A byte could be saved by 0-indexing k, but it isn't actually an index so I decided against that.
Explanation:
         [Uõ]      :Starting with the array [1...n]
_      }h          :Repeat n-1 times:
 é1-V              : Rotate the array right 1-k times (i.e. rotate left k-1 times)
      Å            : Remove the new first element
              Ì    :Get the last value remaining

Japt -h, 10 bytes
õ
£=éVn1¹v

Try it

Husk, 11 8 bytes
Ωεȯtṙ←⁰ḣ

Try it online!
Algorithm from Kamil Drakari's answer.

APL (Dyalog Unicode), 17 bytes
{¯1↓⍺⌽⍵}⍣{1=≢⍺}∘⍳

Try it online!
Takes input as k  f  n.
Explanation
{¯1↓⍺⌽⍵}⍣{2=≢⍵}∘⍳
               ∘⍳ list from 1..n
        ⍣         (f⍣g) → apply f repeatedly till g is true
{¯1↓⍺⌽⍵}          f: rotate list through k elements, drop last
         {1=≢⍺}   g: is the length = 1, for the previous iteration?

APL (Dyalog Unicode), 36 bytes
1+{⍺>1:⍺|⍵+⍵∇⍨⍺-1⋄0}

Try it online!
Recursive function.

Jelly, 7 bytes
RṙṖ¥ƬṖṪ

Try it online!
How it works
RṙṖ¥ƬṖṪ - Main link. Takes n on the left and k on the right
R       - Range; Yield [1, 2, ..., n]
   ¥Ƭ   - Do the following to a fixed point and collect intermediate steps:
 ṙ      -   Rotate k steps to the left
  Ṗ     -   Remove the last element
     Ṗ  - Remove the empty list (the fixed point)
      Ṫ - Return the single element left over


text:
Create a User-Profile Mini-Game
Yesterday, I stumbled on a very clever thing.

Yes, that's a working implementation of Tic-Tac-Toe on a user profile page, from @minitech.  Of course, the moment I saw it, I had to reverse engineer his idea and one-up him :P

Here's my own example embedded directly in the post.  It's a tad buggy due to a couple of implementation details I haven't worked out a good solution for.  Sometimes after you click a peg, it doesn't update properly until another page refresh:
Towers of Hanoi

Reset
Can you do better?

Create a working game in your posted answer (or your user profile page).  This is done via appropriately configuring a webserver you own (or writing a program that acts as a webserver), and embedding content from it in a post, using the referer to determine what commands the user is giving to the game.
Coolest idea (most votes) wins the competition, by Canada Day (Sunday, July 1, 2012 @ 11:59 PM EST)
In the event of a tie, the older answer wins.

+1 Simple, but brilliant idea! BTW - for the deadline I think you mean June 2, 2012.

Short deadline + already answered your own question = downvote.

@boothby: I was actually thinking about deleting my answer.  The intention was to provide a concrete example, not to win the contest (or votes, I don't greatly care about rep).  Can you provide some constructive suggestions to the competition?  What would you like the deadline to be?  How should the spec be changed to motivate you to participate?

I just noticed that minitech's AI can't play a perfect game of tic-tac-toe. Play center, bottom-left, top-center, center-right, center-left.

@mellamokb, the later you make the deadline (within reason), the more answers and more variety you'll get.  I'd say set it for Canada Day.

@boothby, There was just a recent SE blogpost reminding people that they are encouraged to answer their own questions.

@breadbox: That was probably more relevant for SO than here.  I agree with boothby that my posting an answer could be seen as an unfair way to win/get votes, so I removed it and placed my example inside the question instead.

@boothby: No I agree, I'll extend it out some more.  I didn't want to make the contest too long, but I think end of June is fine.  I'll update.

Maybe I'm being stupid, but none of these work for me (Chrome 19.0.1084.46 beta-m)

I'm on Chrome 19.0.1084.52 and have no issue.  What are you seeing?

Neither example works in Firefox 12 on Windows 7.  What are the browser requirements?

@Mr.Wizard: working fine on FF 12.0 & Windows 7 here, could you post more details about what's not working?

@Mr.Wizard: If you look at some of the examples below, they should all work because they have a single image.  As I mention in my post, since I have 4 images, there are flukey things that happen, where it doesn't appear to work but it actually has.  My updates are applied specifically when the image with text (first image) is loaded.  If that image is loaded last due to how the browser loads the images, it will appear that nothing has happened, but the state of the game actually has changed if you reload the page (i.e., click the question title to reload) or click another peg.

You might have to allow 3rd party cookies to get Hangman and Maze working (my game should work fine without it; I recommend blocking them again afterwards for privacy reasons). ChristopheD's and my game also need a browser that allows svg in img tags

@copy: I switched to PNG output for compatibility purposes, and the 3rd party cookie (which was really only a problem with IE with most browser's default settings) should be solved now as well afaik.

@ChristopheD I think P3P policies only work for IE and Safari. I can't play Maze or Hangman without changing my settings at least (Chromium 17)

Yeah, this was randomly thrown together. Chess coming up next, guys! Also, nice job on the towers of Hanoi. It looks better.

@minitech: I especially liked your secret message in TTT if you try to hack :P

Conway's Game of Life

+1 generation -
+5 generations -
zoom in -
zoom out
Load pattern:
random -
glider -
gunstar -
snail -
lwss -
lightspeedoscillator1 -
tumbler
Used Python and SVG output. I have tried using single pixels at first (so you could toggle single cells), but it did not work out, because the browser does not load images in order. Also, much bigger patterns are possible like this without crashing my webserver.
Update:
I had some fun with python and added several features and improvements:

Added HUD with population count, zoom and name
Patterns in the rle format can now be loaded (long list, via) using the pattern parameter (e.g. ?pattern=glider). The filesize is limited to 1.5kB
Can forward n generations, limited to 5 at a time, using the next parameter
Slightly improved algorithm. It's not really fast though, I want this to stay simple
It also works standalone now (uses either referer or its own query string):
https://copy.sh/fcgi-bin/life2.py?pattern=gosperglidergun

sessions = {}

WIDTH = 130
HEIGHT = 130
RULE = (3,), (2, 3)

def read_pattern(filename, offset_x, offset_y):

    filename = PATH + filename + '.rle.gz'

    try:
        if os.stat(filename).st_size > 1500:
            return ['pattern too big', set()]
    except OSError as e:
        return ['could not find pattern', set()]

    file = gzip.open(filename)

    x, y = offset_x, offset_y
    name = ''
    pattern_string = ''
    field = []

    for line in file:
        if line[0:2] == '#N':
            name = line[2:-1]
        elif line[0] != '#' and line[0] != 'x':
            pattern_string += line[:-1]

    for count, chr in re.findall('(\d*)(b|o|\$|!)', pattern_string):
        count = int(count) if count else 1

        if chr == 'o':
            for i in range(x, x + count):
                field.append( (i, y) )
            x += count
        elif chr == 'b':
            x += count
        elif chr == '$':
            y += count
            x = offset_x
        elif chr == '!':
            break

    file.close()

    return [name, set(field)]

def next_generation(field, n):

    for _ in range(n):

        map = {}

        for (x, y) in field:
            for (i, j) in ( (x-1, y-1), (x, y-1), (x+1, y-1), (x-1, y), (x+1, y), (x-1, y+1), (x, y+1), (x+1, y+1) ):
                map[i, j] = map[i, j] + 1 if (i, j) in map else 1

        field = [
            (x, y)
            for x in range(0, WIDTH)
            for y in range(0, HEIGHT)
            if (x, y) in map
            if ( (map[x, y] in RULE[1]) if (x, y) in field else (map[x, y] in RULE[0]) )
        ]

    return field

def life(env, start):

    if 'REMOTE_ADDR' in env:
        client_ip = env['REMOTE_ADDR']
    else:
        client_ip = '0'

    if not client_ip in sessions:
        sessions[client_ip] = read_pattern('trueperiod22gun', 10, 10) + [2]

    session = sessions[client_ip]

    if 'HTTP_REFERER' in env:
        query = urlparse.parse_qs(urlparse.urlparse(env['HTTP_REFERER']).query, True)
    elif 'QUERY_STRING' in env:
        query = urlparse.parse_qs(env['QUERY_STRING'], True)
    else:
        query = None

    timing = time.time()

    if query:
        if 'next' in query:
            try:
                count = min(5, int(query['next'][0]))
            except ValueError as e:
                count = 1
            session[1] = set( next_generation(session[1], count) )
        elif 'random' in query:
            session[0:2] = 'random', set([ (random.randint(0, WIDTH), random.randint(0, HEIGHT)) for _ in range(800) ])
        elif 'pattern' in query:
            filename = query['pattern'][0]
            if filename.isalnum():
                session[0:2] = read_pattern(filename, 10, 10)
        elif 'zoomin' in query:
            session[2] += 1
        elif 'zoomout' in query and session[2] > 1:
            session[2] -= 1

    timing = time.time() - timing

    start('200 Here you go', [
        ('Content-Type', 'image/svg+xml'),
        ('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'),
        ('Expires', 'Tue, 01 Jan 2000 12:12:12 GMT')
    ])

    pattern_name, field, zoom = session

    yield '<?xml version="1.0" encoding="UTF-8"?>'
    yield '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'
    yield '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="full" width="400px" height="200px">'
    yield '<!-- finished in %f -->' % timing
    yield '<text x="0" y="10" style="font-size:10px">Population: %d</text>' % len(field)
    yield '<text x="100" y="10" style="font-size:10px">Zoom: %d</text>' % zoom
    yield '<text x="180" y="10" style="font-size:10px; font-weight:700">%s</text>' % pattern_name
    yield '<line x1="0" y1="15" x2="666" y2="15" style="stroke:#000; stroke-width:1px" />'

    for (x, y) in field:
        yield '<rect x="%d" y="%d" width="%d" height="%d"/>' % (zoom * x, zoom * y + 20, zoom, zoom)

    yield '</svg>'

from flup.server.fcgi import WSGIServer
import random
import re
import gzip
import os
import urlparse
import time

WSGIServer(life).run()

You can take my code as a template for further python fastcgi submissions.

+1 Awesome!  One suggestion: append #5946 to your links, and it will jump back to your post after every update.

hmm.. at least it worked when i tried it.. ah. because in Towers of Hanoi you're always clicking on different pegs.  hmm

@mellamokb it works, but you can't click the same link twice now

Ya, I just realized that lol.  Guess you can provide a disclaimer that when doing next generation, just press F5 for future iterations instead of clicking the next link again and again after the first time.

Regarding browser does not load images in order, that's the implementation detail that is troubling me.  I'm thinking there needs to be a way to have the first image requested (which ever one it is) do all the session updates, and the rest of the images just load.  But it's difficult to track this on the server side, especially if the requests look identical.

It would be really awesome if someone could make this a dynamically-rendered animated GIF.

Accepted your answer as it has the most votes.  Although to be fair, that's probably partly because yours was the oldest answer :)

@mellamokb thanks. In my opinion you don't really need to accept answers on this platform, because it looks as if the challenge is closed

C# - Stack Exchange Hangman
Guess names of Stack Exchange websites in this Hangman game:

(source: apphb.com)

`A`
`B`
`C`
`D`
`E`
`F`
`G`
`H`
`I`
`J`
`K`
`L`
`M`
`N`
`O`
`P`
`Q`
`R`
`S`
`T`
`U`
`V`
`W`
`X`
`Y`
`Z`

`New game`

This was done using ASP.NET MVC 3.0. Here's the code of the Controller that does the trick:
public class HangmanController : Controller
{
    public ActionResult Index()
    {
        var game = Session["hangman"] as HangmanGame ?? HangmanGame.New();

        game = ExecuteGameCommand(game);

        Session["hangman"] = game;

        var imageRenderer = new HangmanImageRenderer(game);
        return new ImageResult(imageRenderer.Render());
    }

    private HangmanGame ExecuteGameCommand(HangmanGame game)
    {
        var referrerQuery = Request.UrlReferrer != null ? Request.UrlReferrer.Query : string.Empty;

        if (referrerQuery.Contains("_new_hangman_"))
            return HangmanGame.New();

        if(game.IsOver())
            return game;

        var chosenLetter = HangmanGame.ValidLetters
            .FirstOrDefault(letter => referrerQuery.Contains(String.Format("_hangman_{0}_", letter)));

        if (chosenLetter != default(char))
            game.RegisterGuess(chosenLetter);

        return game;
    }
}

Other than this code, there are three more classes that I haven't included since they are pretty long and straightforward:

HangmanGame - here's where the game business rules are implemented
HangmanImageRenderer - the class that encapsulates all the GDI ugliness
ImageResult - a custom ActionResult that is used to return a dynamically generated image

The entire code listing is available at http://pastebin.com/ccwZLknX

+1 Wow, you guys are awesome :).  Like the ideas so far!

Cool, never heard of appharbor.com.  Are you really paying to host your answer?

@mellamokb no, I'm using the Appharbor's free hosting plan. If this gets clicked a lot I guess I'll have to pay though... :)

I was going to mention if necessary, I can provide custom subdomain hosting and FTP access to my hosting site.

@mellamokb thanks, but I think this hosting will do. I was just joking about many clicks. :)

You could add the following header to make your solution work in IE (with default Medium Privacy settings, won't accept cookies from your image otherwise): P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"

@ChristopheD Wow, I wasn't even aware that this does not work on IE. Thanks a lot, I made the modification you suggested and it works fine now (at least in IE9)

Clojoban! [WIP]
I wanted to make a bigger game out of this to learn Clojure, so this took a while to pull off (and got pretty big.) I've had a lot of fun doing it, btw!

Restart levelNew game
. . ↑
←
→ -
No-op*
. . ↓
*(click here if game becomes unresponsive)
Instructions
You are Robby , a hard-working robot. You work at a FlipCo Industries as a heavy load carrier. Your job is to move each box  to a goal  spending as few steps as possible. FlipCo's facilities are DANGEROUS. There are lots of challenges and special places to discover.
If you get stuck, click Restart level (but your step count won't be reset!)

You can also play at Clojoban's front page (although it kind of ruins the purpose of the challenge.) It fixes the infamous anchor problem, doesn't require cross-site cookies and you can play with your keyboard arrow keys! You can also play at my user profile page without the annoying anchor problem.
In Firefox the image doesn't flicker while it's loading so it's a bit more comfortable to play.
This game is FAR from completion, Clojoban is still a work in progress. You can see the complete sourcecode at Clojoban's GitHub project page. There's some info in the README about contributing. I need levels too! See the level format at the example levels. You can peek at Clojoban's issue tracker and see what's coming next!

Now your reputation is 11 :)

@mellamokb thanks! Game is embedded now :)

Apparently this didn't get much attention. Any tips for improving?

Your answer is good, I think this question overall has stagnated.  I haven't seen much activity or votes for the last couple of days.

That's a great game! I think you should make a standalone version; I got to the third level and got rid of pressing the No-op button. :) Anyway, great work!

@w0lf there's a standalone version at Clojoban's front page. You can even use your arrow keys to move there, which makes the game far more playable :)

@ÁlvaroCuesta Just finished it. Excellent! The ice is a great twist to the classic Sokoban. This would also be great for a mobile phone game :)

How did you get the game working in your SO -profile? The game is in image -element and then with POST -request played? I tried already the labyrithm but did not get it working in the profile :(

It appears this game has stopped working :(

@hhh look at the address bar! The SO-side querystring is read in the referer header. Persistence is handled game-side with sessions.

@mellamokbtheWise apparently it fixed itself.

You want a good level? Take a look at these: http://nethackwiki.com/wiki/Sokoban they do have too many boxes though.

Maze

(source: t15.org)

New
←
↑
↓
→ -
Noop button

I started from the PHP maze generator I found here: http://dev.horemag.net/2008/03/01/php-maze-generation-class/.
EDIT: changed the output to PNG instead of SVG (for better cross browser compatibility).
EDIT 2: added a header for fixing IE cookie compatibility. Should now work correctly in all major browsers.
The image does not refresh if you take the same direction twice (due to the anchor links). Press F5 the second time, or play the maze on my stackoverflow profile.
EDIT 3: Added a no-op button for easily being able to take the same direction twice (see comments below).
<?php
// based upon the maze generator by Evgeni Vasilev (PHP Adaptation)
// see http://dev.horemag.net/2008/03/01/php-maze-generation-class/
class Maze
{
  var $maze = array();
  var $mx = 0;
  var $my = 0;
  var $xplayer = 1;
  var $yplayer = 1;

  function Maze($mx, $my)
  {
    $mx +=2;
    $my +=2;
    $this->mx = $mx;
    $this->my = $my;
    $dx = array( 0, 0, -1, 1 );
    $dy = array( -1, 1, 0, 0 );
    $todo = array();
    $todonum = 0;

    for ($x = 0; $x < $mx; ++$x){
      for ($y = 0; $y < $my; ++$y){
        if ($x == 0 || $x == $mx-1 || $y == 0 || $y == $my-1) {
          $this->maze[$x][$y] = 32;
        } else {
          $this->maze[$x][$y] = 63;
        }
      }
    }
    $x = rand(1, $mx-2); $y = rand(1, $my-2);
    $x = 1; $y = 1;
    $this->maze[$x][$y] &= ~48;
    for ($d = 0; $d < 4; ++$d){
      if (($this->maze[$x + $dx[$d]][$y + $dy[$d]] & 16) != 0) {
        $todo[$todonum++] = (($x + $dx[$d]) << 16) | ($y + $dy[$d]);
        $this->maze[$x + $dx[$d]][$y + $dy[$d]] &= ~16;
      }
    }

    while ($todonum > 0) {
      $n = rand(0, $todonum-1);
      $x = $todo[$n] >> 16;
      $y = $todo[$n] & 65535;
      $todo[$n] = $todo[--$todonum];
      do {
        $d = rand(0, 3);
      } while (($this->maze[$x + $dx[$d]][$y + $dy[$d]] & 32) != 0);
      $this->maze[$x][$y] &= ~((1 << $d) | 32);
      $this->maze[$x + $dx[$d]][$y + $dy[$d]] &= ~(1 << ($d ^ 1));
      for ($d = 0; $d < 4; ++$d){
        if (($this->maze[$x + $dx[$d]][$y + $dy[$d]] & 16) != 0) {
          $todo[$todonum++] = (($x + $dx[$d]) << 16) | ($y + $dy[$d]);
          $this->maze[$x + $dx[$d]][$y + $dy[$d]] &= ~16;
        }
      }
    }
    $this->maze[1][1] &= ~1;
    $this->maze[$mx-2][$my-2] &= ~2;
  }

  function _drawLine($img,$color, $x1, $y1, $x2, $y2)
  {
    imageline($img, $x1, $y1, $x2, $y2, $color);
  }

  function _drawPlayer($img, $x, $y, $r, $colorborder, $colorfill)
  {
    imagefilledellipse($img, $x, $y, $r, $r, $colorfill);
    imageellipse($img, $x, $y, $r, $r, $colorborder);
  }

  function _drawWin($img, $color)
  {
    imagestring($img, 5, 170, 90, "YOU WIN!", $color);
  }

  function movePlayerDown()
  {
    if ($this->yplayer+1 < $this->my-1 && ($this->maze[$this->xplayer][$this->yplayer] & 2) == 0)
    $this->yplayer++;
  }

  function movePlayerUp()
  {
    if ($this->yplayer-1 > 0 && ($this->maze[$this->xplayer][$this->yplayer] & 1) == 0)
      $this->yplayer--;
  }

  function movePlayerRight()
  {
    if ($this->xplayer+1 < $this->mx-1 && ($this->maze[$this->xplayer][$this->yplayer] & 8) == 0)
      $this->xplayer++;
  }

  function movePlayerLeft()
  {
    if ($this->xplayer-1 > 0 && ($this->maze[$this->xplayer][$this->yplayer] & 4) == 0)
      $this->xplayer--;
  }

  function renderImage($xs, $ys)
  {
    $off = 0;
    $w = ($this->mx*$xs)+($off*2); $h = ($this->my*$ys)+($off*2);
    $img = imagecreatetruecolor($w, $h);
    imagesetthickness($img, 2);
    $fg = imagecolorallocate($img, 0, 0, 0);
    $bg = imagecolorallocate($img, 248, 248, 248);
    $red = imagecolorallocate($img, 255, 0, 0);
    imagefill($img, 0, 0, $bg);
    if (($this->xplayer == $this->mx-2) && ($this->yplayer == $this->my-2)) {
      $this->_drawWin($img, $red);
      return $img;
    }

    for ($y = 1; $y < $this->my-1; ++$y) {
      for ($x = 1; $x < $this->mx-1; ++$x){
        if (($this->maze[$x][$y] & 1) != 0)
          $this->_drawLine ($img, $fg, $x * $xs + $off, $y * $ys + $off, $x * $xs + $xs + $off, $y * $ys + $off);
        if (($this->maze[$x][$y] & 2) != 0)
          $this->_drawLine ($img, $fg, $x * $xs + $off, $y * $ys + $ys + $off, $x * $xs + $xs + $off, $y * $ys + $ys + $off);
        if (($this->maze[$x][$y] & 4) != 0)
          $this->_drawLine ($img, $fg, $x * $xs + $off, $y * $ys + $off, $x * $xs + $off, $y * $ys + $ys + $off);
        if (($this->maze[$x][$y] & 8) != 0)
          $this->_drawLine ($img, $fg, $x * $xs + $xs + $off, $y * $ys + $off, $x * $xs + $xs + $off, $y * $ys + $ys + $off);
        if ($x == $this->xplayer && $y == $this->yplayer) {
          $this->_drawPlayer ($img, $x * $xs + ($xs/2), $y * $ys + ($ys/2), 14, $fg, $red);
        }
      }
    }
    return $img;
  }
}
header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
session_start();
$orig_url = $_SERVER['HTTP_REFERER'];
if (!isset($_SESSION['maze']) || strpos($orig_url, 'resetmaze')){
    $_SESSION['maze'] = new Maze(25,10);
}
$maze = $_SESSION['maze'];
if (strpos($orig_url, 'playerdown')) { $maze->movePlayerDown(); }
if (strpos($orig_url, 'playerup')) { $maze->movePlayerUp(); }
if (strpos($orig_url, 'playerright')) { $maze->movePlayerRight(); }
if (strpos($orig_url, 'playerleft')) { $maze->movePlayerLeft(); }
$img = $maze->renderImage(16,16);
header("Content-Type: image/png");
imagepng($img);
imagedestroy($img);
?>

+1 Nice! for a better experience, add #answer-6171 at the end of your links. Otherwise, no one will have enough patience to solve the maze.

@W0lf: Thanks. I thought about including the # links but the problem is they don't refresh the page when you take the same direction twice (which can happen in a maze ;-). I've added them now so people will have to press F5 the second time they want to take the same direction. Another option is to play it here (my SO profile: http://stackoverflow.com/users/81179/christophed)

I would fancy a simple no-operation link (refresh?) to make the update easier when trying to move twice in the same direction :)

@kaoD: Without the anchor parts (#) which jump to the right answer to the question (internally, without page refresh), a simple page refresh would work fine (as you can see on my linked profile where the same maze is also available). But the problem then would be that you would find yourself at the top of the page after every refresh. The real problem is that we're really limited in what we can include in an answer here on StackOverflow (for good reason off course), we can't use arbitrary Javascript for example. I have no idea about an easy way out.

You can still have the anchor and it will go straight to your post, but with a different URL (which will allow for correct gameplay.) I find the F5 method clunky.

@kaoD: the URL's are part of the answer here, I can't easily change them (each iteration). Or do I misunderstand? AFAIK the other solutions suffer the same shortcomings (when using anchor links to point to the right answer).

@ChristopheD I mean you just need a link to http://codegolf.stackexchange.com/questions/5933/create-a-user-profile-mini-game/6171?noop#answer-6171 and clicking it will refresh the page, keep the anchor and will let you click the same option again.

@kaoD: I've included a noop part as you suggested, but I still don't see how that would help (the second time) since I am obliged to use fixed links in my answer...

@ChristopheD wow, I'm having a hard time making it clear :P If you put that link apart (not for each of your links) the user can click it to avoid pressing F5 (which doesn't always work for me, btw.) Since the URL changes (and your game does nothing, since it's a non-operative link) you can click again the link that didn't work before!

@kaoD: sorry for begin so slow in understanding what you meant, I've added a noop button.

Sorry I am total noob but I tried to get a next move like this here, why does it not work? I am apparently misunderstanding the POST -request? I copy-pasted this code to my server with PHP support, maze here works, but the POST -controls not working with your example, why?

"Simon says" game
Unfortunately, I could not get this submission in on time by the (somewhat arbitrary) deadline, but I really wanted to demonstrate animation in such a user profile game, and none of the previous submissions are animated. This game is a clone of the classic Milton Bradley game Simon, in which the player tries to repeat an increasingly long sequence of signals.
Information about this game, including its source code, is available at its GitHub page. There may be occasional graphical glitches (especially on Windows computers) arising from the hackish "palette animation" that avoids the need for a graphics drawing library. The existence of these glitches can serve as a useful excuse for quickly losing this game because of terrible memory.
Additionally, the effects of high latency and limited bandwidth can make this game much more challenging than the original as well. I think that in order to get much more than five points (when the game first speeds up), you will need to determine which light flashes one more time than in the previous round rather than depending on the correct sequence (which is very hard to do).
If this game fails to work for you (it restarts every time you click a button), your browser might be blocking its cookie. I have not yet added a workaround, so for the time being, please either use Chrome, Opera, or Firefox or temporarily change your Internet Explorer or Safari cookie settings.
Edit 2018-05-24: At this time, I have deleted the publicly accessible Heroku instance of this app. I may or may not put the app back online at a later date. The app's code is still available on GitHub, so you can either run it locally or create your own Heroku app instance if you wish to play the game.

+1 That is absolutely brilliant!  Never thought of doing dynamically generated animate gifs :P


text:
Text-Twist - similar to boggle problem
A similar play on the boggle problem from before (some text from that has been used below, edited to fit)
any code that solves the familiar "text-twist" game
Objective
7 letters are given at random, to which there is a minimum 1 word that uses all 7 letters, and multiple words using less (3 or more required)
The letters may be used in any order, however not duplicated (unless duplicates are included in the 7)
Your code should run for no more than 1 minute (60 seconds). At that time, it should have solved all results.
Final challenge score will be the character count of the program.
In the event of a tie, the winner will be the fastest output, decided by an average of 3 inputs, the same being given to both.
In the event there is still a tie, the winner will be whichever algorithm found more long (6+) words.
Rules / constraints
Please refer to wordlist.sourceforge.net for a word list (use ISPELL "english.0" list - the SCOWL list is missing some pretty common words).
This listing may be referenced in your code any way you wish.

"This listing may be referenced in your code any way you wish." Does this just mean that we can access the file contents in any way, or (for example) can we require that the list has been preprocessed in some way?

@breadbox, I think there must be some limits. E.g. if you preprocess it to reduce the problem to a single grep ^$0 dict | sed s/^.*:// I think that's going too far...

Yes, but then where do you draw the line? But never mind; I realized a bit later that I should have asked a number of more basic questions first.

Perl, 90 chars
$_++for@q{<>=~/./g};open E,"E";while(<E>){%p=%q;$.*=$p{$_}--for/./g;y///c>3&&$.&&print}

The program takes the list of letters as a line on standard input. The word list is referenced as a file in the current directory named "E". (Presumably this falls under the umbrella of "any way you wish".)
Some other assumptions I made that were not spelled out in the problem description:

that the goal was to produce a program (as opposed to a function);
that the input was case-sensitive;
that apostrophes and hyphens were not to be ignored;
that the program was required to not match on words in the word list that were too short.

Also, I wonder if the time limit given in the original description is necessary. Even when given a huge list of letters such that every word in "english.0" matches, my program still runs to completion in under 1s.

Ruby 154 152 151
require 'set'
d=Set.new(File.read(?e).split)
(3..7).each{|t|puts (0..6).to_a.permutation(t).map{|p|p.map{|i|$*[0][i]}.join}.select{|w|d.include? w}|[]}

Expects the 7 letter input as the first command line argument (ex: ruby texttwist.rb abcdefg). Dictionary is in a file called "e" in the same dir.

I think you can change .uniq for |[]

@Cyoce You're right; thanks!

Also I think you can remove the parens on d.include?(w)

@Cyoce That's also right. Edited!

Python, 158 chars
w=raw_input()
q=dict.fromkeys(w,0)
for c in w:q[c]+=1
for b in open('E'):
 p=dict(q)
 for c in b[:-1]:
    if p.get(c,0):p[c]-=1
    else:b=''
 if len(b)>3:print b,

This seems larger than it needs to be, but I'm just starting to learn Python from a golfing perspective. Hopefully someone more Python-savvy will submit a better answer.

bash 152
s(){
echo $1|sed -r 's/(.)/\1\n/g'|sort|tr -d "\n"
}
o=`s $1|sed -r 's/(.)/\1?/g'`
for s in `egrep "^[$1]{3,7}$" e`;do s $s|egrep -q ^$o$&& echo $s;done

The file has to be renamed to 'e' (line 1) to make it work.
Ungolfed:
Let's generate the testdata ourself:
alpha=({a..z})
word=$(for n in {1..7}; do r=$((RANDOM%26)); echo -n ${alpha[r]}; done ; echo)
echo $word
# $word=owimvhl

In above code, $word is $1 - user input.
text=$(egrep "^[$word]{3,7}$" english.0)
# t=hill him hollow how howl iii ill loom low mill mom mow oil owl vii viii vow whim who whom will willow woo wool

We take every word of len 3 to 7 from the english.0 dict, ^...$ prevent unwanted characters to slip in. We still might have unwanted duplicates, however.
sort () {
  echo $w | sed -r 's/(.)/\1\n/g' | sort | tr -d '\n'
}
# sort $w7 => hilmovw

We now split the word, to sort the characters, and rebuild the word. Now we insert a ? after every character:
optional=$(sort $word|sed -r 's/(.)/\1?/g')
# h?i?l?m?o?v?w?

This way we only use every character, which appears only once, only once.
for s in $text ; do sort $s | egrep -q "^$optional$" && echo $s; done
him
how
howl
low
mow
oil
owl
vow
whim
who
whom

Hm. Assertion that there is a match with 7 characters didn't hold. Try something else:
time ./cg-5947-text-twist.sh unknown
know
known
non
noun
now
nun
own
unknown

real    0m0.207s
user    0m0.200s
sys 0m0.052s

C# 412
void F(string l){
for(var i=3;i<8;i++)
foreach(var s in P(l.Length,i,new int[]{})
.Select(p=>new string(p.Select(c=>l[c]).ToArray()))
.Where(File.ReadAllLines("e").Contains)
.Distinct())
Console.WriteLine(s);
}
IEnumerable<int[]>P(int n,int r,int[]c){
if(c.Length<r)
for(var i=0;i<n;i++)foreach(var j in P(n,r,c.Concat(new[]{i}).ToArray()))yield return j;
else
if(c.Length==c.Distinct().Count())yield return c;
}

Not really the right language to golf in, but it was fun. :)
The entry point is the F method, which needs to be called with a string argument representing the 7 letters.
I tested it with the input "indents" got this output: http://pastebin.com/uBuwr50R (unfortunately I don't think it's possible to run this on ideone.com because of the dictionary file dependency).
The above test executes in about 7.5s on my machine.
If I replace File.ReadAllLines("e") with new HashSet<string>(File.ReadAllLines("e")), the execution time drops to about 1.5s, but at a pretty high character count cost.
Just like breadbox (in his Perl answer), I:

named the dictionary file e and considered it's present in the current dir
made the string comparisons case sensitive
did not ignore special characters (apostrophes, hyphens) in string comparisons

Update: Here's an ungolfed (and slightly refactored for readability) version: http://pastebin.com/b1wxv4zU