text:
Convert C header names to C++ header names
In the C standard library, header names end with a .h suffix:
stdio.h

In C++, those header names are available in an alternative form, with a c prefix instead:
cstdio

Write a function that converts the first form into the second. You can do the conversion in-place, or leave the original string intact and return a new string. Whatever feelds natural in your language of choice.
The code must be compiled/interpreted without errors. Compiler warnings are acceptable.
Here is your baseline C solution. It has 70 characters and generates a warning about strlen:
void f(char*h){int i=strlen(h);h[--i]=0;while(--i)h[i]=h[i-1];*h='c';}

The shortest solution (measured in number of characters) wins.
Update: If your language of choice does not support functions, whole programs are also acceptable.
Update: As suggested by FUZxxl, here is a complete list of the header files in the C standard library:
assert.h
ctype.h
errno.h
float.h
limits.h
locale.h
math.h
setjmp.h
signal.h
stdarg.h
stddef.h
stdio.h
stdlib.h
string.h
time.h

Specifically, there are no header names with multiple dots in them.

80386 machine code, 13 bytes
Hexdump of the code:
b0 63 86 01 41 3c 2e 75 f9 c6 01 00 c3

Source code (can be compiled by Visual Studio):
__declspec(naked) void __fastcall conv(char s[])
{
    _asm {
        mov al, 'c';            // b0 63
    myloop:
        xchg al, [ecx];         // 86 01
        inc ecx;                // 41
        cmp al, '.';            // 3c 2e
        jne myloop;             // 75 f9
        mov byte ptr [ecx], 0;  // c6 01 00
        ret;                    // c3
    }
}

It converts the string in-place. The code is so simple, it doesn't need to save and restore registers (using only al and ecx, which the fastcall convention allows to clobber).

Nice, this takes me back :)

Definitely one of the cooler solutions! But the source code isn't really 13 bytes, only the compiled form of it (that I think few of us would want to write in a hex editor).

Give him his win. Byte = character is a perfectly reasonable interpretation here.

@PerLundberg I see the source code in this case as being the "how it works" expanded/commented explanation that a lot of people include in their ultra-compact languages. For such a small program it could very well have been hand-written. :)

@fluffy Fair point. And yeah, the number of people that could write the binary code by heart is certainly >0, even though I don't know anyone that geeky myself. ;)

Python: 19 characters
lambda s:'c'+s[:-2]

CJam, 6 bytes
'clW(<

This is a full program which reads the string via STDIN
Explanation:
'c               "Put character c on stack";
  l              "Read a line from STDIN";
   W             "W is a predefined variable with value -1";
    (            "Decrease the value by 1";
     <           "Remove last 2 characters from the string on stack, the input argument";

Try it online here

Isn't -2 just as good as W(?

Java 8 — 25 characters
h->"c"+h.replace(".h","")

brainfuck - 25 23 bytes
,[>,]<-----.<,<[<]>[.>]

If your language of choice does not support functions, whole programs are also acceptable.

This is a whole program that takes input from STDIN.
,[>,]      get all bytes of input
<-----.    subtract 5 from last byte (always "h"; "h" minus 5 = "c") and print result
<,         set second last byte to 0 by abusing comma
<[<]>      go to first byte
[.>]       print byte and move right until hitting 0

Wouldn't this step off the left edge of the tape upon [<]

@feersum If your interpreter allows you to step off the left edge, yes. Every one I've ever used loops the tape.

@feersum If you'd like to try it but your interpreter does allow you to fall off, you can fix it with a > at the beginning.

Haskell — 23 characters
('c':).takeWhile(/='.')

Haskell — 16 characters, as suggested by nimi
('c':).init.init

Dropping the last 2 characters with init.init instead of taking all up to the first . saves a few bytes.

@nimi That is an awesome suggestion!

C, 38
See on Ideone
f(s,o){snprintf(o,strlen(s),"c%s",s);}

s is a pointer to the input string, and o is where the output should be written to.
I found a way to abuse snprintf. The output string conveniently happens to be one character shorter than the input, and the maximum length of the string written by snprintf is 1 less than the n argument, so it cuts off the .h. Note: this technique will not work with Microsoft's implementation because it does the wrong thing and fails to null-terminate the string.

TIS Node Type T21 Architecture - 85 bytes
This answer is just for fun; the language came into existence after this challenge was written and I therefore cannot win with it. (Not that I was going to.)

Okay, I had a little fun with this one. I probably should just call the language "TIS-100", but why break character? :D
TIS-100 is a game about programming a computer with a totally unique and bizarre architecture. I wrote a custom puzzle for this challenge, which allows me to take input and check output against a known-correct "string". Unfortunately, there's no way to handle strings or characters, so this program simply uses the ASCII value of each character for input and output.
If you'd like to see it in action, you can use this emulator, or just watch me run it in the actual game here. Note that in the video, the final line of the first node is D:MOV UP NIL. After finishing the video, I realized I could golf that down to D:ADD UP. Functionally there's no difference, because the value of ACC is immediately overwritten anyway.
This is the string I used for my byte count:
MOV 99 ANY
MOV -46 ACC
ADD UP
JEZ D
ADD ACC ANY
JRO -5
D:ADD UP
MOV UP ANY
MOV UP ANY

That's the text of each non-empty node, seperated by newlines (effectively adding 1 byte for each node used beyond the first, mirroring our rule about code in multiple files).

Windows Batch file 11
@echo c%~n1

The first parameter passed in is %1.  The ~n modifier returns just the filename without extension.
If it's acceptable to echo the expanded command to the screen as well, then the initial @ could be removed.

J (9 characters)
'c',_2}.]

|y is the magnitude of y (also called absolute value)
x }. y drops |x items from y; items are dropped from the front if x is positive, from the end if x is negative.
x , y appends x and y.
'c' , _2 }. y does the transformation you want; in tacit notation this can be expressed as 'c' , _2 }. ].

Dyalog APL (8 characters)
'c',¯2↓⊢

This solution is exactly the same as the J solution I submitted but uses one character less due to ↓ being one character less than }..

piet (9x11 = 99 8X11=88)

another try (2x37 = 74)

Hard to make it much smaller since it needs to generate a 99 ('c') and a 46('.'), and that takes space in piet.

Piet's never measured in characters, only codels, so you don't need to mention the 0 chars bit :) Also that's a lot of white

trying to compress, but it is a bit difficult. Having trouble getting it to terminate if I remove yet another row or column.

This is a bit of cheating, but I like it. This is like using /dev/null as your source-code.

According to META (http://meta.codegolf.stackexchange.com/questions/4782/do-programs-have-to-terminate?cb=1), your program isn't required to finish. As long as it does it's task, your program can run forever. Read the first answer to the question.

Ostrich 0.6.0, 8 characters
););"c\+

) is the "right uncons" operator. When applied to a string, it turns, for example, `foo` into `fo` `o`. ; is used to pop the extra character off, and this is done again.
Then, "c is pushed. This is simply a shorthand for `c`.
\+ swaps the top two stack elements and concatenates them.

Was this language created by you?

@IsmaelMiguel Yes. (See the main Github repo.)

I though so. I already checked it, therefore thinking about it. There is no reference on that language anywhere. Only here. So, I assumed it was made by you. For a 14 years old guy, you went really far on programming. +1000 for that!

@IsmaelMiguel Whoops, sorry, should have told you that I'm KeyboardFire on Github. Thanks!

You don't need to. It's almost implied. I'm ismael-miguel (very original, check https://github.com/ismael-miguel). I have nothing interesting and useful there, but you may check it. But I'm interested on your language. The only complete thing is the UIntArray class for php (https://github.com/ismael-miguel/php-uintarray if you are interested).

F# - 39 37 31
31 - Because typeinference in F# rocks!
fun s->("c"+s).Replace(".h","")

37
fun(s:string)->"c"+s.Replace(".h","")

39
fun(s:string)->"c"+s.Remove(s.Length-2)

Doesn't work for a header named foo.hoo.h.

@FUZxxl There are no such headers in the C standard library.

@FredOverflow You might want to specify the set of names on which the transformation has to work. Right now your question is worded in a way that might lead people to assume that this kind of input must work correctly.

@FUZxxl I have updated the question accordingly.

gema, 6
*.h=c*

(Gema is an obscure macro language.)

GNU sed -r, 14
sed doesn't really have any concept of functions, so here is a complete sed program instead:
s/(.*)../c\1/

Output
$ sed -r 's/(.*)../c\1/' <<< stdio.h
cstdio
$

The -r has been included in the score as one extra character.

This solution is invalid: It should probably be s/\(.*\)\.h/c\1/ instead.

@FUZxxl - I'm assuming -r is passed to sed.  As per usual [tag:code-golf] I need to count that as an extra point.

@DigitalTraume Notice that -r is not a standard option and not available outside of GNU sed. You might want to change the language name to GNU sed to reflect that.

@FUZxxl Yes. Done.

\.h can be shortened to ..

@StevenTaschuk Yes - thanks!

Bash, 18
f()(echo c${1%.*})

Output:
$ f stdio.h
cstdio
$

Pyth, 7 characters
L+\cPPb

Explanation:
L         def y(b):return
 +\c                      "c" +
    PPb                         b[:-1][:-1]

Try this:
L+\cPPb
y"stdio.h

on the online Pyth Compiler/Executor

If full programs were allowed:
Pyth, 6 characters
+\cPPQ

I have never seen Pyth. Would you be so kind and explain the code? :)

@FredOverflow See http://codegolf.stackexchange.com/q/40039/18487

I believe you can use PPb instead of <b_2

@FryAmTheEggman Thanks.

It seems like full programs are allowed, so you can get to 6.

"If your language of choice does not support functions, whole programs are also acceptable" Pyth defs has functions

Prelude, 31 characters
Since full program submissions are apparently acceptable, here is a program that reads the C-style header from STDIN and prints the C++-style header to STDOUT:
99+9+(?)###(#
9(1-)       ^)(!)

This requires a standard-compliant interpreter which prints output as character codes. If you're using the Python interpreter you'll need to set NUMERIC_OUTPUT = False.
It also requires that there's no trailing newline on STDIN.
Explanation
In Prelude all lines are executed in parallel, one column at a time. Each line has its own stack, initialised to an infinite amount of 0s.
99+9+
9(1-)

This is the shortest I could come up with to get a 99 onto the top stack (the character code of c). First I add up 18 on the top stack and push a 9 onto the bottom stack. The bottom then counts down to 0 in a loop, while the top stack adds more 9s up. This adds up to 99 on the top stack, and the bottom stack is left with 0s again. Note that all of +9+ is part of the loop, so there are actually two addition operations per iteration, but that's not an issue, thanks to the infinite supply of 0s underneath.
Now (?) reads STDIN, one character at a time and pushes onto the top stack. The loop terminates at the end of the input, when ? pushes a zero. ### gets rid of that zero, the h and the .. Now the next loop pops numbers from the top stack while copying them to the bottom stack. This essentially reverses the stack. Note that the opening and closing parentheses are on different lines - this is not an issue, because the vertical position of the ) is irrelevant in Prelude, but it saves me a byte on the first line.
Lastly, (!) prints all the characters until the stack is empty.

C++14, 41 characters
[](auto&s){s="c"+s.substr(0,s.size()-2);}

Inspired by this other answer. I made it a separate answer because here I use a feature that is new in c++14, generic lambda.
See it in action here.

Perl — 20 characters
sub{c.pop=~s/..$//r}

Note how c is a bareword and as such this requires a lack of use strict. This must be used as an expression, not a statement.

T-SQL — 58 characters
CREATE PROC Q(@ VARCHAR(MAX))AS
SELECT'c'+LEFT(@,LEN(@)-2)

Run as EXEC Q (your string here)

C, 64
Mildly shorter than the c reference:
f(char*h){char*d=strstr(h,".");memmove(h+1,h,d++-h);*d=0;*h=99;}

Probably more golfing to be done with this.

C, 48 (libc hack)
f(char*h){strcpy(h+1,h);*strstr(h,".")=0;*h=99;}

The strcpy manpage explicitly states "The strings may not overlap".  However I found that the libc I am using appears to be coded safely to handle this correctly all the same.  This is GNU C Library (Ubuntu EGLIBC 2.19-0ubuntu6.4) on Ubuntu 14.04.

Is omitting the return type of a function legal in C89?

@FredOverflow.  Yes - gcc compiles this just fine with -std=c89.  http://codegolf.stackexchange.com/a/2204/11259

@FredOverflow Yes. The return type defaults to int.

The man page just reiterates the Standard - compiling this with VC++ (VS2012) gives "cstdii" for "stdio.h".  Didn't check ICC/Sun/clang, but your 64-char version says "why?" - it's about as short as it can (legally) be in C.

Marbelous, 24
@063
-Z//
3W<C+Z
]]!!
@0

Takes input through STDIN, outputs to STDOUT.
This works by checking each byte with . (0x46). As 0x46 cannot fit inside a single base-36 digit, we subtract 35 (Z) before comparing, and add it back before outputting.
Each marble is duplicated by 3W (three-way duplicator, but the left side is discarded off the side of the board). The marble sent downwards fetches the next byte from STDIN. The marble to the right is checked to ., then either outputted, or sent to !!, which terminates the program.
The program starts by passing c (0x63) through, which will be output to STDOUT.
Try it online here. Libraries must be enabled, cylindrical boards must be disabled.

JavaScript (ES6) 20
Can't believe ES6 was still missing
s=>'c'+s.slice(0,-2)

Perl, 15 (14 + -p)
s/(.*)\.h/c$1/

mk, 34 characters
mk(1) is the Plan 9 replacement for make. Just for fun, this mkfile converts C header names into C++ header names:
c%:Q:
    :

%.h:Q: c%
    echo $prereq

There is a single tab before : and echo. Use like this:
% mk stdio.h
cstdio

Vyxal, 5 bytes
\cpṪṪ

Explanation:
\cpṪṪ   # full program
\c      # c
  p     # prepend using implicit input
   ṪṪ   # remove last two letters

Try it Online!

CoffeeScript - 16
(x)->"c"+x[..-3]

TI-BASIC 83/84, 15
"c"+sub(Ans,1,length(Ans)-2

Ruby: 16 characters
->x{?c+x[0..-3]}

Or, more correct solution as suggested by @mbuettner
->x{?c+x[/\w+/]}

You can call it like this:
->x{?c+x[/\w+/]}.call 'stdio.h'
# cstdio

XD damnn.. XD XD

R, 33
function(x)sub("(.+)..","c\\1",x)

This function uses regular expressions.
Example usage:
> (function(x)sub("(.+)..","c\\1",x))("stdio.h")
[1] "cstdio"

MS QuickBasic or QB64 ~ 33 bytes
A$=left$(A$,len(A$)-2)
A$="c"+A$

A$ is the name of the file

Go, 47,46
func h(s string)string{return"c"+s[:len(s)-2]}

I know I'm not winning anything with this, but I thought I might as well go for it. No pun intended

I think you can drop the space between return and "c".

@FUZxxl I didn't know I could do that, thanks for pointing that out!

C++ 14, 48
[](string s){return "c"+s.substr(0,s.size()-2);}

><>, 22 21 bytes
Since full programs are now allowed...
i:0(?v
~}-5~/r
o;!?l<

Explanation
i:0(?v      Keep reading input until EOF
~}-5~/r     Pop the -1 from EOF, turn 'h' -> 'c' with 5- and shift to back, pop '.', reverse stack
o;!?l<      Keep outputting until the stack is empty

K, 7 bytes
"c",-2_

Pretty simple. Just drops 2 chars off the end and prepends a c.
Also, despite how it looks, this is actually a function:
f:"c",-2_
f"stdio.h"

Awk: 10 characters
$0="c"$1

Sample run:
bash-4.3$ awk -F. '$0="c"$1' <<< 'stdio.h'
cstdio

V, 5 bytes
éc$xx

Try it online!
Hexdump:
00000000: e963 2478 78                             .c$xx

This is a full program that takes input from STDIN.
Explanation
éc     insert the character 'c'
$      go to the end of the line
xx     delete two characters

This is ic<esc>$xx in pure Vim.

Excel formula, 36 23 bytes
If the input is put in cell A1,
="c"&LEFT(A1,LEN(A1)-2)

Explanation
="c"&LEFT(A1,LEN(A1)-2)
="c"&                     Return the letter 'c' concatenated with...
     LEFT(            )   the first...
             LEN(A1)-2    (the length of input, minus 2 from the '.h') characters...
          A1,             of the input.

05AB1E, 5 bytes
¨¨'cì

Try it online.
Header ε is used to for-each over the input-list to verify all test cases instead of just one.
Footer }» is to close this for-each, and print the results with new-line delimiter.
Explanation:
¨¨       # Remove the last two characters of the input
    ì    # Prepend:
  'c     #  "c"

Technically not competing since the whole language was made after the question was asked.

@Nit Not anymore since the Summer of 2017. Relevant meta post.

Ah, didn't know that, thanks for the heads up.

Japt, 7 6 bytes
ic ¯-2
ic     # Given the default input, prepend a 'c' at the start
   ¯-2 # and trim off the last two letters.

Try it online!

Save a byte by omitting the '.

@Shaggy Thanks, I often forget Japt handles inputs as defaulting to chars in these cases.

Whitespace, 63 bytes
[S S S T    T   S S S T T   N
_Push_99_c][T   N
S S _Print_as_character][N
S S N
_Create_Label_LOOP][S S S N
S_Push_0][S N
S _Duplicate][T N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve][S N
S _Duplicate][S S S T   S T T   T   S N
_Push_46_.][T   S S T   _Subtract][N
T   S S N
_If_0_Jump_to_Label_EXIT][T N
S S _Print_as_character][N
S N
N
_Jump_to_Label_LOOP]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.
Try it online (with raw spaces, tabs and new-lines only).
Explanation in pseudo-code:
Print "c"
Start LOOP
  Character i = STDIN as character
  if(i == '.')
    EXIT program (with error)
  Print i
  Go to next iteration of LOOP

Program stops with an error: Label_EXIT not found.

Acc!!, 43 bytes
Write 99
N
Count i while _/96 {
Write _
N
}

Try it online!
Algorithm

Write c
Read a character into the accumulator
Loop while that character is a lowercase letter:

Write the character
Read another character

TI-89 Basic, 56 bytes
:Def a(a)=Func
:Return "c"+sub(a,1,length(a)-2
:End Func

Julia: 19 characters
f(s)="c"*s[1:end-2]

Sample run:
julia> f(s)="c"*s[1:end-2]
f (generic function with 1 method)

julia> print(f("stdio.h"))
cstdio

Perl (program) 15
s/(.*)\.h/c\1/

It converts filenames supplied on std input, and needs to be run with the p flag, so that's one more character I believe. Eg
echo stdio.h | perl -p header.pl

output:
cstdio

Note to sticklers: I just spotted that this may be invalid because challenge implies that programs are only acceptable if the language doesn't support functions. However, I'm not going to throw it all away at this stage! Ah well.
Update: Augh! And I hadn't spotted page 2 of the answers either. Please refer to @malkaroee's effectively identical answer posted 4 months ago. ... Hang on, who resurrected this thread?

Lua, 39 bytes
function f(n)return "c"..n:sub(1,-3)end

C# 6, 52 bytes
class P{string C(string f)=>"c"+f.Replace(".h","");}

C# <6, 58 bytes
class P{string C(string f){return"c"+f.Replace(".h","");}}

MATLAB, 19
@(c)[99,c(1:end-2)]

Fairly straight forward. Prepends 'c' to the input string less the last two letters. MATLAB automatically converts the 99 (ASCII value) to 'c' when appending to a character string.

Tcl, 36 bytes
proc H h {set s c[regsub ..$ $h ""]}

Try it online!

Stackers (27 bytes)
«h ®h h cc ( ~ ~

Ungolfed Version
«h "define a table called h
®h "read STDIN to h
h "read h to the stack
cc  "add the value for 'c' to the stack
(   "put c on the bottom of the stack
~ ~ "destroy the top two values on the stack
   "print stack bottom two top

Stackers is a programming language I created myself that is meant to be based on stacks, with variables and tables thrown in

SNOBOL4 (CSNOBOL4), 41 bytes
	INPUT ARB . O RPOS(2)
	OUTPUT ='c' O
END

Try it online!

Thunno 2 j, 4 bytes
2ẓ'c

Attempt This Online!
Explanation
2ẓ'c  '# Implicit input
2ẓ     # Remove last two characters
  'c  '# Push the character "c"
       # Join the stack
       # Implicit output

Raku, 13 bytes
{'c'~S/..$//}

Try it online!
S/..$// returns the result of chopping off the last two characters of the string, and 'c' ~ prepends a "c" to the front.

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


text:
Create a Scalable Valentine's Day Heart
Happy Valentine's Day! To celebrate this day of love and happiness (or sadness and loneliness for those of us who are single...), let's write some code to create some hearts!
Specifically, if you take this challenge upon you, you are to write code to output a heart/hearts as an image file, with the ability to easily change the dimensions of the image (both width and height, separately). You could take input into your program to get the dimensions, or two simple variables that can be changed would be enough (or a couple constants). If you do opt for the variables, no more than two tokens of the program should be changed to adjust the size.
So for instance, you could write a program to output this image (with variable width and height, of course):

However, that heart isn't that interesting. It's just a plain heart. I challenge you to create the most creative and interesting heart that you can!

I can help if you do not desire the love being given at Valentine's eve :P

Just a note. I did not downvote it :P

With practically no restrictions this feels like it could turn into an art contest...

I'm voting to close this question as off-topic because it's an art contest, not a programming contest.

This should be short with Mathematica (http://mathworld.wolfram.com/images/equations/HeartCurve/NumberedEquation4.gif)

@PeterTaylor Has PPCG really changed so much since I posted http://codegolf.stackexchange.com/q/15860/9498 that this is now off topic? I thought the requirement was that a big part of the challenge is coding. In order to participate in this challenge, you'd need to code.

I would say it's more the other way round: that question was never on topic, but we've got better at closing stuff which isn't.

Bash: 16 characters
echo -e "\u2665"

output (when unicode supported)
♥

Ah wait, it must be an image?
ImageMagick: 137 characters
w=99
h=199
convert -size ${w}x$w -gravity center -font WebDings -fill red label:Y h.gif
convert h.gif -resize ${w}x$h\! h2.gif

output (when WebDings font installed)

Java
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

import static java.lang.Math.PI;
import static java.lang.Math.cbrt;
import static java.lang.Math.pow;
import static java.lang.Math.sqrt;

public class Heart {
    public static double scale(int x, int range, double l, double r) {
        double width = r - l;
        return (double) x / (range - 1) * width + l;
    }

    public static void main(String[] args) throws IOException {
        BufferedImage img = new BufferedImage(1000, 1000, BufferedImage.TYPE_INT_RGB);
        final double max_heart = 0.679; // This is the approximate max value that can come out of the heart function (found by trial and error)
        double max = 0.0;
        for (int x = 0; x < img.getWidth(); x++) {
            for (int y = 0; y < img.getHeight(); y++) {
                double xv = scale(x, img.getWidth(), -1.2, 1.2);
                double yv = scale(y, img.getHeight(), -1.3, 1);
                double heart = heart(xv, yv);
                int r = 0xFF;
                int gb = (int) (0xFF * (max_heart - heart));
                int rgb = (r << 16) | (gb << 8) | gb;
                img.setRGB(x, y, rgb);
            }
        }
        ImageIO.write(img, "png", new File("location/heart.png"));
    }

    public static double heart(double xi, double yi) {
        double x = xi;
        double y = -yi;
        double temp = 5739562800L * pow(y, 3) + 109051693200L * pow(x, 2) * pow(y, 3) - 5739562800L * pow(y, 5);
        double temp1 = -244019119519584000L * pow(y, 9) + pow(temp, 2);
        if (temp1 < 0) {
            return topHeart(x, y, temp, temp1);
        }
        double temp2 = sqrt(temp1);
        double temp3 = cbrt(temp + temp2);
        if (temp3 != 0) {
            double part1 = (36 * cbrt(2) * pow(y, 3)) / temp3;
            double part2 = 1 / (10935 * cbrt(2)) * temp3;
            double looseparts = 4.0 / 9 - 4.0 / 9 * pow(x, 2) - 4.0 / 9 * pow(y, 2);
            double sqrt_body = looseparts + part1 + part2;
            if (sqrt_body >= 0) {
                return sqrt(sqrt_body);
            } else {
                return -1;
            }
        } else {
            return Math.sqrt(Math.pow(2.0 / 3, 2) * (1 - Math.pow(x, 2)));
        }
    }

    private static double topHeart(double x, double y, double temp, double temp1) {
        //complex arithmetic
        double[] temp3 = cbrt_complex(temp, sqrt(-temp1));
        double[] part1 = polar_reciprocal(temp3);
        part1[0] *= 36 * cbrt(2) * pow(y, 3);
        double[] part2 = temp3;
        part2[0] /= (10935 * cbrt(2));
        toRect(part1, part2);
        double looseparts = 4.0 / 9 - 4.0 / 9 * pow(x, 2) - 4.0 / 9 * pow(y, 2);
        double real_part = looseparts + part1[0] + part2[0];
        double imag_part = part1[1] + part2[1];
        double[] result = sqrt_complex(real_part, imag_part);
        toRect(result);

        if (Math.abs(result[1]) < 1e-5) {
            return result[0];
        }
        return -1;
    }

    public static double[] cbrt_complex(double a, double b) {
        double r = Math.hypot(a, b);
        double theta = Math.atan2(b, a);
        double cbrt_r = cbrt(r);
        double cbrt_theta = 1.0 / 3 * (2 * PI * Math.floor((PI - theta) / (2 * PI)) + theta);
        return new double[]{cbrt_r, cbrt_theta};
    }

    public static double[] sqrt_complex(double a, double b) {
        double r = Math.hypot(a, b);
        double theta = Math.atan2(b, a);
        double sqrt_r = Math.sqrt(r);
        double sqrt_theta = 1.0 / 2 * (2 * PI * Math.floor((PI - theta) / (2 * PI)) + theta);
        return new double[]{sqrt_r, sqrt_theta};
    }

    public static double[] polar_reciprocal(double[] polar) {
        return new double[]{1 / polar[0], -polar[1]};
    }

    public static void toRect(double[]... polars) {
        for (double[] polar: polars) {
            double a = Math.cos(polar[1]) * polar[0];
            double b = Math.sin(polar[1]) * polar[0];
            polar[0] = a;
            polar[1] = b;
        }
    }
}

To scale, just change the x/y dimensions of this line (the first line in the main function):
BufferedImage img = new BufferedImage(1000, 1000, BufferedImage.TYPE_INT_RGB);

Output (for a size of 1000 by 1000):

On wikipedia, there is a 3D heart shown. This was my inspiration; I thought to myself, "Why not use a 3D heart and use the Z output as color?" So that's exactly what I did. However, I didn't use the exact same formula; I used this implicit equation for a 3D heart:

I played around in Mathematica, (I think I switched z and y) and solved for z, yielding this really ugly equation (click for full size):

Then, I "simply" implemented the function in Java. Okay, it wasn't so simple. I had to do some checks to avoid exceptions (no sqrts of negative numbers). But there is one case where we do need to take a sqrt of a negative number (IE delve into the complex world) in order to get a real output. That's why I have the topOfHeart function; it does the computation for that part. If I replace the call to that function with return -1, this is the image I get instead (smallified):

A couple interesting things to note:

I do a lot of return -1 to show that I reached an invalid value, but I don't handle this in the main function. This results in a color of 0xFFADAD - a lovely shade of pink
The complex number functions are semi-interesting. I switch between polar and rectangular coordinates, since polar coordinates make multiplicative operations easier, while rectangular coordinates make additive operations easier.

cbrt_complex and sqrt_complex are actually very interesting. Using wolframalpha, I found this formula for the nth root of a complex number (polar form):

taking the reciprocal of a polar coordinate complex number is easy: r eiθ -> 1/r e-iθ
multiplying by a real number d is also easy: r eiθ -> d r eiθ

W o w. J u s t  -  w o w.

source: Stack Exchange

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

sort: votes


text:
Key length of Vigenère cipher
The Vigenère cipher is a substitution cipher where the encryption of each letter of the plaintext depends on a different character in a keyword.  This stops you using simple methods of frequency analysis to guess the correct substitution.  However, the keyword is repeated if it is shorter than the plaintext.  This is a weakness.  If the length of the keyword is known (n, say), however, and is much shorter than the message, then you can decompose the message into separate sections by taking every nth letter.  You can then use frequency analysis on these.
The Kasiski examination is a method to work out the most likely key lengths.  It does this by considering identical substrings which happen to be a multiple of the key length apart.  They are therefore encrypted in the same way.  Turning this round, identical substrings in the ciphertext are likely to be a multiple of the key length apart.  If you identify these distances, then the key length is likely to be a common factor of all these distances.
Your job is to write a function or program that can guess the most likely length of the keyword, given some encrypted text.  To be precise, the function or program (just called function below) will satisfy the following:

Inputs consist of a string representing the ciphertext and a positive integer (len, for the purposes of this spec) representing the shortest common substring to look at.
The ciphertext will consist of upper case A-Z characters only. Any length is permitted.
You can assume valid inputs without checking.
The inputs may be passed in, or read from stdin.
The function will identify all pairs of identical substrings in the ciphertext which have a length of at least len.
Substrings in each pair may not overlap but substrings in different pairs can overlap.
The function will return, or write to stdout, the highest common factor of the distances between the starts of these identical pairs.
If there are no identical substrings then the function will return 0.

For example:
"AAAAAAAAAAAAAAAAAA", n returns 1 for any n from 1 to 8, 9 for n = 9 (as the only possible non-overlapping substrings of length 9 happen to be the same) and 0 otherwise.
"ABCDEFGHIJKL", n returns 0 for any n
"ABCDEABCDE", n returns 5 for n<=5 and 0 otherwise
"ABCABABCAB", 2 returns 1 because "AB" pairs are separated by 2,3,5 & 8
"ABCABABCAB", 3 returns 5
"VHVSSPQUCEMRVBVBBBVHVSURQGIBDUGRNICJQUCERVUAXSSR", 4 returns 6 because the repeating "VHVS" are 18 characters apart, while "QUCE" is separated by 30 characters
Naturally, lowest byte count wins and avoid standard loopholes.

I followed this up to the examples, but the first one appears to completely contradict the spec. Surely "AAAAAAAAAAAAAAAAAA", n should return 1 for any n from 1 to 8, because that's the highest common factor of n and n+1?

@PeterTaylor Quite correct.  I've edited this in and improved the formatting.

CJam, 67 bytes
Definitely still room for improvement, but I'll post what I have so far.
Try it online
0r:T,,ri>{T,L(-,_m*{~:XT>L<T@LX+e>,{0t}/X>\#_W>\2$?{\1$_!+%}h;}/}fL

I don't know how CJam works but it gives the right answers.  Can you explain it?

JavaScript (ES6) 117
F=(s,n,G=(a,b)=>b?G(b,a%b):a)=>(i=>{
  for(f=i;s[(j=i+n)-1];i++)
    for(;p=~s.indexOf(s.substr(i,n),j++);)
      f=G(~p-i,f)
})(0)|f

Ungolfed
F=(s,n)=>
{
  var G = (a,b) => b ? G(b,a%b) : a; // GCD function
  var p,w,i,j, f = 0; // f starting divisor
  for(i = 0; s[i + n - 1]; ++i) // scan s for each substring of lenght n
  {
     w = s.substr(i,n);
     for (j=i+n; (p = s.indexOf(w,j)) != -1; ++j) // find all occurrencies of substring in the rest f the string
        f = G(p - i, f); // p-i is the distance between pairs
  }
  return f
}

Test In Firefox/FireBug console
;["AAAAAAAAAAAAAAAAAA","ABCDEFGHIJKL","ABCDEABCDE","ABCABABCAB",
  "VHVSSPQUCEMRVBVBBBVHVSURQGIBDUGRNICJQUCERVUAXSSR"]
.forEach(s=>{
  for(o=[],i=1;i<=10;i++) o.push(i+':'+F(s,i));
  console.log(s+' '+o)
})

Output
AAAAAAAAAAAAAAAAAA 1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:1,9:9,10:0
ABCDEFGHIJKL 1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0
ABCDEABCDE 1:5,2:5,3:5,4:5,5:5,6:0,7:0,8:0,9:0,10:0
ABCABABCAB 1:1,2:1,3:5,4:5,5:5,6:0,7:0,8:0,9:0,10:0
VHVSSPQUCEMRVBVBBBVHVSURQGIBDUGRNICJQUCERVUAXSSR 1:1,2:1,3:6,4:6,5:0,6:0,7:0,8:0,9:0,10:0

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


text:
Rotor Routers on a Grid
Input
Your input is a single string, separated by newlines into 2n+1 lines of length 2n+1, for some integer n ≥ 0. The integer n is not part of the input; you'll have to compute it from the string. The lines are composed of the "direction characters" >^<v. If newlines pose a problem, you can replace them by vertical pipes |.
The input forms a square grid of size (2n+1)x(2n+1), and each cell of the grid is interpreted as a rotor router, which points in one of the four cardinal directions. We proceed to drop a token on the router at the center of the grid, and then the routers will move it around in the following way. When the token lands on a router, the router turns 90 degrees in the counter-clockwise direction, and moves the token one step in the new direction it points to. If it lands on another router, the process is repeated, but eventually, the token will fall off the grid.
Output
Your output is the final configuration of the routers, in the same format as the input.
Example
As an example input, consider the 3x3 grid
<^<
^><
>^v

where the central router has been highlighted to indicate the token (it's a bit hard to see). The central router rotates to face north, and moves the token to the central cell of the top row:
<^<
^^<
>^v

This router rotates to face west, and sends the token to the top left corner:
<<<
^^<
>^v

The router in the corner sends the token south, so it's now at the leftmost cell of the middle row:
v<<
^^<
>^v

That router rotates to face west and sends the token off the grid.
v<<
<^<
>^v

This is the final grid configuration, so your program should output it. Note that in more complex examples, the token can pass the same router multiple times before falling off the grid.
Rules
You can write either a function or a full program. This is code-golf, so the lowest byte count wins. Standard loopholes are disallowed. You can decide whether there is a trailing newline in the input and/or output.
Test Cases
Input:
v
Output:
>

Input:
<^<
^><
>^v
Output:
v<<
<^<
>^v

Input:
>>^>>
v<vv<
>^>^<
^<>>^
vvv>>
Output:
>>^>>
>v>>v
^>>vv
^^>>>
v^<<^

Input:
<^^^^^^^^
<<^^^^^^>
<<<^^^^>>
<<<<^^>>>
<<<<^>>>>
<<<vv>>>>
<<vvvv>>>
<vvvvvv>>
vvvvvvvv>
Output:
>>>>>>>>v
^>>>>>>vv
^^>>>>vvv
^^^>>vvvv
<<<<<vvvv
^^^^<<vvv
^^^<<<<vv
^^<<<<<<v
^<<<<<<<<

Should the two instances of "rotates to the east" say "rotates to face west"?

@PeterTaylor Good catch. I always seem to confuse the two.

Is the input string terminated with a newline?

@edc65 You can decide that yourself, also for the output. There are no preceding newlines, though.

CJam, 62 61 63 bytes
Try it online
Nq_N#):D;+_,2/{:P"^<v>^

"_P4$=#:X)=t_,0PX[1DW*WDSP]=-e>e<}h;1>

Expanded and commented:
Nq              "Read the input grid";
_N#):D;         "Calculate the vertical delta (line length + 1)";
+               "Prepend a newline to the grid";
_,2/            "Calculate the initial position as the length of the grid
                 string divided by 2";
{               "Do...";
  :P"^<v>^

"
  _P4$=           "Get the character indexed by the position in the grid";
  #:X             "Map the character to an operation number:
                   '^'=>0, '<'=>1, 'v'=>2, '>'=>3, '^'=>4, '\n'=>5, '\n'=>6
                   (the unreachable duplicate mappings are important below)";
  )=t             "Set the character indexed by the position in the grid to
                   the result of mapping the operation number + 1 backwards";
  _,0PX[1DW*WDSP]="Map the operation number to a negated delta (this occurs
                   after rotating routers, which means that operation n should
                   act like the character corresponding to operation n + 1):
                   0=>1, 1=>-delta, 2=>-1, 3=>delta, 5=>position";
  -e>e<           "Subtract the negated delta from the position and clamp it to
                   [0, length of the grid string] (array indices are circular,
                   so the length of the grid string will act like the index 0
                   and point to the initial newline next iteration, which will
                   *really* set the position to 0)";
}h              "... while the position is not 0 (i.e. not at the initial
                 newline)";
;1>             "Clean up and remove the initial newline";

My solution operates on the input as a flat string, so there's only one position value to keep track of and virtually no pre/postprocessing; there are only 2 bytes of preprocessing to add newline to the beginning of the grid and 2 bytes of postprocessing to remove it from the output. But these 4 bytes are well worth the cost as they let me keep newlines in and "execute" them like routers, but they "rotate" into another newline and set the position to zero. And the main loop ends when the position becomes zero.

I'll rule that the preceding newline unfortunately has to go; only trailing ones are permitted.

@Zgarb Fixed, +2 bytes.

It seems that the output from your link is not correct

@aditsu You are indeed correct. I'm not sure what I touched, I swear it used to work fine. I'll look into it.

@aditsu Turns out subtraction isn't commutative. Thanks for pointing out that it was broken, that was easy enough to fix. But now one of the comments touches the code. :(

CJam, 90 69 bytes
q_,mqi):L_*Lm2/(:X;{_X_@="^<v>"_@#_[WL1LW*]=X+:X;)=tX)L%XW>XLL(*<**}g

Huge for now, Can still be reduced a lot.
Try it online here

Curses, foiled again! I was just about to post by 70 byte CJam solution, but it looks like that'll need some rethinking now.

JavaScript (ES6) 121 120 127 129
A named function that gets the string as an input parameter and returns the output.
Assuming the input string is terminated with a newline.
Edit bug fix, .search() does not work well with undefined
F=s=>(o=~s.search('\n'),s=[...s],
R=p=>~(u='^<v>'.indexOf(s[p]))?R(p+[-1,-o,1,o][u],s[p]='<v>^'[u]):s)(-~o*o/2-1)
.join('')

Ungolfed and explained
F=s=>{
  o = s.search('\n')+1; // offset to next row
  s = [...s]; // string to array
  R=p=>{ // recursive search functiom, parameter p is current position in grid
    u = '^<v>'.indexOf(s[p]); // find direction
    if (u<0) return s; // if no direction found, out of grid -> stop recursion
    s[p] = '<v>^'[u] // set new direction into the array cell
    return R(p+[-1,o,1,-o][u]) // call recursive function with new position
  }
  return R((o-1)*o/2-1) // start recursive search with initial position at grid center
  .join('') // array to string
}

Test In Firefox/FireBug console
s='<^^^^^^^^\n\
<<^^^^^^>\n\
<<<^^^^>>\n\
<<<<^^>>>\n\
<<<<^>>>>\n\
<<<vv>>>>\n\
<<vvvv>>>\n\
<vvvvvv>>\n\
vvvvvvvv>\n'
console.log(F(s))

Output
>>>>>>>>v
^>>>>>>vv
^^>>>>vvv
^^^>>vvvv
<<<<<vvvv
^^^^<<vvv
^^^<<<<vv
^^<<<<<<v
^<<<<<<<<


text:
What golfing languages are better suited as an object for genetic programming?
I see GolfScript, Pyth, CJam and similar languages can make compex-ish algorithms in few bytes. This terseness makes think about genetic programming applications (using said languaes as the thing being mutated).
I assume that to make a good GP language, it should have following characteristics:

Programs are typically short;
Random bytes should have high change of being a well-formed program;
Programs should compile and run fast;
Typical programs should not fall into endless loop often, or such loops should be early-detectable in most cases;
Contatenations, extraction of substrings, small modifications should often lead to something related to the original program;
Program should be easy to put in a sandbox (i.e. should not crash the interpreter);
Be turing-complete or near it.

How much languages typically used for golfing suit for genetic programming?

You might want to clarify that you're trying to evolve programs in the target language, as opposed to trying to implement genetic algorithms in a programming language. Also, does it have to be specifically golfing languages? Because Brainfuck for instance is probably a good candidate (and I know it has been used for this purpose). In any case, I'm not really sure this is on topic here. I don't really know which SE it would fit better, because it's sort of open-ended and a bit of a list question. Might be something interesting to discuss in chat though.

I also believe this should go to meta instead of main site,

@Optimizer I don't think this has a place on meta. Meta is for discussions about how we run this site. If anything it might go on SO or Programmers.SE. We don't have machine learning SE yet (there have been two attempts that didn't survive three weeks of beta), where this would probably be most appropriate.

We do have questions like list some well formed questions from main site on meta ..

I'm voting to close this question as off-topic because it is neither a programming challenge, nor is it a question asking for golfing advice. I think this might be on-topic on Stack Overflow or Programmers.SE, but at least on the former it could be too open-ended to be well received.

I think this doesn't hurt. It is an advice question directly related to golfing (although not for golfing itself), and can't be expected to be answered better anywhere else. We may want to close it if it becomes too broad or primarily opinion-based. But seeing the two related questions, I think that is unlikely true.

I would be surprised if any golfing languages were appropriate for genetic programming. Pyth, at least, is very unlikely to form a valid program with random bytes, and I believe the same is true of most golfing languages. This, if nothing else, probably invalidates them as genetic programming languages.

There is a joke about Perl programmer fixing errors in a "programme" typed by mashing random keys on keyboard. For golfing languages I expect higher probability of 20 random bytes being a meaningful program compared to Java or C.

http://en.wikipedia.org/wiki/Malbolge is so complicated that it is easier to generate a program than to write one by hand.

@Vi. I don't dispute that, I just think the ratio is too low for any of these languages to be much good for golfing.

Genetic programming doesn't necessarily require that a large proportion of random strings are valid programs, just that there are at least some potential mutations that are valid.


text:
Correct errors using Hamming(7,4)
The Hamming(7,4) code goes back to 1950. Back then Richard Hamming worked as a mathematician at Bell Labs. Every Friday Hamming set the calculating machines to perform a series of calculation, and collected the results on the following Monday. Using parity checks, these machines were able to detect errors during the computation. Frustrated, because he received error messages way too often, Hamming decided to improve the error detection and discovered the famous Hamming codes.
Mechanics of the Hamming(7,4)
The goal of Hamming codes is to create a set of parity bits that overlap such that a single-bit error (one bit is flipped) in a data bit or a parity bit can be detected and corrected. Only if there occur multiple errors, the Hamming code fails of recovering the original data. It may not notice an error at all, or even correct it falsely. Therefore in this challenge we will only deal with single-bit errors.
As an example of the Hamming codes, we will look at the Hamming(7,4) code. Additionally to 4 bits of data d1, d2, d3, d4 it uses 3 parity bits p1, p2, p3, which are calculated using the following equations:
p1 = (d1 + d2 + d4) % 2
p2 = (d1 + d3 + d4) % 2
p3 = (d2 + d3 + d4) % 2

The resulting codeword (data + parity bits) is of the form p1 p2 d1 p3 d2 d3 d4.
Detecting an error works the following way. You recalculate the parity bits, and check if they match the received parity bits. In the following table you can see, that every variety of a single-bit error yields a different matching of the parity bits. Therefore every single-bit error can be localized and corrected.
error in bit | p1 | p2 | d1 | p3 | d2 | d3 | d4 | no error
-------------|---------------------------------------------
p1 matches   | no | yes| no | yes| no | yes| no | yes
p2 matches   | yes| no | no | yes| yes| no | no | yes
p3 matches   | yes| yes| yes| no | no | no | no | yes

Example
Let your data be 1011. The parity bits are p1 = 1 + 0 + 1 = 0, p2 = 1 + 1 + 1 = 1 and p3 = 0 + 1 + 1 = 0. Combine the data and the parity bits and you get the codeword 0110011.
data bits   |   1 011
parity bits | 01 0
--------------------
codeword    | 0110011

Lets say during a transmission or a computation the 6th bit (= 3rd data bit) flips. You receive the word 0110001. The alleged received data is 1001. You calculate the parity bits again p1 = 1 + 0 + 1 = 0, p2 = 1 + 0 + 1 = 0, p3 = 0 + 0 + 1 = 1. Only p1 matches the parity bits of the codeword 0110001. Therefore an error occurred. Looking at the table above, tells us that the error occurred in d3 and you can recover the original data 1011.
Challenge:
Write a function or a program, that receives a word (7 bits), one of the bits might be wrong, and recover the original data. The input (via STDIN, command-line argument, prompt or function argument) format may be a string "0110001", a list or an array [0, 1, 1, 0, 0, 0, 1] or an integer in MSB 0b0110001 = 49. As described above, the order of the input is p1 p2 d1 p3 d2 d3 d4. The output (via return value or STDOUT) has to be of the same format, but in the order d1 d2 d3 d4. Only return/output the 4 data bits.
This is code-golf. Therefore the shortest code wins.
Test cases:
1110000 -> 1000  # no error
1100000 -> 1000  # error at 1st data bit
1111011 -> 1111  # error at 2nd data bit
0110001 -> 1011  # error at 3rd data bit (example)
1011011 -> 1010  # error at 4th data bit
0101001 -> 0001  # error at 1st parity bit
1010000 -> 1000  # error at 2nd parity bit
0100010 -> 0010  # error at 3rd parity bit

function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=0,c=0,p=-1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);t++;c=p==o?c:t;i=i.replace("{{PLACE}}",c+".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);p=o;$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=45684;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*([^,]+)/
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<link rel=stylesheet type=text/css href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	AuthorLanguageSize

Winners by Language

LanguageUserScore

{{PLACE}}	{{NAME}}{{LANGUAGE}}{{SIZE}}Link

{{LANGUAGE}}{{NAME}}{{SIZE}}Link

Is there a particular reason the last parity bit is given after the first data bit?

@xnor Mathematically it doesn't make any difference, at which position the parity bits are. Historically they are placed on the positions of powers of two. E.g. the Hamming(15,11) has the parity bits at the positions 1, 2, 4 and 8.

@xnor If you take [is_p3_wrong][is_p2_wrong][is_p1_wrong] in base two it gives the position of the incorrect bit in the word. (Based on the table in the question.) This probably will be useful for some algorithms.

Very nice :) When you write "Write a function or a program, that receives a word (7 bits), one of them might be wrong,[...]" I think you mean one of the bits might be wrong but you actually say one of the words might be.

@Lembik Sure, clarified it.

Added the leaderboard snippet, I hope this is ok!

@flawr Sure, thanks.

Octave, 70 66  55 bytes
This function F is setting up the decoding matrix H, finding the error and correcting the position of the error (if there is one). Then it is returning the right data bits. Input is a standard row vector.
@Jakube suggested I should use Octave instead of Matlab where you can use indices on expressions, which makes the whole thing again shorter 11 bytes:
F=@(c)xor(c,1:7==bi2de(mod(c*de2bi(1:7,3),2)))([3,5:7])

Following is the shortest solution in Matlab, as you cannot directly use indexing on expressions. (This works in Octave too, of course.)
Was able to replace addition/mod2 with xor:
f=@(c)c([3,5:7]);F=@(c)f(xor(c,1:7==bi2de(mod(c*de2bi(1:7,3),2))))

Old:
f=@(c)c([3,5:7]);F=@(c)f(mod(c+(1:7==bi2de(mod(c*de2bi(1:7,3),2))),2))

Thank you, but this does not work, unfortunately you can only access variables that way...

Haven't Matlab installed, I only used http://octave-online.net/, where it works. Maybe change the language?

Oh, I was allready suspecting that octave could do so, but then I'm gonna change the language of course, thank you very much!

Piet 50x11 = 550

codel size is 15. Not too concerned about size, but it passed all the tests.

I rather like this given the context of the problem.

@Optimizer "codel size" is essentially the magnification factor of a piet program. Here, each logical pixel (or codel) has been expanded to a 15x15 block to make easier visibility. That is what I mean, not "code size"

ah..... my bad.

Python, 79
f=lambda x,n=0,e=3:e&~-e and f(x,n+1,(n&8)*14^(n&4)*19^(n&2)*21^n%2*105^x)or~-n

Take input and output as numbers with the least significant bit on the right.
Instead of attempting error recovery, we just try encoding every possible message n from 0 to 15 until we get an encoding that's one bit away from what's given. The recursion keeps incrementing n until it finds one that works and returns it. Though there's no explicit termination, it must end within 16 loops.
The expression (n&8)*14^(n&4)*19^(n&2)*21^n%2*105 implements the Hamming matrix bitwise.
To check for a single error, we xor the given message with a computed one to get e, and check if it's a power of two (or 0) with the classic bit-trick e&~-e==0. But, we can't actually assign to the variable e within a lambda, and we refer to it twice in this expression, so we do a hack of passing it as an optional argument to the next recursive step.

JavaScript (ES6), 92 87 81
Function getting and returning an integer in MSB.
The implementation is straightforwrd following @randomra comment:

calc p3wrong|p2wrong|p1wrong (line 2,3,4)
use it as a bit mask to flip the incorrect bit (line 1),
then return just the data bits (last line)

F=w=>(w^=128>>(
  (w^w*2^w*4^w/2)&4|
  (w/8^w^w*2^w/16)&2|
  (w/16^w/4^w^w/64)&1
))&7|w/2&8

Test In Frefox/FireBug console
;[0b1110000,0b1100000,0b1111011,0b0110001,
0b1011011,0b0101001,0b1010000,0b0100010]
.map(x=>x.toString(2)+'->'+F(x).toString(2))

Output
["1110000->1000", "1100000->1000", "1111011->1111", "110001->1011", "1011011->1010", "101001->1", "1010000->1000", "100010->10"]

I really like your compact bitwise operation solution=)

Python 2, 71
f=lambda i,b=3:i&7|i/2&8if chr(i)in'\0%*3<CLUZfip'else f(i^b/2,b*2)

Several characters are unprintable ASCII so here is an escaped version:
f=lambda i,b=3:i&7|i/2&8if chr(i)in'\0\x0f\x16\x19%*3<CLUZfip\x7f'else f(i^b/2,b*2)

Input and output to the function are done as integers.
I'm taking advantage of the fact that the number of valid messages is only 16, and hard-coding them all. Then I try flipping different bits until I get one of those.

Haskell, 152 bytes
a(p,q,d,r,e,f,g)=b$(d+e)#p+2*(d+f)#q+4*(e+f)#r where b 3=(1-d,e,f,g);b 5=(d,1-e,f,g);b 6=(d,e,1-f,g);b 7=(d,e,f,g-1);b _=(d,e,f,g);x#y=abs$(x+g)`mod`2-y

Usage: a (1,1,1,1,0,1,1) which outputs (1,1,1,1)
Straightforward solution: if p<x> does not match, set bit <x> in a number. If this number is 3, 5, 6 or 7, flip the corresponding d<y>.

Can you add some more instructions on how to call your code (for instance using a online compiler like http://ideone.com)? I always get some weird errors (very likely my fault).

@Jakube: save the code into a file, say hamming.hs and load it into the Haskell REPL ghci: ghci hamming.hs. Call the function a as described above. The only online haskell interpreter I know of (http://tryhaskell.org) requires some more code: let  a(p,q, ... 2-y  in a (1,1,1,1,0,1,1)

IA-32 machine code, 36 bytes
Hexdump:
33 c0 40 91 a8 55 7a 02 d0 e1 a8 66 7a 03 c0 e1
02 a8 78 7a 03 c1 e1 04 d0 e9 32 c1 24 74 04 04
c0 e8 03 c3

Equivalent C code:
unsigned parity(unsigned x)
{
    if (x == 0)
        return 0;
    else
        return x & 1 ^ parity(x >> 1);
}

unsigned fix(unsigned x)
{
    unsigned e1, e2, e3, err_pos, data;
    e1 = parity(x & 0x55);
    e2 = parity(x & 0x66);
    e3 = parity(x & 0x78);
    err_pos = e1 + e2 * 2 + e3 * 4;
    x ^= 1 << err_pos >> 1;
    data = x;
    data &= 0x74;
    data += 4;
    data >>= 3;
    return data;
}

x86 CPU automatically calculates the parity of each intermediate result. It has a dedicated instruction jp that jumps or not jumps depending on the parity.
It wasn't specified explicitly in the challenge, but the convenient property of hamming codes is that you can interpret the parity bits as a binary number, and this number indicates which bit was spoiled during transmission. Actually, this number is 1-based, with 0 meaning there were no transmission errors. This is implemented by shifting 1 left by err_pos and then right by 1.
After fixing the transmission error, the code arranges the data bits in the needed order. The code is optimized for size, and it may be unclear at first how it works. To explain it, I denote by a, b, c, d the data bits, and by P, Q and R the parity bits. Then:
    data = x;     // d  c  b  R  a  Q  P
    data &= 0x74; // d  c  b  0  a  0  0
    data += 4;    // d  c  b  a ~a  0  0
    data >>= 3;   // d  c  b  a

Assembly source (fastcall convention, with input in ecx, and output in eax):
    xor eax, eax;
    inc eax;
    xchg eax, ecx;

    test al, 0x55;
    jp skip1;
    shl cl, 1;

skip1:
    test al, 0x66;
    jp skip2;
    shl cl, 2;

skip2:
    test al, 0x78;
    jp skip3;
    shl ecx, 4;

skip3:
    shr cl, 1;
    xor al, cl;

    and al, 0x74;
    add al, 4;
    shr al, 3;

    ret;

APL (Dyalog Extended), 26 25 bytes
(⊤⍳7)(3 5 6 7⊇⊢≠≠.∧∧.=⊣)⊢

Try it online!
-1 byte thanks to @Adám.
A bit shortened further using monadic ⊤.

APL (Dyalog Unicode), 31 30 bytes
⎕{(1<+⌿⍵)/⍺≠⍵∧.=⍨⍵≠.∧⍺}2⊥⍣¯1⍳7

Try it online!
-1 byte thanks to @Adám.
Full program that takes the boolean vector from stdin. Generalized matrix product f.g turns out to be very suitable for decoding Hamming code.
How it works
⎕{(1<+⌿⍵)/⍺≠⍵∧.=⍨⍵≠.∧⍺}2⊥⍣¯1⍳7  ⍝ Full program
                       2⊥⍣¯1⍳7  ⍝ m←3×7 matrix of bit patterns of 1..7
                                ⍝ 0 0 0 1 1 1 1
                                ⍝ 0 1 1 0 0 1 1
                                ⍝ 1 0 1 0 1 0 1
⎕                        ⍝ Take the length-7 boolean vector v from stdin
 {                    }  ⍝ Pass to the inline function; ⍺←v ⋄ ⍵←m
                 ⍵≠.∧⍺   ⍝ Calculate parity for each row of m
            ⍵∧.=⍨        ⍝ Compute which column of m matches the error pattern
          ⍺≠  ⍝ Flip that bit from the codeword (or nothing if no error)
  (1<+⌿⍵)/    ⍝ Extract the data bits from the codeword

⊣∧.=⍨≠.∧ → ≠.∧∧.=⊣

Oops: ⎕{(1<+⌿⍵)/⍺≠⍵∧.=⍨⍵≠.∧⍺}2⊥⍣¯1⍳7


text:
Generate unique non-sequential string of length n without memory of previously generated strings
Scenario:
Imagine a situation where you wish to share a unique alphanumeric code. Perhaps it is a one-time-use coupon code you hand write on business cards, or some other scenario where it is desirable to have a code where mis-keying the entry is unlikely to produce valid result and the another valid code is not readily guessed.
However, when you are issuing these codes you do not have access to the list of codes that have already been issued. Rather, you know only how many have been issued before.
Challenge:
Write a function that generates a unique string of length n, subject to the following constraints:

Available Characters: Each character in resultant string shall be from a configurable list of allowed values, which may be "hard-coded" into the algorithm.

Sample List: A, B, C, D, E, F, G, H, J, K, L, M, N, P, Q, R, S, T, U, V, W, X, Z, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 (A-Z and 0-9, omitting "I" and "J")

Configurable Length Output: The length n of the generated string shall be configurable within the algorithm, for n<=8.
Input: A seed is available (unique sequential positive integer >=1 and up to 10 digits)
Stateless: The algorithm has no memory of previously generated strings (no database calls)
Repeatable: The same seed shall yield the same result
Unordered Output: Sequential seed values shall not generate strings in any obvious order (that is to say, results should superficially "appear" random)

For example, 1:"AAAA", 2:"AAAB", 3:"AAAC", ... would NOT qualify, while 1:"RR8L", 2:"1D9R", 3:"TXP3", ... is on the right track.
Note: While this criterion is admittedly subjective, "degree of randomness" is not intended to be the core aspect of this function. Given the Popularity Contest format, I'll leave it up to the community to decide whether a pattern is too obvious.

Unique Output: String shall be unique, at least within limitations of available characters and requested string length. Therefore, each possible permutation is to be used exactly once before any combination may be reused.

For example, if configured to generate a string of length n=5 and the available characters include A-Z and 0-9 except for "O", "I" (34 possible characters), then the string may not repeat between seed>=1 and seed<=45,435,424.
However, if length n=4 with 34 available characters, then the same string need only be unique on seed>=1 and seed<=1,336,336

Winning Criteria:
Popularity Contest - Submission with the most upvotes will be selected as the winner no sooner than two weeks after the first valid solution. Please upvote any and all submissions you feel adequately meet the above criteria.

Welcome to PPCG. I'm afraid your very dry spec makes me think this is homework! If it is a genuine challenge, some pointers: 1. Why an algorithm and not a program/function? 2."Code challenge" means you must specify an objective criterion for the winning answer. Other tags eg "code golf" (shortest code) have implied winning criterions. 3. why not specify the allowable characters in the question? 4. what is the maximum length (and by extension what is the maximum seed value? do all possible output strings have to be generatable?)  5. It's v. similar to some other questions, it may be a duplicate

Forgive me, while I have visited PPCG before, I'm not yet familiar with all of the guidelines and traditions here so I certainly appreciate your feedback.  No, it is not homework. The idea came up when pondering how one might generate a unique record "lookup key" where other record locators such as barcodes, serial numbers, etc. While this could easily be achieved by querying a database of previously generated lookup keys, the idea of eliminating that option posed a unique challenge I thought others may find intriguing. I didn't find other questions quite like this one, so I posted it here.

how is it supposed to be stateless but avoid using previously used strings?

@feersum what he means by stateless is that it doesn't store previously used strings. I see no problem with that bit. I have a minor issue with "appear to be random" as this is highly open to interpretation. A simple substitution cipher might suffice, (though a more diligent entry might enhance it by having the key depend on the previous character.)

That's the main point of the challenge - to devise a way to generate a unique string without knowing what came before. The results need not be random, but simply have that appearance by not occurring in any obvious order.

@cragmonkey the reason your question was put on hold is that it lacks a winning criterion. You can edit to add one (such as code golf) and it will go to the review queue. I would suggest you ask for a program/function, not an algorithm, and nail down the other particulars such as maximum seed value and word length. My general feeling was that encryption and random number generators have been done to death, but its true I can't find your exact question and a variable base (ie number of allowed characters) does rule out many seeded rng algorithms. I dont know how this question will be received.

Either way, stick around and answer a few questions to find out what we're about. Writing a good challenge is hard. Feel free to post your next challenge in the sandbox for review http://meta.codegolf.stackexchange.com/q/2140/15599

This now has a winning criterion, and I think it should be reopened.

Is the seed the same as the number of strings issued before, or are they 2 separate inputs?

@glebm They're the same input.

C(++) - we don't need no friggin' primes
The problem is to generate a different permutation of n characters taken from an a size alphabet for each seed value.
There are an such permutations, and they can be represented as values of a n digits number in base a.
The number of bits necessary to represent all these values is log2(an), rounded up.
We have at most 8 characters per code, and the alphabet contains at most 256 characters, so a 64 bits word is just what we need to cover all possible codes with all possible alphabets.
Now we just need something that maps all possible 232 seed values to the possible range of code values (and looks random enough).
I settled for a basic 32 bits reversal, which gives highest variability for low seed values.
If the possible codes range is smaller than the seed's, there will be duplicates anyway, and the codes will be like the n first digits of a greater number.
If the 232 seed values are not enough to cover all code values, the scrambled seed is extended to the smallest power of two inferior to code max value, by injecting 0s in the lower bits.
This should spread the range of code values while guaranteeing no duplicates.
However, the last digit will have a slightly lower frequency due to the rounding to a power of 2.
If alphabet size is much greater than 2, the difference will be hardly noticeable.
The scrambled seed is then converted as a number in base a, the digits being the symbols of the alphabet.
A few (pseudo) random thoughts
The big weakness of this method is that it won't work well with alphabets whose size is a power of two. The apparent randomness is due to the non-integer number of bits needed to encode a digit.
On second thought maybe we do need some friggin primes after all...
At any rate, even the most magnificent pseudo-random repartition is useless as far as data protection is concerned, since the encryption method is stateless and could be easily cracked by brute-force.
The code
I used the excellent bit shuffling generator of Mr. Jasper Neumann to produce the bit reverser, though other solutions are possible.
I compiled with g++4.8 under MinGW/Win7, but the code is nothing but glorified C and should work with any C++ compiler.
#include <cstdlib> // atoi
#include <cstdio>  // printf
#include <cmath>   // pow

#define Alphabet "ABCDEFGHKLMNOPQRSTUVWXYZ0123456789"
#define Length 8

unsigned bit_permute_step_simple(unsigned x, unsigned m, unsigned shift)
{
  return ((x & m) << shift) | ((x >> shift) & m);
}

unsigned shuffle (unsigned x)
{
    x = bit_permute_step_simple(x, 0x55555555, 1);  // Bit index complement 0
    x = bit_permute_step_simple(x, 0x33333333, 2);  // Bit index complement 1
    x = bit_permute_step_simple(x, 0x0f0f0f0f, 4);  // Bit index complement 2
    x = bit_permute_step_simple(x, 0x00ff00ff, 8);  // Bit index complement 3
    x = bit_permute_step_simple(x, 0x0000ffff, 16);  // Bit index complement 4
    return x;
}

#define Base (sizeof(Alphabet)-1)
typedef char Code[Length+1];

void gen_code (unsigned seed, Code code)
{
    // shuffle seed bits (the inversion is to avoid zero value for seed = 0)
    unsigned long long scrambled = shuffle(~seed);

    // if maximal code size is less than seed max value, there will be duplicates anyway
    int extra_bits = floor(Length * log(Base)/log(2)) - 32;
    if (extra_bits > 0) scrambled <<= extra_bits;

    // basic base conversion.
    // The last code digit might have a slightly lower frequency than others
    int i;
    for (i = 0 ; i != Length ; i++)
    {
        int digit = scrambled % Base;
        code[i] = Alphabet[digit];
        scrambled /= Base;
    }
    code[i] = '\0';
}

int main (int argc, char * argv[])
{
    if (argc != 2) exit(-1);
    unsigned seedm = atoi(argv[1]);
    Code code;

    for (unsigned seed = 0 ; seed != seedm ; seed++)
    {
        gen_code (seed, code);
        printf ("code (%u) = %s\n", seed, code);
    }

    return 0;
}

The main() prints a specified number of codes for consecutive seeds.
Sample output:
n=8, alphabet = ABCDEFGHKLMNOPQRSTUVWXYZ0123456789
code (0) = 215GVK7B
code (1) = MPPT46CX
code (2) = 4AF2E28Y
code (3) = GLGGAS6W
code (4) = U3MSPN2Y
code (5) = CR42Y97H
code (6) = WCWB943L
code (7) = CZW2XAAB
code (8) = UBHMSV6C
code (9) = CZ0W1HCY
code (10) = WMS5BD8Z
code (11) = 8UTL725X
code (12) = MDYVMY1Z
code (13) = 40F6VM7K
code (14) = OO7E6F3M
code (15) = U5L28BA5
code (16) = 08GMUH56
code (17) = KW0W35AS
code (18) = 2HS5D16T
code (19) = ESTL9Q4R

n=4, alphabet = ABCDE
code (0) = AEBD
code (1) = CEAE
code (2) = BEDD
code (3) = DECE
code (4) = DBAB
code (5) = ACEB
code (6) = EBCB
code (7) = BCBC
code (8) = ECDE
code (9) = BDCA
code (10) = ADAA
code (11) = CDEA
code (12) = CACC
code (13) = EABD
code (14) = DAEC
code (15) = ABDD
code (16) = CDCB
code (17) = EDBC
code (18) = DDEB
code (19) = AEDC

Python 3:
The main task of this challenge is to find a bijection between [0, 1, ..., #alphabet^length-1] to itself, which appears to be random.
I stumbled about linear congruential generators, which generate a permutations of the numbers, when the parameters of it satisfy some properties. But interestingly the resulting strings didn't looked random at all. So I decided to do some own stuff.
One obvious bijection is the function f(x) = (a * x + c) % m, where m = #alphabet^length, a and m are random numbers with gcd(a,m) = 1. Since the function has to be repeatable, I used the fixed values a = 0.4 * m and c = 0.3 * m. Of course this is nowhere near random.
The second bijection is based on primitive roots. When p is a prime (or 4, or (prime>2)^alpha, or 2*(prime>2)^alpha), then there exists values g, where g^i generates a permutation of all numbers. Therefore I search for next primes smaller than m and g is approximately m/3. Since p is smaller than m, not all numbers are effected by this approach, I have to use it twice, once for the first p numbers and once for the last p numbers.
My program first applies the first and than the second bijection. And the result looks quite random to me. E.g. the output for the alphabet ABC and length 3 is: BCB, ACA, BCC, BBC, CCA, ABC, CAA, ABB, CAB, AAC, AAA, BAC, BBB, CBC, BAB, ACB, BBA, BCA, CBA, CCC, AAB, ABA, CAC, BAA, ACC, CCB, CBB.
from fractions import gcd
from numbthy import is_prime, is_primitive_root

def random_linear_congruence(length, seed):
    multiplier = int(length * 0.4)
    while gcd(multiplier, length) > 1:
        multiplier += 1

    start_value = int(length * 0.3)
    return (start_value + seed*multiplier) % length

def random_primitive_root(length, seed):
    prime = length
    while not is_prime(prime):
        prime -= 1

    prim_root = prime // 3
    while not is_primitive_root(prim_root, prime):
        prim_root = (prim_root - 1 ) % prime

    random_number = seed
    if 0 < seed < prime:
        random_number = (prim_root ** seed) % prime

    t = length - prime
    if random_number > t:
        random_number = ((prim_root ** (random_number - t)) % prime) + t

    return random_number

def unique_nonsenquential_string(alphabet, length, seed):
    alphabet = sorted(alphabet)
    modulus = len(alphabet)**length

    random_number = seed
    random_number = random_linear_congruence(modulus, random_number)
    random_number = random_primitive_root(modulus, random_number)

    # convert to base len(alphabet)
    word = []
    for i in range(length):
        word.append(random_number % len(alphabet))
        random_number //= len(alphabet)

    return ''.join(map(lambda x: alphabet[x], word))

outputs = set()
alphabet = "ABC"
length = 3
for seed in range(len(alphabet)**length):
    random_string = unique_nonsenquential_string(alphabet, length, seed)
    outputs.add(random_string)
    print("Seed {:2d}: {}".format(seed, random_string))
if len(outputs) == len(alphabet)**length:
    print("Unique output")

You can find numbthy.py here: Basic Number Theory functions implemented in Python

Simplicity (python 2)
This may not be in the spirit of the challenge, but it works, and is far simpler than the other algorithms.
import random
from string import uppercase

def unique_code(n, seed, alphabet):
    pre_state = random.getstate() #so we don't interfere outside scope
    random.seed(seed)
    code = ''.join([random.choice(alphabet) for _ in xrange(n)])
    random.setstate(pre_state)
    return code

length = 4
for i in range(20):
    print '{} [seed {:d}]'.format(unique_code(length, i, uppercase), i)

Running this code gives:
VTKG [seed 0]
DWTG [seed 1]
YYBC [seed 2]
GOJP [seed 3]
GCKE [seed 4]
QTUY [seed 5]
UVMG [seed 6]
IDQB [seed 7]
FZDS [seed 8]
MJDW [seed 9]
OLPF [seed 10]
LOYM [seed 11]
MRRD [seed 12]
GRRW [seed 13]
CSQY [seed 14]
ZATE [seed 15]
JMKL [seed 16]
NUYH [seed 17]
ERIF [seed 18]
RUNN [seed 19]

Nice idea, but it doesn't satisfy the unique output constraint.

Can confirm. Try it with length 3 and alphabet abc, bbb occurs twice (at least on my system)


text:
Rock Paper Scissors with a twist
The challenge
This challenge is going to be a classic king of the hill game of RPS. You must write a program that takes two command line arguments, a string of all the moves that you have made, and a string of all the moves that your opponent has made. The program will then return either 'r', 'p' or 's' for rock, paper and scissors respectively. Your opponent's program will do the same thing, and the winner will get +1 point. The winner is determined by the following picture.
In the event of a tie, (Both throw the same move) no points will be awarded. If you fail to throw a valid move within 1/2 a second, or if you throw a move other than 'r', 'p' or 's', the other player will be awarded 2 points, and an 'x' will be added to the string of all of your moves. After 500 rounds, the program with more points will be awarded 1 win. If there is a tie after 500 rounds, it will go into sudden death mode. (First program to get any more points wins) The controller program (Which I haven't written yet, but I will get to) will keep track of calling the programs, keeping track of score and enforcing certain rules.
The twist
Now here is the part that makes it interesting. You must do it in a language that you have little to no experience with. I realize that this is highly subjective and there is nothing stopping someone from using a language that they already know very well, so this is on the honor system. The whole point of this challenge is to encourage people to experiment with languages that they wouldn't normally ever learn anything about. Also, I'm hoping this will be a little bit like code review. So the Java experts will comment on my answer that totally botches everything about Java and I learn a little bit more. And then when somebody who's never touched python before writes an answer in python, I will give them useful tips for how to improve their code, etc.
Rules

This isn't exactly a rule, since there is no way to enforce it, but don't use a language that you have already know. I will let you define what counts as "already knowing a language" but the spirit of the challenge is that everybody gets to try something new.
Every entrant will play every other entrant exactly one time. So if there were four entrants named a, b, c and d, we would have in this order, a vs b, a vs c, a vs d, b vs c, b vs d, c vs d.
You can not copy other entrants code to predict their behavior. You can try to predict entrants behavior, (e.g. analyzing their moves, looking for patterns etc.) but you cannot use their code directly.
Multiple submissions are not only allowed, they are encouraged! However, every submission by the same person must be in a different language. Also, no tag-teaming of any sort. Any entrants that attempt tag-teaming will have all of their entrances removed.

Is the removal of lizard and spock, and the addition of new languages not enough?

As you say, there is no way to objectively enforce the first rule, so I think it's fairly insubstantial to the challenge, which makes this a duplicate of the existing RPSLV. Furthermore, I don't think it's a good idea to post a KotH before the controller is written. Despite the simplicity of this challenge, you might encounter issues with the challenge design once you write the controller, at which point it would be too late to amend the challenge. I recommend you use the sandbox next time.

I like to imagine that people would enjoy the challenge and novelty of using a language that they haven't used before. Also, a quick scan of their profile would reveal whether or not they've answered a question in X language before.

Learning through having fun is precisely why I am here, so I appreciate the idea of using a new language (despite the problems of enforcing it.) However, we really need to see the controller.

What is the bigger problem with the question, the lack of a controller, or the inability to objectively enforce the first rule?

I'd probably vote to reopen if you write a controller.


text:
Apportionment paradox
Given:

A natural number S.
A list of N rational weights W that sum to 1.

Return a list L of N non-negative integers, such that:
(1) sum(L) = S
(2) sum((S⋅W_i - L_i)^2) is minimal

In other words, approximate S⋅W_is with integers as closely as possible.
Examples:
1 [0.4 0.3 0.3] = [1 0 0]
3 [0 1 0] = [0 3 0]
4 [0.3 0.4 0.3] = [1 2 1]
5 [0.3 0.4 0.3] = [2 2 1] or [1 2 2] but not [1 3 1]
21 [0.3 0.2 0.5] = [6 4 11]
5 [0.1 0.2 0.3 0.4] = [1 1 1 2] or [0 1 2 2]
4 [0.11 0.3 0.59] = [1 1 2]
10 [0.47 0.47 0.06] = [5 5 0]
10 [0.43 0.43 0.14] = [4 4 2]
11 [0.43 0.43 0.14] = [5 5 1]

Rules:

You can use any input format at all, or just provide a function that accepts the input as arguments.

Background:
This problem comes up when displaying S of different types of items in different proportions Wi with regard to the types.
Another example of this problem is proportional political representation, see the apportionment paradox. The last two test cases are known as Alabama paradox.

As a statistician, I recognised this problem as equivalent to a
  problem encountered in identifying sample sizes when conducting a
  stratified sample. In that situation, we want to make the proportion
  of each stratum in the sample equal to the proportion of each stratum
  in the population.
  — @tomi

Could you say in words what the task is? I'm having trouble decompressing the expressions into something intuitive.

Both should be ≤, fixed. The task is to present an integer as a sum of integers based on weights. The remainder should distribute favoring the highest weights, though I am not sure this requirement is encoded correctly? This is interesting because round(A + B) != round(A) + round(B), a short solution requires an insight on what's going on here.

In other words, approximate S⋅W[i] with integers as closely as possible.

Maybe change the rules to minimize the sum of the distances L[i] - S*W[i] squared, instead of rule 2 and rule 3. This would approximate S*W[i].

@Jakube Or replace rule 3 by L[i]>=L[j] ==> W[i]>=W[j].

@Zgarb Yes, that would work too. But if he want's to approximate S*W[i], minimizing the distances is better.

@Jakube Great catch and follow-up fix, this is exactly it, thank you. Updated to define a distance (I used abs but sqr should lead to the same lists being correct).

@glebm I would still suggest sum(abs(S⋅W[i] - L[i])^2). I think there are examples, where it approximates S*W[i] better.
And you now can remove rule 2, the minimizing rule takes care of this already.

@glebm I think the question is fine now. Next time use the Sandbox in Meta before posting it  here.

[0 3 0] do not sum to 1

@aditsu oops, introduced a typo when improving the examples. thanks!

Also [0 1 2 2]  is another possible solution for 5 [0.1 0.2 0.3 0.4]

Maybe you should add an example for 1 [0.4 0.3 0.3]

APL, 21
{{⍵+1=⍋⍋⍵-⍺}⍣⍺/⍺0×⊂⍵}

This is a translation from aditsu's 37 byte CJam answer.
Test it online.
Explanation
 {      ⍵-⍺}            ⍝ Right argument - left argument.
 {  1=⍋⍋⍵-⍺}            ⍝ Make one of the smallest number 1, others 0.
 {⍵+1=⍋⍋⍵-⍺}            ⍝ Add the result and the right argument together.
 {⍵+1=⍋⍋⍵-⍺}⍣⍺          ⍝ Repeat that S times. The result of each iteration is the new right argument.
                  ⊂⍵    ⍝ Return enclosed W, which is taken as one unit in APL.
               ⍺0×⊂⍵    ⍝ Return S*W and 0*W.
{{⍵+1=⍋⍋⍵-⍺}⍣⍺/⍺0×⊂⍵}   ⍝ Make S*W the left argument, 0*W the right argument in the first iteration.

Python 2, 95 83 132 125 143
My first (and second) (and third) algorithm had problems so after a (another!) rewrite and more testing, here is (I really hope) a correct and fast solution:
def a(b,h):
 g=h;c=[];d=[]
 for w in b:f=int(w*h);d+=[f];c+=[h*w-f];g-=f
 if g:
  for e in sorted(c)[-g:]:i=c.index(e);c[i]=2;d[i]+=1
 return d

The source before the minifier now looks like:
# minified 143 bytes
def golfalloc(weights, num):
    # Tiny seq alloc for golfing
    gap = num;
    errors = [];
    counts = []
    for w in weights :
        count = int(w*num);
        counts += [count];
        errors += [num*w - count];
        gap -= count
    if gap:
        for e in sorted(errors)[-gap:] :
            i = errors.index(e);
            errors[i] = 2;
            counts[i] += 1
    return counts

The tests return:
Pass                    Shape    N               Result Error                        AbsErrSum
ok            [0.4, 0.3, 0.3]    1            [1, 0, 0] -0.60,+0.30,+0.30                 1.20
ok                  [0, 1, 0]    3            [0, 3, 0] +0.00,+0.00,+0.00                 0.00
ok            [0.3, 0.4, 0.3]    4            [1, 2, 1] +0.20,-0.40,+0.20                 0.80
ok            [0.3, 0.4, 0.3]    5            [2, 2, 1] -0.50,+0.00,+0.50                 1.00
ok            [0.3, 0.2, 0.5]   21           [6, 4, 11] +0.30,+0.20,-0.50                 1.00
ok       [0.1, 0.2, 0.3, 0.4]    5         [1, 1, 1, 2] -0.50,+0.00,+0.50,+0.00           1.00
ok          [0.11, 0.3, 0.59]    4            [1, 1, 2] -0.56,+0.20,+0.36                 1.12
ok         [0.47, 0.47, 0.06]   10            [5, 5, 0] -0.30,-0.30,+0.60                 1.20
ok         [0.43, 0.43, 0.14]   10            [4, 4, 2] +0.30,+0.30,-0.60                 1.20
ok         [0.43, 0.43, 0.14]   11            [5, 5, 1] -0.27,-0.27,+0.54                 1.08

This algorithm is similar to other answers here. It is O(1) for num so it has the same run time for integers 10 and 1000000. It is theoretically O(nlogn) for the number of weights (because of the sort). If this withstands all other tricky input cases, it will replace the algorithm below in my programming toolbox.
Please don't use that algorithm with anything not golfy. I made compromises in speed to minimise source size. The following code uses the same logic but is much faster and more useful:
def seqalloc(anyweights, num):
    # Distribute integer num depending on weights.
    # weights may be non-negative integers, longs, or floats.
    totalbias = float(sum(anyweights))
    weights = [bias/totalbias for bias in anyweights]
    counts = [int(w*num) for w in weights]
    gap = num - sum(counts)
    if gap:
        errors = [num*w - q for w,q in zip(weights, counts)]
        ordered = sorted(range(len(errors)), key=errors.__getitem__)
        for i in ordered[-gap:]:
            counts[i] += 1
    return counts

The value of num doesn't affect speed significantly. I have tested it with values from 1 to 10^19. The execution time varies linearly with the number of weights. On my computer it takes 0.15 seconds with 10^5 weights and 15 seconds with 10^7 weights. Note that the weights are not restricted to fractions that sum to one. The sort technique used here is also about twice as fast as the traditional sorted((v,i) for i,v in enumerate...) style.
Original Algorithm
This was a function in my toolbox, modified a little for golf. It was originally from a SO answer. And it is wrong.
def seqalloc(seq, num):
    outseq = []
    totalw = float(sum(seq))
    for weight in seq:
        share = int(round(num * weight / totalw)) if weight else 0
        outseq.append(share)
        totalw -= weight
        num -= share
    return outseq

It gives an approximation, but is not always correct, although the sum(outseq) == num is maintained. Fast but not recommended.
Thanks to @alephalpha and @user23013 for spotting the errors.
EDIT: Set totalw (d) to be 1 as OP specifies the sum of weights will always be 1. Now 83 bytes.
EDIT2: Fixed bug found for [0.4, 0.3, 0.3], 1.
EDIT3: Abandoned flawed algorithm. Added better one.
EDIT4: This is getting ridiculous. Replaced with correct (I really hope so) algorithm.
EDIT5: Added not-golfy code for others that may like to use this algorithm.

a([0.4, 0.3, 0.3], 1) returns [0, 1, 0], while the correct answer is [1, 0, 0].

This solution is not correct, I've added alephalpha's example to the post.

I have been using this a while with this bug. Ouch. I will edit with a fixed algorithm soon.

Should be fixed now.

Still wrong. a([0.11,0.3,0.59],4) returned [0, 1, 3]. Should be [1, 1, 2].

Answer changed with a new algorithm that passes every test I could throw at it. Thanks @user23013 for picking up that error.

f([0.47,0.47,0.06],10) returned [5, 4, 1]. Should be [5, 5, 0].

How on earth do you guys keep coming up with these test cases!?

@Sp3000 My first test case is derived from [0.4/4, 1.3/4, 2.3/4], where sorting obviously doesn't fix the problem. I think the new program just work like others if total*w+w is changed to num*w. And I found a case where it makes differences. In fact there is already a wikipedia page which gives a case f([6./14,6./14,2./14],11).

Never seen someone bowl so much!

@user23013, I have updated the algorithm and checked and tested as much as I can. I am hoping this one is bullet proof. After you mentioned that wikipedia reference, I tested with that too. If I don't get it right this time, they will come and take away my computer science qualifications!

@Optimizer. I am not familiar with the "bowl" reference.

I think it's correct now.

@CarpetPython I went through a similar process with this algorithm, and this is how I came up with this problem. If they take away your license, they should take mine too :)

Mathematica, 67 50 46 45 chars
f=(b=⌊1##⌋;b[[#~Ordering~-Tr@#&[b-##]]]++;b)&

Ungolfed:
f[s_, w_] := Module[{a = s*w, b, c, d},
  b = Floor[a];
  c = b - a;
  d = Ordering[c, -Total[c]];
  b[[d]] += 1;
  b]

Example:
f[5,{0.1,0.2,0.3,0.4}]

{1, 1, 1, 2}

My goodness, that's short, considering it's Mathematica!

CJam - 37
q~:W,0a*\:S{[_SWf*]z::-_:e<#_2$=)t}*p

Try it online
Explanation:
q~             read and evaluate the input
               (pushing the number and the array on the stack)
:W,            save the array in variable W and calculate its length (N)
0a*            make an array of N zeros (the initial "L")
\:S            swap it with the number and save the number in S
{…}*           execute the block S times
    [_SWf*]    make a matrix with 2 rows: "L" and S*W
    z          transpose the matrix, obtaining rows of [L_i S*W_i]
    ::-_       convert to array of L_i-S*W_i and duplicate
    :e<        get the smallest element
    #          find its index in the unsorted array,
               i.e. the "i" with the largest S*W_i-L_i
    _2$=)t     increment L_i
p              print the result nicely

Notes:

The complexity is about O(S*N), so it gets really slow for large S
CJam is sorely lacking arithmetic operators for 2 arrays, something I plan to implement later

Different idea - 46
q~:Sf*_:m[_:+S\-@[1f%_,,]z{0=W*}$<{1=_2$=)t}/p

Try it online
This is much more straightforward and efficient, but alas, quite a bit longer.
The idea here is to start with L_i=floor(S*W_i), determine the difference (say D) between S and their sum, find the D indices with the largest fractional part of S*W_i (by sorting and taking top D) and increment L_i for those indices. Complexity O(N*log(N)).

Now there is the O(N) :e<.

@user23013 oh yeah, for the first program, thanks

That was quick! Congrats

For those wondering, replacing the sort with a linear time selection algorithm would yield O(n) instead of the actual O(nlogn) caused by the sort: Find the D-th largest element, P, in O(N), then increment elements that are ≥P D times (O(N) since D <= N).

@glebm that's pretty cool, but I think there is a problem if multiple elements have the same value (P). Maybe you can solve it in 2 passes then: first increment and count the elements >P, then you know how many elements =P are needed. Or if you can get that information from the selection algorithm, even better.

JavaScript (ES6) 126 130 104 115 156 162 194
After all the comments and test cases in @CarpetPython's answer, back to my first algorithm. Alas, the smart solution does not work.
Implementation shortened a little, it still tries all the possible solutions, calc the squared distance and keep the minimum.
Edit For each output element of weight w, 'all' the possible values are just 2: trunc(w*s) and trunc(w*s)+1, so there are just (2**elemensts) possible solutions to try.
Q=(s,w)=>
  (n=>{
    for(i=0;
        r=q=s,(y=i++)<1<<w.length;
        q|r>n||(n=r,o=t))
      t=w.map(w=>(f=w*s,q-=d=0|f+(y&1),y/=2,f-=d,r+=f*f,d));
  })()||o

Test In Firefox/FireBug console
;[[ 1,  [0.4, 0.3, 0.3]      ]
, [ 3,  [0, 1, 0]            ]
, [ 4,  [0.3, 0.4, 0.3]      ]
, [ 5,  [0.3, 0.4, 0.3]      ]
, [ 21, [0.3, 0.2, 0.5]      ]
, [ 5,  [0.1, 0.2, 0.3, 0.4] ]
, [ 4,  [0.11, 0.3, 0.59]    ]
, [ 10, [0.47, 0.47, 0.06]   ]
, [ 10, [0.43, 0.43, 0.14]   ]
, [ 11, [0.43, 0.43, 0.14]   ]]
.forEach(v=>console.log(v[0],v[1],Q(v[0],v[1])))

Output
1 [0.4, 0.3, 0.3] [1, 0, 0]
3 [0, 1, 0] [0, 3, 0]
4 [0.3, 0.4, 0.3] [1, 2, 1]
5 [0.3, 0.4, 0.3] [1, 2, 2]
21 [0.3, 0.2, 0.5] [6, 4, 11]
5 [0.1, 0.2, 0.3, 0.4] [0, 1, 2, 2]
4 [0.11, 0.3, 0.59] [1, 1, 2]
10 [0.47, 0.47, 0.06] [5, 5, 0]
10 [0.43, 0.43, 0.14] [4, 4, 2]
11 [0.43, 0.43, 0.14] [5, 5, 1]

That's a smarter solution. Single pass on weigth array.
For each pass i find the current max value in w. I change this value in place with the weighted integer value (rounded up), so if s==21 and w=0.4, we  got 0.5*21 -> 10.5 -> 11. I store this value negated, so it can't be found as max in the next loop. Then I reduce the total sum accordingly (s = s-11) and also reduce the total of the weigths in variable f.
The loop ends when ther is no max above 0 to be found (all the values != 0 have been managed).
At last I returns the values changed to positive again.
Warning this code modifies the weights array in place, so it must be called with a copy of original array
F=(s,w)=>
 (f=>{
  for(;j=w.indexOf(z=Math.max(...w)),z>0;f-=z)
    s+=w[j]=-Math.ceil(z*s/f);
 })(1)||w.map(x=>0-x)

My first try
Not so a smart solution. For every possible result, it evaluates the difference, and keeps the minimum.
F=(s,w,t=w.map(_=>0),n=NaN)=>
  (p=>{
    for(;p<w.length;)
      ++t[p]>s?t[p++]=0
      :t.map(b=>r+=b,r=p=0)&&r-s||
        t.map((b,i)=>r+=(z=s*w[i]-b)*z)&&r>n||(n=r,o=[...t])
  })(0)||o

Ungolfed And explained
F=(s, w) =>
{
  var t=w.map(_ => 0), // 0 filled array, same size as w
      n=NaN, // initial minumum NaN, as "NaN > value"  is false for any value
      p, r
  // For loop enumerating from [1,0,0,...0] to [s,s,s...s]
  for(p=0; p<w.length;)
  {
    ++t[p]; // increment current cell
    if (t[p] > s)
    {
      // overflow, restart at 0 and point to next cell
      t[p] = 0;
      ++p;
    }
    else
    {
      // increment ok, current cell is the firts one
      p = 0;
      r = 0;
      t.map(b => r += b) // evaluate the cells sum (must be s)
      if (r==s)
      {
        // if sum of cells is s
        // evaluate the total squared distance (always offset by s, that does not matter)
        t.map((b,i) => r += (z=s*w[i]-b)*z)
        if (!(r > n))
        {
          // if less than current mininum, keep this result
          n=r
          o=[...t] // copy of t goes in o
        }
      }
    }
  }
  return o
}

CJam, 48 bytes
A straight forward solution to the problem.
q~:Sf*:L,S),a*{m*{(+}%}*{1bS=},{L]z::-Yf#:+}$0=p

Input goes like
[0.3 0.4 0.3] 4

Explanation:
q~:S                                 "Read and parse the input, store sum in S";
    f*:L                             "Do S.W, store the dot product in L";
         S),                         "Get array of 0 to S";
        ,   a*                       "Create an array with N copies of the above array";
              {m*{(+}%}*             "Get all possible N length combinations of 0 to S ints";
                        {1bS=},      "Filter to get only those which sum up to S";
{L]z::-Yf#:+}$                       "Sort them based on (S.W_i - L_i)^2 value";
 L                                   "Put the dot product after the sum combination";
  ]z                                 "Wrap in an array and transpose";
    ::-                              "For each row, get difference, i.e. S.W_i - L_i";
       Yf#                           "Square every element";
          :+                         "Take sum";
              0=p                    "After sorting on sum((S.W_i - L_i)^2), take the";
                                     "first element, i.e. smallest sum and print it";

Try it online here

Pyth: 40 bytes
Mhosm^-*Ghded2C,HNfqsTGmms+*G@Hb}bklHyUH

This defines a function g with 2 parameters. You can call it like Mhosm^-*Ghded2C,HNfqsTGmms+*G@Hb}bklHyUHg5 [0.1 0.2 0.3 0.4.
Try it online: Pyth Compiler/Executor
Explanation:
mms+*G@Hb}bklHyUH     (G is S, H is the list of weights)
m             yUH    map each subset k of [0, 1, ..., len(H)-1] to:
 m          lH          map each element b of [0, 1, ..., len(H)-1] to:
    *G@Hb                  G*H[b]
   +     }bk               + b in k
  s                       floor(_)

This creates all possible solutions L, where L[i] = floor(S*W[i]) or L[i] = floor(S*W[i]+1). For instance, the input 4 [0.3 0.4 0.3 creates [[1, 1, 1], [2, 1, 1], [1, 2, 1], [1, 1, 2], [2, 2, 1], [2, 1, 2], [1, 2, 2], [2, 2, 2]].
fqsTG...
f    ... only use the solutions, where
 qsTG       sum(solution) == G

Only [[2, 1, 1], [1, 2, 1], [1, 1, 2]] remain.
Mhosm^-*Ghded2C,HN
  o                  order the solutions by
   s                   the sum of
    m         C,HN       map each element d of zip(H, solution) to
     ^-*Ghded2           (G*d[0] - d[1])^2
 h                   use the first element (minimum)
M                    define a function g(G,H): return _

Mathematica 108
s_~f~w_:=Sort[{Tr[(s*w-#)^2],#}&/@
Flatten[Permutations/@IntegerPartitions[s,{Length@w},0~Range~s],1]][[1,2]]

f[3, {0, 1, 0}]
f[4, {0.3, 0.4, 0.3}]
f[5, {0.3, 0.4, 0.3}]
f[21, {0.3, 0.2, 0.5}]
f[5, {0.1, 0.2, 0.3, 0.4}]

{0, 3, 0}
{1, 2, 1}
{1, 2, 2}
{6, 4, 11}
{0, 1, 2, 2}

Explanation
Ungolfed
f[s_,w_]:=
Module[{partitions},
partitions=Flatten[Permutations/@IntegerPartitions[s,{Length[w]},Range[0,s]],1];
Sort[{Tr[(s *w-#)^2],#}&/@partitions][[1,2]]]

IntegerPartitions[s,{Length@w},0~Range~s] returns all the integer partitions of s, using elements taken from the set {0, 1, 2, ...s} with the constraint that the output should contain the same number of elements as in the set of weights, w.
Permutations gives all of the ordered arrangements of each integer partition.
{Tr[(s *w-#)^2],#} returns a list of ordered pairs, {error, permutation}
for each permutation.
Sort[...] sorts the list of {{error1, permutation1},{error2, permutation2}...according to the size of the error.
[[1,2]]] or Part[<list>,{1,2}] returns the second item of the first element in the sorted list of {{error, permutation}...}.  In other words, it returns the permutation with the smallest error.

R, 85 80 76
Uses the Hare Quota method.
Removed a couple after seeing the spec that W will sum to 1
function(a,b){s=floor(d<-b*a);s[o]=s[o<-rev(order(d%%1))[0:(a-sum(s))]]+1;s}

Test run
> (function(a,b){s=floor(d<-b/(sum(b)/a));s[o]=s[o<-rev(order(d%%1))[0:(a-sum(s))]]+1;s})(3,c(0,1,0))
[1] 0 3 0
> (function(a,b){s=floor(d<-b/(sum(b)/a));s[o]=s[o<-rev(order(d%%1))[0:(a-sum(s))]]+1;s})(1,c(0.4,0.3,0.3))
[1] 1 0 0
> (function(a,b){s=floor(d<-b/(sum(b)/a));s[o]=s[o<-rev(order(d%%1))[0:(a-sum(s))]]+1;s})(4,c(0.3, 0.4, 0.3))
[1] 1 2 1
> (function(a,b){s=floor(d<-b/(sum(b)/a));s[o]=s[o<-rev(order(d%%1))[0:(a-sum(s))]]+1;s})(5,c(0.3, 0.4, 0.3))
[1] 1 2 2
> (function(a,b){s=floor(d<-b/(sum(b)/a));s[o]=s[o<-rev(order(d%%1))[0:(a-sum(s))]]+1;s})(21,c(0.3, 0.2, 0.5))
[1]  6  4 11
> (function(a,b){s=floor(d<-b/(sum(b)/a));s[o]=s[o<-rev(order(d%%1))[0:(a-sum(s))]]+1;s})(5,c(0.1,0.2,0.3,0.4))
[1] 1 1 1 2
>

Octave, 87 76
Golfed:
function r=w(s,w)r=0*w;for(i=1:s)[m,x]=max(s*w-r);r(x)+=1;endfor endfunction

Ungolfed:
function r=w(s,w)
  r=0*w;   # will be the output
  for(i=1:s)
    [m,x]=max(s*w-r);
    r(x)+=1;
  endfor
endfunction

(Blasted "endfor" and "endfunction"! I'll never win but I do enjoy golfing with a "real" language.)

Nice algorithm. You can replace zeros(size(w)) with 0*w.

Nice! Why didn't I think of that?

Python, 139 128 117 bytes
def f(S,W):
 L=(S+1,0,[]),
 for n in W:L=[(x-i,y+(S*n-i)**2,z+[i])for x,y,z in L for i in range(x)]
 return min(L)[2]

Previous itertools solution, 139 bytes
from itertools import*
f=lambda S,W:min((sum(x)!=S,sum((S*a-b)**2for a,b in zip(W,x)),list(x))for x in product(*tee(range(S+1),len(W))))[2]

I was wondering if an itertools solution would be possible. Nice work +1. Am I right in thinking this has O(n^4) time complexity?

Itertools solution was O(S^len(W)) actually :P. New solution's a lot faster, but still slow

T-SQL, 167 265
Because I like to try and do these challenges in a query as well.
Turned it into an inline function to better fit the spec and created a type for the table data. It cost a bit, but this was never going to be a contender. Each statement needs to be run separately.
CREATE TYPE T AS TABLE(A INT IDENTITY, W NUMERIC(9,8))
CREATE FUNCTION W(@ int,@T T READONLY)RETURNS TABLE RETURN SELECT CASE WHEN i<=@-SUM(g)OVER(ORDER BY(SELECT\))THEN g+1 ELSE g END R,A FROM(SELECT A,ROW_NUMBER()OVER(ORDER BY (W*@)%1 DESC)i,FLOOR(W*@)g FROM @T)a

In use
DECLARE @ INT = 21
DECLARE @T T
INSERT INTO @T(W)VALUES(0.3),(0.2),(0.5)
SELECT R FROM dbo.W(@,@T) ORDER BY A

R
---------------------------------------
6
4
11