text:
Probability to win a hand of poker (Texas hold 'em)
Challenge:
In the last stage of a two players Texas hold 'em, given a two-card hand and five cards on table, determine your probability to win versus an opponent by the standard ranking of poker hands.
Input:
Seven cards (sdtin or arguments). The first two cards are your hand while the last five are on the table. Each card will be a two letter string of the form RS where R is rank and S is suit. The ranks range from 2-9, T for ten, and J, Q, K, and A for Jack, Queen, King, and Ace respectively. The suits are H, D, C, S for Hearts, Diamonds, Clubs, and Spades respectively.
Output:
The probability to win (stdout or return): from '0.00' to '1.00'.
Input to Output Examples:
AH 7C  KH QH JH TH 6C -> 1.00

Explanation: You have a royal flush, 100% winning chances.
9H 7C  KH QH JH TH 6C -> 0.96

Explanation: You have a straight flush, your opponent can only win with an AH, 95.6% winning chances.
Rules and Clarifications:

There are 52 different cards. You can refer to Texas hold 'em to get the idea.
Your opponent has 2 unknown cards (out of 45 left). That's 990 possibilities with equal probability.
You are free to decide if Ties count or don't count in the calculation of the probability.
As this is code golf, the shortest answer wins.

How should a potential tie be handled in the calculation? And given that you're asking about probabilities, it would be clearer if you made explicit your prior that the opponent holds each of the 990 possible pairs with equal probability.

@PeterTaylor I made "ties" free so you can shorten your code appropriately.

@Cœur - I just want to give you a kudos on the challenge... I've spent about 2.5 hours so far trying to solve this. If I do solve it I think I'll need gzip to make it small! ;-)

@scunliffe I was thinking of simplifying the challenge by only outputting 0 if you have less than 50% chances winning, or 1 if you have more than 50% chances winning, then I realized some people would hardcode the combinations somehow, compacting it with a hash-table maybe.

source: Stack Exchange

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

sort: votes


text:
Write a Rectangular Program that Outputs the Number of Times it was Rotated
The title says it all. Your goal is to write a program that forms a w×h rectangle of characters that can be rotated and re-run to output the number of 90° Counter-Clockwise (CCW) rotations that have been done.
For example, if the 3×2 program
abc
def

solved the problem, it would initially output 0, and successive rotations of 90° CCW
cf    fed    da
be    cba    eb
ad           fc

would output 1, 2, and 3 respectively.
Using comments makes this a trivial task is most languages. In Ruby for example, it can be done in a 7×7 rectangle:
###p###
### ###
###1###
p 0#2 p
###3###
### ###
###p###

The challenge is to do this without any sort of comments.
Scoring
Your score is w*h, the area of your rectangle. Newlines are excluded. In other words, code-golf, newlines not counted.
The score for the Ruby example is 49 (though of course it is invalid since it has comments).
Notes

Your code must really be rectangular with no missing characters at the end of lines.
If you wish you may output other legal "mod 90°" values instead of 0 1 2 3. So 8 is fine instead of 0, and -1 is fine instead of 3, etc.
The output may go to the console or into a file.
Standard loopholes apply.

I hope this, my first question, really intrigues some people. Enjoy!

To be more specific about what a comment is, is a comment any unevaluated code? Unparsed code?

I mean that none of your language's traditional "comment characters" should appear in any of the 4 rotated versions. So for C++, two slashes next to each other should never appear, though one may be used alone. Likewise with /*. I hope that clarifies it.

What about languages that do not have comment characters?

So code like echo 0;exit;e in bash is allowed?

If there is no way to comment then you needn't worry. @user23013 That bash is fine.

can the program throw errors/exceptions after outputting the answer?

@xem I don't think so. The program should be syntactically legal and be able to run without errors any way it is rotated.

fair enough. I posted my JS solution (score=9) without error :)

edit: JS score = 4

I think since a 0x0 rectangle has no well-defined rotation, any output is acceptable--including the null output (e.g. what the Python program `` would output).

APL (1x3 = 3)
5!3

This solution uses the extra rule that any output that is correct mod 4 works.
In APL, x!y is the number of way to choose x elements from y, commonly known as binom(y,x) or choose(y,x). Let's check that each rotation gives the right answer.
0 rotations
5!3

There's no way to choose 5 elements from 3, so we get 0, which is automatically printed.
1 CCW rotation
3
!
5

APL happily evaluates each line, getting the number 3, the operator !, and then the number 5, printing only the last of these (5), which is 1 mod 4.
2 CCW rotations
3!5

This is binom(5,3), which is (5*4*3*2*1)/(3*2*1)/(2*1) = 10, which is 2 mod 4.
3 CCW rotations
5
!
3

As before, only the last-evaluated value of 3 is printer.
I don't actually know APL, so please tell me if I got any of the explanation wrong. I found it by trial and error as the first language on this site that:

Automatically prints the result of an expression
Given multiple lines of expressions, only outputs the last one
Has no issue with an operator standing alone on a line
Takes operators infix
Has a single-character arithmetic binary operator that is asymmetric (aRb != bRa), and flexible enough to return a variety of numbers.

For (5), I went down the list of APL dyadic functions. My first candidate operation was the integer division / of C and Python 2, but APL division ÷ gives floats. Exponentiation is tempting, but fails because a and a^b have the same parity but are gotten by consecutive rotations (unless b=0, but then b^a=0). Boolean operators like < give 0 and 1 180 degrees apart, which doesn't work. Finally, I found the binomial operator ! and tried numbers until I got some that work.
Thanks to Quincunx for his confidence that there exists a smaller solution than 2x2.

Man, it's nice to see an answer that uses a non-esoteric language and wins.

I've accepted this as the answer since it is the shortest according to my rules, but I want to make Ventero's answer (http://codegolf.stackexchange.com/a/33162/26997) a very honorable mention. It follows the true essence of the problem.

It also works in J in the exact form you gave.

Actually, doesn't APL print both the 3 and the 5 in the 90° rotation?

@FUZxxl I think this only works in ngn/apl.

Ruby, 7×9 (63)
 30;p
0||p=p
0|0;p;p
;p;p|p;
p=p ||0
;p   p;
2||p =p
 00;1
     p

A bit longer than the other solution, but at least this solution doesn't depend on any implicit printing or rule abuse. For all four rotations, the full code is parsed and other than some short-circuiting, all of it is executed. Surprisingly, there's absolutely no symmetry in the code
This solution relies on the fact that it's still possible to call the p function (which is used to print the numbers) even if a variable with the same name has already been defined. For example, something like p p calls the function p with the variable p as argument (thus, printing the value of p).
Explanation for some of the common expressions used in the code:

p: As mentioned above, this is either a function call or a variable. When the variable is not defined, this calls the function p without arguments, which does nothing and returns nil.
p p: Prints the variable p.
p|x: When p is the function, this is identical to nil|x, which returns true/false depending on the value of x. If p is an integer, it's bitwise or. Either way, this statement has no side effect.
p=p||x: Effectively the same as p||=x (conditional assignment) with the advantage of being syntactically valid and a no-op when reversed.

Symmetric version (9×10 = 90)
    p

  0 * 0
  00100
  0||2* p
p *0||0
  00300
  0 * 0

    p

This is the shortest symmetric solution (C2 when ignoring the numbers to print) I could come up with.
Test script
Here's a test script to verify the code above (the # at the line ends have been added so that the whitespace doesn't get stripped and are removed before execution):
rotate=->s{s.split($/).map{|i|i.chars.reverse}.transpose.map(&:join).join($/)}

s=<<EOD.gsub(?#,"")
 30;p  #
0||p=p #
0|0;p;p#
;p;p|p;#
p=p ||0#
;p   p;#
2||p =p#
 00;1  #
     p #
EOD

puts ">>> 0°"
eval s
puts ">>> 90°"
eval rotate[s]
puts ">>> 180°"
eval rotate[rotate[s]]
puts ">>> 270°"
eval rotate[rotate[rotate[s]]]

It may not be the shortest but this is exactly the kind of obfuscated brilliance I was looking for :D

@Calvin'sHobbies Does this meet the "Your code must really be rectangular with no missing characters at the end of lines" restriction?

@JoshuaTaylor It's rectangular, some lines are just padded with spaces (which, as far as I'm concerned, is a character). If that wouldn't meet the restriction for whatever reason, I could also pad the lines with semicolons instead ...

@Ventero I certainly hope this legal;  I'm just trying to understand what was meant in the question.

@JoshuaTaylor Woops, sorry, didn't notice you were asking Calvin'sHobbies.

@Ventero No worries.  I just asked it here rather than on the main question because in this we have an example. :)

@Ventero Padding with spaces (or really anything besides comments and newlines) is just fine.

Python - 23 x 23 = 529
Ok, this question has already a winner, but there is no Python solution, yet. So I thought about it - heavily! - and found a way to make the bulky print command working in any direction without producing errors when parsed from one of the other directions.
The breakthrough was the following line:

'"\'';forward_code;"';backward_code;""\'"''

While the forward_code is executed, the backward_code is part of a string and thus not printed. This is exactly the other way around when reading backwards.
So combined with two more directions and fine-tuned to get all quotes matching correctly I end up with the following solution:

''"''""''"''"''"'"''""'
"  ""                 "
"  \\                 "
'"\'';print 1;"'""\'"''
'"\''"';3 tnirp;""\'"''
"  ;""                "
"  p'                 "
'  r;                 '
'  i2                 '
"  n                  "
"  tt                 "
'   n                 '
'  4i                 '
"  ;r     .-=<>=-.    "
' \"p    /__----__\   '
"  ';'  |/ (')(') \|  "
"  ""    \   __   /   "
'  ""    .`--__--`.   '
"  \\   /    :|    \  "
'  ''  (_)   :|   (_) '
'  ""    |___:|____|  '
"  ''    |_________|  "
''"''""''"''"''"'"''""'

Edit: I found a way to deal with all that whitespace. ;)

Is there any way to also put p=print in the file, since you've got so much whitespace currently? (Python 3, of course)

@isaacg: I don't think so. The definition p=print is also lengthy. And more importantly: You can't reuse p after rotating the code!

I guess you're right. It's two bad, though.

Nominated: Best Use of Whitespace Award.

GolfScript, 4 (2x2)
43
12

Prints 4312 which is 0 (mod 4). The rotations print 3241 (1 mod 4), 2134 (2 mod 4), and 1423 (3 mod 4).
Prompted by:

If you wish you may output other legal "mod 90°" values instead of 0 1 2 3. So 8 is fine instead of 0, and -1 is fine instead of 3, etc.

There are actually many sets of numbers for which this works. I found these with this Python program:
def f(a,b,c,d):
    return int("%i%i%i%i"%(a,b,c,d))
for a in range(10):
    for b in range(10):
        for c in range(10):
            for d in range(10):
                candidate = f(a,b,c,d) % 4 == 0
                candidate &= f(b,d,a,c) % 4 == 1
                candidate &= f(d,c,b,a) % 4 == 2
                candidate &= f(c,a,d,b) % 4 == 3
                if candidate:
                    print("%i, %i, %i, %i"%(a,b,c,d))

Although the program outputs 0s (which probably wouldn't work), the valid solutions are of the form
ab
cd

Where a∈{4,8}, b∈{3,7}, c∈{1,5,9}, d∈{2,6}. IE (a,b,c,d)∈{4,8}×{3,7}×{1,5,9}×{2,6} which is 24 solutions.

Very clever. I honestly thought that extra rule was innocuous.

Don't forget to count the newline as a character.

@Everybody Note that this is not the smallest possible program. A 2x1 is possible, and it is the smallest possible. So get to work!

An equivalent python program: x=[print("%i, %i, %i, %i"%(a,b,c,d))for a,b,c,d in __import__('itertools').product(*(range(10),)*4)if int("%i%i%i%i"%(a,b,c,d))%4==0and int("%i%i%i%i"%(b,d,a,c))%4==1and int("%i%i%i%i"%(d,c,b,a))% 4==2and int("%i%i%i%i"%(c,a,d,b))%4==3]. One liner ftw!

@isaacg Your score is w*h, the area of your rectangle. Newlines are excluded. In other words, code-golf, newlines not counted.

@Quincunx Well then post it!

@tomsmeding I said that a 2x1 is a possible solution (a 3x1 is also a possibility). I didn't say that I know a language or a program that could do it. :-/

Assuming the language here simply prints the last number it evaluates, I don't believe a 1*n (one-number) solution exists for any n. This is because the parity of the whole number equals the parity of its rightmost digit, but rotations 90 degrees apart must yield different parities. So, 2*2 is the minimum for this approach.

@Quincunx I see. You can have a 1*3 solution of 3/5 if you have a language that returns the last value it evaluates, has / as integer division ignoring remainder, and doesn't mind a lone number or function operation on a line.

Thought I'd just say: I accidentally deleted a relevant comment: My point was that 2x1 could be possible because the newline due to the rotation produces 4 different possible programs.

BASIC, 64
Won't win, but here it is anyway. (Tested in Chipmunk Basic)
?0:END:?
:::::::1
D:::::::
N::::::E
E::::::N
:::::::D
3:::::::
?:DNE:2?

Note: ? is shorthand for PRINT in various dialects of BASIC. Although there are lots of syntax errors in the code, the END statement in the first line prevents them from being seen by the interpreter.

Actually, your scores are 64 and 16, respectively. Newlines don't count. Also, why not split the answer?

Oh, missed that bit. I would have split the answers if they weren't occupying joint last place. There doesn't seem to be much point otherwise :-)

You're not last anymore :-)

I'd give you bonus points for getting a nice round number of characters. The actual +1 is for the creative use of END though :)

Pyth, 9 characters (3x3)
0 1

3 2

In pyth, everything is printed by default, unless it is preceded by a space. Lines after the first line are for user input, and are not evaluated in this program.
Another way to get 9 characters:
"0"
3 1
"2"

Pyth 1.0.5, 4 characters
While recent changes to pyth have made 2 digit numbers harder to generate (A change that I am considering reverting), older versions of Pyth have easy two digit number generation, which, combined with the implicit printing and the fact that all lines but the first are ignored, gives the following solution:
32
41

Prints 32,21,14,43.

Well, that's just fun. +1

Shucks, I was hoping it wasn't that easy. You are missing 3 characters on your middle line but I'm guessing that's due to the auto-formatting here.

@Calvin'sHobbies Sorry, I see. It chomped my trailing spaces.

@Quincunx Oh, I missed that part of the scoring. Thanks for the fixes.

Befunge, 16
0.@1
@@@.
.@@@
3@.2

Explanation: Digits from 0 to 9 push the corresponding number onto the stack, . pops a value from the stack and prints it as an integer, and @ ends the program.
(tested here)

Doesn't this output the number of times it was rotated counterclockwise?

@TheRare Yes. It does. That is what it should do.

I seem to be utterly blind. Have a +1 because of that.

Befunge!!! Still my favourite language of all times ever forever eternally so!

Piet, 49

I made a point only to use yellow and red colors, and to try and make it roughly symmetrical. When rotated, it prints 0, 1, 2 or 3. Exiting the program in Piet is hard, and takes up around half the space in the picture, unfortunately.

Seems like the right tool for the job.

O_o, I cried finding out about this programming language! Just now. Beautiful. In so many ways! Thank you!

GNU dc, 6 (3x2)
I think this is the shortest answer not to require the "mod 90°" rule-relaxation:
3z1
0p2

Outputs 0, 1, 2 or 3 for each rotation.
For the 0, 2 and 3 rotations, the p simply pops and prints the last number literal to have been pushed to the stack.  For the 1 rotation, the z pushes the current stack depth (1) to the stack, then the p pops and prints it.

So 311/0p2 would also work?

@Neil Yes, good one.  Doesn't affect the golf score though :)

It does affect the golf score, but negatively, since newlines are not counted, but slashes are.

@M.Herzkamp My assumption was that Neil meant 311\n0p2, where \n is a newline character.  Otherwise it would be meaningless within the context of dc.

GolfScript, 9 (3x3)
0}1
} }
3}2

Sort of abusing the rules. The } happens to end the program if there is no matching {, and the contents of the stack are printed at program end.

Don't forget to count the newline as a character.

@isaacg Your score is w*h, the area of your rectangle. Newlines are excluded. In other words, code-golf, newlines not counted.

I didn't know that } can be unbalanced. Nice trick.

JavaScript, 4
03
12

When you execute this program (or a rotation of this program) in a javaScript console, only the last line is evaluated and echoed in the console.
So:
12 modulo 4 == 0
01 modulo 4 == 1
30 modulo 4 == 2
23 modulo 4 == 3

Here are all the similar 2x2 programs that work too:
03
12

03
16

03
52

03
56

03
92

03
96

07
12

07
16

07
52

07
56

07
92

07
96

43
12

43
16

43
52

43
56

43
92

43
96

47
12

47
16

47
52

47
56

47
92

47
96

83
12

83
16

83
52

83
56

83
92

83
96

87
12

87
16

87
52

87
56

87
92

87
96

In other terms,
ab
cd

where a is in [0,4,8], b is in [3,7], c is in [1,5,9], and d is in [2,6]

CJam / GolfScript - 3*3
2;3
;7;
1;0

The semicolon pops the previous number, thus only the bottom right corner is printed.

Aheui, 8
바몽희뷸
뷷희몽반

Since Aheui does not have a letter that pushes 1 onto the stack, I decided to print 0, 5, 2, and 3.
Explanation: 바 and 반 push 0 and 2, respectively, onto the stack and moves the cursor right by one character. 뷸 and 뷷 push 5 and 3, respectively, onto the stack and moves the cursor down by two characters. 몽 pops and prints the number in the stack and moves the cursor up by one character. 희 terminates the program.

JavaScript
(Entered in browser console, shell or another REPL, so result is printed)
1+2
-3-
4+5

Should work for any other language with expressions, non-significant newlines and automatic printing of the result.

I like the idea behind this, but doesn't it always print 1 (mod 4)?

A simpler variation might be '2,3\n,0,\n1,0'.

It does give different results when rotated. @Cory, That's clever! I'm too used to working in a language without the comma operator.

@lrn Yes, it gives different results, but that isn't the requirement. The program has to print 0 (mod 4) when not rotated, and 1, 2 or 3 (mod 4) when rotated the respective number of times...

The second note of the original poster allows any values for the rotated versions, as long as they are distinct.

@lrn I don't think so, read it again

Matlab/Octave - 144 100
Golfed: 10 x 10 = 100
....d.....
....i.....
....s.....
... p2 ...
disp  1...
...3  psid
... 4p ...
.....s....
.....i....
.....d....

Alternative solution: 15 x 15 = 225
.......d.......
.......i.......
.......s.......
...    p    ...
...         ...
...    4    ...
...    .    ...
disp 1...3 psid
...    .    ...
...    2    ...
...         ...
...    p    ...
.......s.......
.......i.......
.......d.......

Can the first solution be reduced to size 8x8, if vrtical and horizontal operators 'disp' share letter 'p'?
...d....
...i....
...s2...
disp 1..
..3 psid
...4s...
....i...
....d...

@AMK: Unfortunately, this produces a syntax error in line ..3 psid. You need at least three dots at the beginning of each line to indicate a line break and to ignore the remaining characters.

Perl 5x7 (35)
1+p+t+1
-print+
1+i+i+1
+tnirp+
1+t+p+1

A bit late to the party. The solitary - determines which number is printed.

Befunge, 12 (6x2)
I Managed to come up with a slight improvement on the existing Befunge answer by making the most of Befunge's two-dimensional nature and having the code path run vertically in two of the orientations.
0.@.1v
v3.@.2

Try it online: Starting 0,
Rotation 1,
Rotation 2,
Rotation 3.

JavaScript, 3
2
1
4

It works... in base 7.
Base 9 version:
2
7
0

Explanation
When run interactively, e.g. from a debugging console, the value of the last statement/expression will be output.
47 = 410 ≣ 0 (mod 4)
4127 = 20510 ≣ 1 (mod 4)
27 = 210 ≣ 2 (mod 4)
2147 = 10910 ≣ 3 (mod 4)
Similar solutions could be found for any odd base.

This was flagged, but I don't understand the question or the answer so I had to skip it. Would be nice if downvoters left a comment explaining their downvotes.

@Rusher I suspect they didn't understand the base 7 bit.

Marbelous, 7*14 = 98
.. \/ \/ .. ..
.. 31 \\ 32 \/
\/ \\ \/ \\ \/
\/ 30 \\ 33 ..
.. .. \/ \/ ..

Are you expecting each cell to remain intact when rotated?

brainfuck, 12x10 = 120
Outputs 0, 1, 2, and 3, respectively.
++         >
++++++++++++
++++++++++++
++++++++++++
++++++++++++
      .+++++
++++++++++++
++++++ +++++
++++++ +++++
++++++ +++++

Try it online!
One turn
Two turns
Three turns

Argh!/Aargh! (4*4=16)
What was that about using the right tool for the job? There are no comments (in the language in general).
The entire family of programs (generated in J: ((|.@:|:) ^: (i. 4)) >'hpqh';'q01p';'p32q';'hqph' or ((|.@:|:) ^: (i. 4)) 4 4 $ 'hpqhq01pp32qhqph')
hpqh
q01p
p32q
hqph

rotated once:
hpqh
q12p
p03q
hqph

rotated twice:
hpqh
q23p
p10q
hqph

rotated three times:
hpqh
q30p
p21q
hqph

To explain this, it might be best to look at an "indented" version (That also works in all rotations):
hhpq h
  0  h
q   1p
p3   q
h  2
h qphh

This version shows that the program consists of 4 separate parts, one for each individual rotation.

h - set control flow left

p - print item in data/code raster below it

q - quit the program

Floater - 9×5=45

Prints 4, 1, 2, or 3 to console.
Note that 'Black' is a valid instruction (NOP), and is syntactic. Without it, it can't find the starting position. Thus, all positions in the rectangle are occupied.

Triangular, 2x3 => 6
%%3
i%i

Try it online!
A "rectangular triangular program" - we certainly do live in a society.
The base version here prints the top value of the stack (initially 0), then the other two prints are missed due to triangular's execution order.
Rotation 1
i%
%%
i3

Increments the top value to 1, prints, misses the other two print commands.
Rotation 2
i%i
3%%

Increments twice, hits the last print command.
Rotation 3
3i
%%
%i

Pushes 3 onto the stack, hits a print statement, misses the other two.

Nice, except the rotation is supposed to be Counter clock-wise. ↺

Pip, 2x2 = 4
tv
oi

Try it online!
All four letters are preinitialized variables; whichever one comes last in the program is autoprinted.

No rotation: i = 0
One rotation: o = 1
Two rotations: t = 10
Three rotations: v = -1

Interesting use of the mod 90 rule.

Python, 18x18 = 324
Uses escaping and mixed quotation marks to change how each string is parsed after rotation. Triple quotes allow the literals to span multiple lines and take up less space.
"""p         '   "
   r         '   "
   i         '   "
   n'\""",)2(tnirp
'''t          '
   (          \
   3          "
   )          "
   ,          "
   '          ,
   '          )
   '          1
   \          (
   "          t"""
print(0),'''\"n
'   "         i
'   "         r
'   "         p'''

Test code (needs to be cleaned up) :
with open('./rotpy.py','r') as fh:
    l=list(fh)
    ll=max(len(x)for x in l)
    l=[x[:-1]+' '*(ll-len(x)) for x in l]

def r(l):
    return list(''.join(reversed(z)) for z in zip(*l))

for i in range(4):
    exec('\n'+'\n'.join(l))
    l=r(l)

Element, 2x3 = 6
1*
`2
3

This is an improvement over the 3x3 naive solution, which has a ` in the middle with a number on each side.  The 0 case, shown above, is the most interesting, since the * is used to multiply the 3 by nothing to get 0.  Other than that, it's not that complicated.
If you find the space awkward, you can replace it with pretty much any other character, excluding []{}`_.
For reference, here are the other three rotations:
case 1
*2
1`3

case 2
 3
2`
*1

case 3
3`1
 2*

Japt, 3 * 1 = 3 bytes
5zB

Try it online: as-is,
rotated once,
twice,
thrice.
Outputs 0, 5, 2, 11 respectively.
The variable B holds the value 11, and Number.z(other) is floor division (everyone looked for apparently :p). For multi-line code, the last line is passed to output, which is simply a constant here.

2 * 2 = 4 bytes
2J
1T

Try it online: as-is,
rotated once,
twice,
thrice.
Outputs 0, 21, 2, -1 respectively.
T holds 0, and J holds -1.
The trick is that, if two literals or variables are put side-by-side, a comma is inserted and the output is just the last one.
2 * 2 JS solution works in Japt too.

MAWP, 2x2 = 4
0:
23

-2 characters from Bubbler.
The position of the : operator determines when things are output, so we can abuse that and position the numbers around it.
Bubbler's modification pops the existing 1 from the stack, saving two bytes.
Try it!

05AB1E, 4 (2x2) bytes
YX
3¾

To-the-point approach.
Try it online or verify all four rotations.
Explanation:

Y is a variable with default value \$2\$
X is a variable with default value \$1\$
¾ is a counter variable with default value \$0\$

So in all four rotations they are all three pushed to the stack, and then output the last integer on the stack is output implicitly as result.
An alternative 2x2 is a port of the @DLosc's Pip answer, where T = \$10\$ and ® = \$-1\$:
TX
®¾

Try it online or verify all four rotations.

Zsh, 36 (6x6)
 <<<0
3    <
<    <
<    <
<    1
 2<<<

Try it online!.
Alternative, (10x10):
printf 0 p
         r
3        i
         n
f        t
t        f
n
i        1
r
p 2 ftnirp

Exploits the fact that printf only prints the first word, if there are no quotes.

Japt, 2*2=4 bytes
Outputs 0, 1, 2 & -1.
ÄÄ
JT

Test it | Rotated: once, twice, or thrice
Outputs 0-3.
ÄÄ
ÑV

Try it
I'm struggling to find anything in the spec that disallows trivial solutions of double, or even single, digit numbers.

Chip, (2x5) 10
b~
+a
~t
e*
 f

* activates all neighbor elements: north, east, south and west (source)
~ if not activated from the west, activates the east neighbor (NOT-gate) (never activated here)
t terminates execution after printing the current byte
a sets the bit 0x01 of the output
b sets the bit 0x02 of the output
e sets the bit 0x10 of the output
f sets the bit 0x20 of the output
+ if activated by any neighbor, activate all other neighbors (wire)
Chip requires either the -w flag (to allow execution without input), or some input in order to run.
Prints 0, 1, 2, or 3 in ASCII. If code points 0x00 to 0x03 are desired, remove the e and f, then move the space up to fill the gap.

><> (Fish), 11 bytes
0v1
vnv
3v2

Try it
Starts in a corner, pushing whatever the rotated value is. Then gets sent in a infinite downwards loop which will soon crash since the stack is empty.

Thunno, 4 bytes (2x2)
2y
3x

Attempt This Online! (0)
Attempt This Online! (1)
Attempt This Online! (2)
Attempt This Online! (3)

(The last one outputs 23 but that's ok because 23 % 4 = 3)
Port of Kevin Cruijssen's 05AB1E answer.
x defaults to 0 and y defaults to 1.

TI-Basic, 2x2 = 4
03
12

This is the exact same as this answer, for the same reason.
3x3 = 9
2:3
:::
1:0

Pyt, 9
2ĉ3
ĉĉĉ
1ĉ0

Try it online!
The key here is that ĉ clears the stack, so for every rotation, only the last number is implicitly printed.

authors: Наполовину не пустой

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

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


text:
Find the unique number
I have read a question similar to this. I found it interesting, and difficult  so I rephrased the question as a code golf. (that question is closed )
Challenge:

In 1 million and 1 numbers, all the numbers having the duplicate except only one number . Write a program that can find this unique number.

Input form:

a text file containing 1000001 integer seperated by space.
  The numbers are shuffled

Output form:

a single number

Note:
Using standard library functions to compare values is not allowed the (in case you intend to use something as strcmp() in c or anything similar in other languages)
a simple algorithm that can achieve the job.
This is code golf, so the shortest code win.
All languages are allowed. ( I prefer c/c   x86 assembly if possible because i have no experience in any other language)
add some explanation to your source code if possible.
Good luck.

You might want to further define comparison operators. Now I can just do f=open('f').read().split(); [i for i in f if f.count(i)&2][0] and be done with it.

Capitalisation and some line breaks, please!

What does it mean that "all the numbers have a duplicate except one"? Does it mean that every number occurs 0, 1, or 2 times? Or could the input be 1 1 1 2? Also, what is the range of integers permitted in the input?

This mean that there is 2 exact copies of 1000000 number in the txt file and one copy of single number
example of input file
1 3 6 5 1 5 6 3 2
each number is doubled except 2
there is no limits for that inters in the file but they are all integers.

Golfscript, 6 characters
~]{^}*

This simply XORs all numbers: assuming the input file consists of the numbers a b b c c d d ... in any order, this calculates a^b^b^c^c^d^d^... (XOR is commutative/associative, so the order of numbers doesn't matter). Since x^x == 0, this effectively leaves only the number that hasn't been duplicated.
Run it like this: golfscript unique.gs < inputfile

I am totally beginner so i need more explanation

@Ahmed I added some explanation, does that make it clearer?

Yes It is clear now
thanks

This is extraordinarily clever (and not gs-only)

Pyth, 10 characters
Note: Does not fail even if there are more than 2 copies of duplicated numbers.
JPw)'ocJNJ

Explanation:
JPw)    J=input.split()
'oJNJ   print first element of J sorted by count of element in J.


text:
Optimize paper folding to mitigate inkblots
Dark black ink has splattered all over your white sheet of printer paper! The obvious solution is to fold the paper so black and white parts meet and both become grey as the ink diffuses. Then unfold and refold until your paper is all equally grey.
Finding the best way to make these folds is your task in this coding challenge. This Pastebin contains four different sized grids of ones and zeros. Each grid represents a piece of ink splattered paper that you must turn grey. Zeros are paper and ones are ink.
In these grids, only horizontal and vertical folds along the spaces between lines and columns are valid. When a fold is made the pairs of overlapping values are averaged. Folds are done one at a time and always unfolded. Folds only change the ink distribution, not the size of the paper.
Rn denotes folding the left edge of the grid to the right, starting after the nth column. Dn denotes folding the top edge of the grid downward fold, starting after the nth row. (n is 1-indexed)
Example
Given this grid
0 1 1 1
0 0 0 0
0 0 0 0

a D1 fold means "fold the entire top row down then unfold".
0 0.5 0.5 0.5
0 0.5 0.5 0.5
0   0   0   0

Then an R2 will produce
0.25 0.5 0.5 0.25
0.25 0.5 0.5 0.25
   0   0   0    0

and another R2 will not change anything.
Goal
Your goal is to write an algorithm that finds the best ink-spreading folding sequence for each of the four grids using exactly 8 folds each time. The folds may be any combination of Rs or Ds.
Scoring
The score of your submission is the sum of your scores for each grid. A grid's score is the sum of the absolute differences between each of its values and its average (its sum divided by its area). Lower scores are better. A score of 0 is perfect, but is probably impossible in only 8 folds.
You must report your four 8-step folding sequences with your code in your answer. This is so we can verify your algorithm really works.
Please put them in this form:
20*20R1D2R3D4R5D6R7D8
40*20R1D2R3D4R5D6R7D8
40*40R1D2R3D4R5D6R7D8
20*80R1D2R3D4R5D6R7D8

Here is a Python script that will calculate your scores given your folding sequences.
Naturally you should not copy someone else's sequence submission. Sequences for each grid only belong to the person who first created them.
Clarifications

Ideally your algorithm will work well on any grid, though you can tailor it to these specific ones.
You must submit your code with your sequence. To win you need the smallest-scoring set of 8-step folding sequences that has not already been posted, and also an algorithm that stands up to public scrutiny. Explain your code, don't obfuscate it.
The grid should never contain negative numbers.
Standard loopholes apply.

I think it's better if you have some test cases, and that participants are expected to give code that produces the sequence, instead of just giving the sequence.

I know that would be ideal but how could I make sure that people aren't hiding their sequence in a program that looks like a possible algorithm?

You can quote standard loopholes and those entries will be invalidated by the community (or more precisely, by you when community points it out) when they found it. And you'd better give more test cases. EDIT: I think one test case is fine, though, if it's difficult enough, which I think so for your current test case.

Another option is to ask people to give the sequence that they got with their code, but ask them to provide a hash (say SHA-256) of their code as proof that they actually produce it using their own work. I remember seeing that kind of mechanism some time ago, but I can't remember. Can anybody point to that challenge?

Another way to prohibit hard-coding is to make the challenge open to other test cases as well.

I do want people to include their code so I made that a requirement. Hopefully people will stay honest but if there is contention then the person who posted first will almost certainly win.

@Howard and others, how would making more test cases help? I figured it was easy enough for people to generate their own random grids. Brute force is out as there are (19*39)^8 potential solutions so checking one per nanosecond would still take a couple million years.

@justhalf this was the challenge with the hashes, for different reasons though.

@Calvin'sHobbies I'd prefer a larger set of test cases, too, to be honest, because some algorithms might fare better on certain grids than others. What you could do is what I did with Vector Racing that each participant may add a test case to the benchmark set. In that case, you'd have to take it on you to test and score all submissions though, because you can't expect early participants to rerun their code with test cases added later.

I see, I didn't think of having multiple grids count towards the score but I like it. I think I'll add 3 or 4 more grids to the gamut.

@Calvin'sHobbies Brute force is (19+39)^8 (minus some symmetries) which is much more feasable.

Python
Exhaustively tries different combinations of folds for the first few folds, then does the rest of the folds using a greedy approach.
The exhaustive approach is bounded within a reasonable range of folds in the center, such that it won't take forever, while not ignoring too many possible folds to yield a good minimum.
Ran using pypy on my macbook air.
Answers:
20*20D9R15R6D11R10R9D10R11
40*20D6D13D9R19R21R20D11D10
40*40D21R21R11D19R23R20D23D15
20*80D33D47D40R10D39D41R9R11

Outputs:
Exhaustive folds levels: 3
Percentage pruned from sides from exhaustive folds: 0.2
Time taken: 4.016076s
Score: 7.91125
20*20D9R15R6D11R10R9D10R11

Exhaustive folds levels: 3
Percentage pruned from sides from exhaustive folds: 0.2
Time taken: 28.529278s
Score: 16.34375
40*20D6D13D9R19R21R20D11D10

Exhaustive folds levels: 3
Percentage pruned from sides from exhaustive folds: 0.25
Time taken: 98.430465s
Score: 42.13
40*40D21R21R11D19R23R20D23D15

Exhaustive folds levels: 3
Percentage pruned from sides from exhaustive folds: 0.25
Time taken: 234.873787s
Score: 32.30875
20*80D33D47D40R10D39D41R9R11

Total Score: 7.91125 + 16.34375 + 42.13 + 32.30875 = 98.69375
Code:
import time, math
from collections import deque

numberOfFolds = 8 # Total number of folds

startTime = time.clock()

exec "grid = ("+"""
1 1 1 0 1 1 0 0 1 0 0 1 0 1 1 0 1 0 1 1
1 1 0 0 0 1 0 1 1 0 0 0 1 0 1 1 1 0 1 1
0 1 0 0 0 1 0 1 0 1 1 1 1 0 1 0 1 0 1 0
0 0 0 1 0 1 0 0 0 0 1 1 1 0 1 1 0 0 0 1
0 1 0 1 1 0 0 0 0 0 1 0 1 1 1 0 1 0 1 0
1 0 1 1 0 1 1 1 1 1 1 0 0 1 0 1 0 1 0 1
0 1 1 1 0 0 0 1 1 0 1 0 1 1 0 0 0 0 0 0
0 0 0 0 0 0 1 1 1 1 1 0 0 0 1 1 0 0 0 0
1 1 1 0 1 0 0 1 0 1 1 1 1 1 1 0 0 0 0 1
1 1 0 0 0 1 1 1 0 1 0 1 0 0 1 1 0 0 1 0
0 1 1 0 0 0 1 1 0 1 1 1 0 1 1 1 0 1 0 1
0 1 1 1 1 0 0 1 1 0 1 0 1 1 1 1 0 1 1 0
0 0 0 1 0 0 0 1 0 1 0 0 1 0 0 0 1 0 0 1
0 0 1 1 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 1
1 1 1 1 0 1 1 0 0 0 0 1 1 1 0 0 0 0 0 1
1 0 0 1 0 0 0 0 1 0 0 1 1 0 0 0 0 0 0 0
0 1 1 1 0 0 1 1 0 0 1 1 1 1 0 1 1 0 0 1
0 0 1 0 1 1 1 1 0 1 1 0 1 0 1 0 0 1 1 0
0 1 1 0 1 0 0 1 0 0 1 1 1 1 1 0 1 1 0 0
0 0 1 0 1 1 1 0 0 1 0 0 0 1 0 1 1 1 1 1
""".replace(" ",",").replace("\n","],[")[2:-2]+")"

def getAverage(grid):
    count = total = 0
    for j in grid:
        for i in j:
            count += 1
            total += i
    return total/float(count)

def getScore(grid, average):
    score = 0
    for j in grid:
        for i in j:
            score += abs(average-i)
    return score

def downFoldedGrid(grid, row, width, height, copy=True):
    if copy: grid = [r[:] for r in grid]
    foldRange = min(row, height-row)
    for j in xrange(foldRange):
        rowRef1 = grid[row+j]
        rowRef2 = grid[row-1-j]
        for i in xrange(width):
            rowRef1[i] = rowRef2[i] = (rowRef1[i] + rowRef2[i]) * .5
    return grid

def downFoldedScore(grid, score, average, row, width, height):
    foldRange = min(row, height-row)
    average2  = 2*average
    for j in xrange(foldRange):
        rowRef1 = grid[row+j]
        rowRef2 = grid[row-1-j]
        a = b = c = 0
        for i in xrange(width):
            a = rowRef1[i]
            b = rowRef2[i]
            c = a+b
            score += abs(average2-c) - abs(average-a) - abs(average-b)
    return score

def rightFoldedGrid(grid, column, width, height, copy=True):
    if copy: grid = [r[:] for r in grid]
    foldRange = min(column, width-column)
    for j in xrange(height):
        rowRef = grid[j]
        for i in xrange(foldRange):
            a = column+i
            b = column-1-i
            rowRef[a] = rowRef[b] = (rowRef[a] + rowRef[b]) * .5
    return grid

def rightFoldedScore(grid, score, average, column, width, height):
    foldRange = min(column, width-column)
    average2 = 2*average
    for j in xrange(height):
        rowRef = grid[j]
        a = b = c = 0
        for i in xrange(foldRange):
            a = rowRef[column+i]
            b = rowRef[column-1-i]
            c = a+b
            score += abs(average2-c) - abs(average-a) - abs(average-b)
    return score

def bestFoldsGreedy(grid, average, maxFolds, width, height):
    score  = getScore(grid, average)
    folds  = []
    append = folds.append
    for z in xrange(maxFolds):
        bestFold      = 0
        bestFoldScore = score
        bestFoldGrid  = grid
        for i in xrange(1, width): #Try all right folds
            foldScore = rightFoldedScore(grid, score, average, i, width, height)
            if foldScore < bestFoldScore:
                bestFold      = i
                bestFoldScore = foldScore
        for i in xrange(1, height): #Try all down folds
            foldScore = downFoldedScore(grid, score, average, i, width, height)
            if foldScore < bestFoldScore:
                bestFold      = -i
                bestFoldScore = foldScore
        if bestFold:
            append(bestFold)
            score = bestFoldScore
            if bestFold > 0: rightFoldedGrid(grid, bestFold, width, height, False)
            else:            downFoldedGrid(grid, -bestFold, width, height, False)
    return score, folds

# Get the height and width
height  = len(grid)
width   = len(grid[0])

# Transpose the grid if height > width for better locality of reference
transposed = False
if height > width:
    grid = [[grid[i][j] for i in range(height)] for j in range(width)]
    transposed = True
    height, width = width, height

# The exhaustive grids and folds attempted
exhaustiveGridsAndFolds = deque([(grid,[])])
popleft = exhaustiveGridsAndFolds.popleft
append  = exhaustiveGridsAndFolds.append

# Set the bounds to exhaustively test for
exhaustiveLevels   = 3
prunePadding       = [0.2, 0.25][width*height > 1000]
leftBound          = int(max(width*prunePadding, 1))
rightBound         = int(width*(1.0-prunePadding))
topBound           = int(max(height*prunePadding, 1))
bottomBound        = int(height*(1.0-prunePadding))

# Populate the exhaustive grids and folds
while 1:
    grid, folds = popleft()
    if len(folds) == exhaustiveLevels:
        append((grid, folds))
        break
    for i in xrange(leftBound, rightBound):
        if i not in folds:
            append((rightFoldedGrid(grid, i, width, height), folds+[i]))
    for i in xrange(topBound, bottomBound):
        if -i not in folds:
            append((downFoldedGrid(grid, i, width, height), folds+[-i]))

# Test all the exhaustive grids and folds greedily
average             = getAverage(grid)
bestFinalScore      = getScore(grid, average)
bestFinalFolds      = []
numberOfGreedyFolds = numberOfFolds-exhaustiveLevels
while exhaustiveGridsAndFolds:
    grid, exhaustiveFolds = popleft()
    finalScore, greedyFolds = bestFoldsGreedy(grid, average, numberOfGreedyFolds, width, height)
    if finalScore <= bestFinalScore:
        bestFinalScore = finalScore
        bestFinalFolds = exhaustiveFolds + greedyFolds

# Repeat the last fold till the total number of folds if needed
if len(bestFinalFolds) < numberOfFolds:
    bestFinalFolds += [bestFinalFolds[-1]]*(numberOfFolds-len(bestFinalFolds))

# Print the best result
foldsString = ""
down  = "D"
right = "R"
if transposed:
    down,  right  = right,  down
    width, height = height, width
for fold in bestFinalFolds:
    if   fold > 0: foldsString += right+str(fold)
    elif fold < 0: foldsString += down+str(-fold)
print "Exhaustive folds levels: " + str(exhaustiveLevels)
print "Percentage pruned from sides from exhaustive folds: " + str(prunePadding)
print "Time taken: " + str(time.clock()-startTime) + "s"
print "Score: " + str(bestFinalScore)
print str(width) + "*" + str(height) + foldsString

Okay, I can stop working on this now. This would have been exactly my algorithm.

@bitpwner You're still using 0.5 as the grid average but it's actually slightly different depending on the grid. With my script at http://ideone.com/5wbrOQ you are scoring 8.26, 17.71875, 44.61125, and 32.72 for a 103.31 total.

C, 16.344 (4 minutes 33 seconds)
Best moves found so far: D6,D13,R19,D9,D11,R21,D10,R20
Uses a mixture of Monte Carlo and hill climbing. Could be made to run much faster, I'm sure.
#include <stdio.h>
#include <stdlib.h>

/*

Best result so far: 16.344
D6,D13,R19,D9,D11,R21,D10,R20

real    4m33.027s
user    4m12.787s
sys 0m1.334s

*/

#define GRID_WIDTH   40
#define GRID_HEIGHT  20
#define GRID_SIZE    (GRID_WIDTH * GRID_HEIGHT)
#define NUM_FOLDS    8
#define MAX_VALUE    (1 << NUM_FOLDS)
#define TARGET_VALUE (MAX_VALUE / 2)

double score_grid(short *g) {
  int i, sum;
  for (i=sum=0; i<GRID_SIZE; i++) sum += abs(*g++ - TARGET_VALUE);
  return sum * 1.0 / MAX_VALUE;
}

void h_fold(short *g, int fold_row) {
  int x, y0, y1;
  if (fold_row<1 || fold_row>=GRID_HEIGHT) return;
  y1 = fold_row * GRID_WIDTH;
  y0 = y1 - GRID_WIDTH;
  while (y0>=0 && y1<GRID_SIZE) {
    for (x=0; x<GRID_WIDTH; x++) {
      g[y0+x] = g[y1+x] = (g[y0+x] + g[y1+x]) >> 1;
    }
    y0 -= GRID_WIDTH;
    y1 += GRID_WIDTH;
  }
}

void v_fold(short *g, int fold_col) {
  int y, x0, x1;
  if (fold_col<1 || fold_col>=GRID_WIDTH) return;
  x1 = fold_col;
  x0 = x1 - 1;
  while (x0>=0 && x1<GRID_WIDTH) {
    for (y=0; y<GRID_SIZE; y+=GRID_WIDTH) {
      g[y+x0] = g[y+x1] = (g[y+x0] + g[y+x1]) >> 1;
    }
    x0--;
    x1++;
  }
}

void print_grid(short *g) {
  int i=0, checksum=0;
  while (i<GRID_SIZE) {
    checksum += *g;
    printf("%3X",*g++);
    if ((++i) % GRID_WIDTH == 0) putchar('\n');
  }
  if (checksum != GRID_SIZE * TARGET_VALUE) printf("Bad total: %d\n",checksum);
}

void init_grid(short *g) {
  int i;
  static short *start_grid=0, *sg;
  if (!start_grid) {
    char *src = "11010110100011100000001000110001001101010111000100100100000101100000101111000010"
                "10110011111011111101101011111001000010101010110111000101000001011111101000011001"
                "10000111111001111011100101101001101100001110001101001011010011011110101000011100"
                "00110010100010100010110101001100110001100100111010000110100110001000110000111101"
                "01000001110000101000110101011011101010111110101010110000001011010010000011101000"
                "11111011111100100100100010111010111111000101011110000100111111111000110101101101"
                "00110100010111101111000011011010000110001001101010010101110010110111101001011111"
                "10110001101100001110010100110100010011011110100110000100100111101101000010011001"
                "00011100110100111101000000001000010100001101001011000101101001000100111100011010"
                "00010110001110011111100011101111011100111001110011111011010010000100101111101001";
    start_grid = malloc(GRID_SIZE * sizeof(short));
    for (i=0; i<GRID_SIZE; i++) start_grid[i] = (src[i]&1)<<NUM_FOLDS;
  }
  sg = start_grid;
  for (i=0; i<GRID_SIZE; i++) *g++ = *sg++;
}

double evaluate(int *moves) {
  short *grid;
  double score;
  int i, f;
  grid = malloc(GRID_SIZE * sizeof(short));
  init_grid(grid);
  for (i=0; i<NUM_FOLDS; i++) {
    f = moves[i];
    if (f>0) v_fold(grid,f);
    else h_fold(grid,-f);
  }
  score = score_grid(grid);
  free(grid);
  return score;
}

double optimize_folding(int *moves, double score) {
  int opt_cycle, i, which_fold, new_move, f1, f2, t;
  double s;

  for (opt_cycle=0; opt_cycle<1000; opt_cycle++) {
    for (i=0; i<NUM_FOLDS; i++) {
      which_fold = random() % NUM_FOLDS;
      do {
        if (random()&1) new_move = random() % (GRID_WIDTH-1) + 1;
        else new_move = -(random() % (GRID_HEIGHT-1) + 1);
      } while (moves[which_fold]==new_move);
      t = moves[which_fold];
      moves[which_fold] = new_move;
      s = evaluate(moves);
      if (s>score) moves[which_fold] = t;
      else score = s;
    }
    for (i=0; i<NUM_FOLDS; i++) {
      f1 = random() % NUM_FOLDS;
      do {
        f2 = random() % NUM_FOLDS;
      } while (f2==f1);
      t = moves[f1];
      moves[f1] = moves[f2];
      moves[f2] = t;
      s = evaluate(moves);
      if (s>score) {
        t = moves[f1];
        moves[f1] = moves[f2];
        moves[f2] = t;
      }
      else score = s;
    }
  }

  return score;
}

void show_moves(int *moves) {
  int i, m;
  for (i=0; i<NUM_FOLDS; i++) {
    m = moves[i];
    printf("%c%d%c",(m>0)?'R':'D',abs(m),((i+1)%NUM_FOLDS)?',':'\n');
  }
}

int main() {
  int i, j, moves[NUM_FOLDS], save_moves[NUM_FOLDS];
  double score, best_score = 1.0E+99;

  srandomdev();
  for (i=0; i<400; i++) {
    for (j=0; j<NUM_FOLDS; j++) {
            if (random()&1) moves[j] = random() % (GRID_WIDTH-1) + 1;
            else moves[j] = -(random() % (GRID_HEIGHT-1) + 1);
        }
        score = optimize_folding(moves, 1.0E+99);
        if (score<best_score) {
            best_score = score;
            for (j=0; j<NUM_FOLDS; j++) save_moves[j]=moves[j];
        }
    }
  printf("%.3lf\n",best_score);
  show_moves(save_moves);
  return 0;
}

Bah. Just noticed that the question has changed. I'll have to fix this later...

Currently I'm getting a decent score of 16.34375 for your 40*20.


text:
Operations on Sets
Note: I have accepted an answer, but I'm willing to accept a better answer if it comes.
Write a program that computes operations on sets. You may take input either from standard input or from command line arguments. Your program must be able to compute unions, intersections, relative complements, and cartesian products. Output should be the result of these operations.
You may not use built-in functions to do the work for you.
Input Format
<A> and <B> represent sets. The format for sets can be anything that is convenient, as long as it actually represents a set (no taking advantage of this "looseness"). The elements of a set don't always have to be in the same order because sets aren't ordered. You define what kind of object these elements can be (integers, letters, ...).

Union: union <A> <B>
Intersection: intersect <A> <B>
Relative complement (difference of sets): complement <A> <B>
Cartesian product: product <A> <B> (format for ordered pairs can be anything convenient -- don't take advantage of this "looseness" either)

For info on what these operations even are, see the Wikipedia page on it.

I'm actually not clear on "actually represents a set". How can one determine whether a proposed representation represents the given set? Does it have to be that a representation of a set is always character for character the same? Python fails the previous point because it lists elements in an arbitrary order. What can the elements of these sets be? (Sorry, I should have asked these all while the question was sandboxed).

Could you explain what some of these terms for those that are not so familiar with them?

Can you clarify "You may not use built-in functions to do the work for you"?  Does this mean no built-in functions whatsoever or no built-in functions specifically designed for handling sets?

@DigitalTrauma I mean no built-ins specifically for computing unions, intersections, etc. You may, for example, use eval() to convert a string to your language's representation of a set.

So, I'm guessing T-SQL is out of the running here?

@MichaelB I don't know that language, so ... I don't know.

@golfer9338: SQL in general handles sets of records, which means pretty much everything in the language is geared towards set operations; you'd have a hard time avoiding them.

What do you mean by "any kind of object"? How am I supposed to parse STDIN in a way that can handle any kind of object?

@Ypnypn I mean you define what kind of object your program can handle. Edited question to reflect this.

GolfScript, 73 characters
.' '?:^>~`"~{:^1$?0<{[^]+}*}/
{\\`{[\\]}+/}+%
{?0<!}+,
{?0<}+,"n/^2/2-=~`

Uses non of the GolfScript set operators and should work on all valid GolfScript objects. Input must be given on STDIN, for format see also the online examples.
> union [1 2 3] [2 3 4]
[1 2 3 4]

> intersect [1 2 3] [2 3 4]
[2 3]

> complement [1 2 3] [2 3 4]
[1]

> product [1 2 3] [2 3 4]
[[1 2] [1 3] [1 4] [2 2] [2 3] [2 4] [3 2] [3 3] [3 4]]

The code does not use GolfScript's set operators but implements them using loops.
.' '?        # find the first space character in the input
:^>          # save the position to variable ^ and remove from start of string
~            # evaluate the string (i.e. get two sets as arguments)
`            # transform the second set into a string
"..."n/      # generates an array of 4 strings which represent the set operations
             # (see below)
^2/2-        # take position of the first space (i.e. length of the operator)
             # divide by two, subtract two (i.e. union->0, intersect->2,
             # complement->3, product->1)
=~           # take the corresponding command string and evaluate on the arguments
`            # transform the result back into a string representation

### union
~{           # evaluate the second argument (i.e. revert the ` operation)
             # and loop over all items
  :^         #   save item to variable ^
  1$?        #   is it contained in the first set?
  0<{        #   if no then
    [^]+     #     add to set
  }*         #   end if
}/           # end loop

### intersection
{            # prepend second argument to code block {...}+ and filter the first set
  ?0<!       #   is the current item contained in the second set? if yes, keep
}+,          # end filter block

### complement
{            # prepend second argument to code block {...}+ and filter the first set
  ?0<!       #   is the current item contained in the second set? if no, keep
}+,          # end filter block

### product
{            # prepend second argument to code block {...}+ and map on first set
  \`{        #   take current item and prepend to code block `{...}+ and iterate
    [\]      #     swap both items (item of second set + item of first set) and
             #     build a tuple of them
  }+/        #   end loop
}+%          # end map

Ruby, 97 characters
$_,a=$*;A,B=eval a
p (~/c/?B.map{|i|~/d/?A.map{|j|[i,j]}:!A.index(i)^~/m/?p: i}:A+B).uniq.compact

Usage examples:
$ ruby set.rb union [[1,2,3],[8]]
[1, 2, 3, 8]
$ ruby set.rb complement [[1,2,3,6,7],[7,2,1,5]]
[5]
$ ruby set.rb intersect [[1,2,3,6,7],[7,2,1,5]]
[7, 2, 1]
$ ruby set.rb product [[1,2],[7,5,2]]
[[[7, 1], [7, 2]], [[5, 1], [5, 2]], [[2, 1], [2, 2]]]

you can swap .compact for -[p] iirc

GolfScript, 77 characters
(\~@99-:x{6x={&}{13x={'"#{['@','*+'].product ['+\','*+']}"'+~}{|}if}if}{-}if`

Sample inputs and outputs:
$ echo "union [1 2 3] [2 3 4]" | golfscript setops.gs
[1 2 3 4]
$ echo "intersect [1 2 3] [2 3 4]" | golfscript setops.gs
[2 3]
$ echo "complement [1 2 3] [2 3 4]" | golfscript setops.gs
[1]
$ echo "product [1 2 3] [2 3 4]" | golfscript setops.gs
"[[1, 2], [1, 3], [1, 4], [2, 2], [2, 3], [2, 4], [3, 2], [3, 3], [3, 4]]"

Okay, now time to explain this gobbledygook. First, here's an explanation of how it chooses which one of the four blocks (union, intersect, complement, product) to execute.
I noticed something convenient about these commands. They each begin with a unique letter (u, i, c, p). Therefore, we only care about this first letter.
Now, to make the code even shorter, these can be converted into ASCII codes (117, 105, 99, 112). Here's an explanation of the main logic of the program:
(     # grab the ASCII code of the first letter of the input string
\~    # evaluate the rest of the string. GS will ignore "nion", "tersect", etc.
@     # stack is now [A B CMD]
99-:x # subtract 99 for shorter code. Now 'uicp' maps to [18 6 0 13]

After this comes a huge chain of ifs. With the set operation logic removed, it looks like this:
{6x={INTERSECT_CODE}{13x={PRODUCT_CODE}{UNION_CODE}if}if}{COMPLEMENT_CODE}if`

Converted to a more readable C-like format, it looks like this:
if (x) {
  if (x == 6) {
    INTERSECT_CODE
  } else {
    if (x == 13) {
      PRODUCT_CODE
    } else {
      // x must be 18
      UNION_CODE
    }
  }
} else {
  // x is 0
  COMPLEMENT_CODE
}

Now, it's just a matter of looking at the code for the set operations. Most of them are fairly straightforwards: & for intersect, | for union, and - for complement. However, GolfScript doesn't have a built-in product operator, so I had to build some Ruby code for that. Here's an explanation of that mess:
'"#{['         # stack: [1 2 3] [2 3 4] '"#{['
@','*+         # stack: [2 3 4] '"#{[1,2,3'
'].product ['+ # stack: [2 3 4] '"#{[1,2,3].product ['
\','*+         # stack: '"#{[1,2,3].product [2,3,4'
']}"'+         # stack: '"#{[1,2,3].product [2,3,4]}"'
~              # evaluate

Simply tack on a ` to show array output correctly, and it's done!

Well played ... using only the first character to know which command to use.

I guess there is a shorter product implementation in GolfScript ;-)

Doesn't this solution violate the You may not use built-in functions to do the work for you.?

@Howard I interpret that as: no set(input())|set(input()) in python (as an example).

@Quincunx Which - if you translate the python to GolfScript - is exactly what the code does.

@Howard Hmm, I thought that meant "You can't use eval(input()) if your language has functions called "union," "intersect," etc. As far as I know, there's not very many other ways you could do this in GS, but I'll try changing it to calculate manually.

@Howard Whoops. I didn't look closely enough.

You can probably drop a few characters by comparing the character mod 8 (which yields [5,1,3,0]).

Bash+coreutils, 200 bytes
I'm not exactly sure what "You may not use built-in functions to do the work for you" means, but I am assuming it means no use of APIs specifically designed for handling sets.  Some of the coreutils used here might be considered to come close, but I am asserting that these utilities operate on files and lines of files, and not specifically on sets:
f()(tr \  \\n<<<$1|sort -u)
c()(comm -2$1 <(echo "$a") <(echo "$b"))
a=`f "$2"`
b=`f "$3"`
case $1 in
u*)sort -u<<<"$a
$b";;i*)c 1;;c*)c 3;;p*)eval printf '%s\\n' {${a//$'\n'/,}},{${b//$'\n'/,}};;esac

The union, intersect and complement cases are relatively uninteresting calls to sort and comm.
The product case uses bash brace expansion.  For example echo {1,2,3},{a,b} produces the output 1,a 1,b 2,a 2,b 3,a 3,b.  The catch here is that brace expansion normally occurs before variable expansion, so the whole thing must be evaled so the variables are effectively expanded first.
Example output:
$ ./sets.sh union "1 2 3 4 3 2 1" "2 4 6 4 6"
1
2
3
4
6
$ ./sets.sh intersect "1 2 3 4 3 2 1" "2 4 6 4 6"
2
4
$ ./sets.sh complement "1 2 3 4 3 2 1" "2 4 6 4 6"
1
3
$ ./sets.sh product "1 2 3 4 3 2 1" "2 4 6 4 6"
1,2
1,4
1,6
2,2
2,4
2,6
3,2
3,4
3,6
4,2
4,4
4,6
$

Haskell, 123 96 bytes
Saved the import Control.Applicative part since liftA2 is now in Prelude.
Not sure whether this is considered cheating, but:
union=liftA2(||)
intersect=liftA2(&&)
complement f=liftA2(&&)f.(not.)
product f g (x,y)=f x&&g y

If allowed, product could be curried to save extra 1 byte.
The key idea is to implement sets as a predicate (a -> Bool) that returns True if the element is present. This can represent not only finite sets, but also infinite sets.
Being possibly infinite, the outputted set cannot be represented in a string, but it can be queried:
Prelude> union (\_->False) (\_->False) 0
False
Prelude> union (\_->False) (\_->True) 0
True
Prelude> union (\_->False) even 0
True
Prelude> union (\_->False) odd 0
False
Prelude> union even odd 0
True
Prelude> intersect (\_->False) (\_->True) 0
False
Prelude> intersect (\_->True) even 0
True
Prelude> intersect odd even 0
False
Prelude> complement (\_->True) even 0
False
Prelude> complement (\_->True) odd 0
True
Prelude> product even odd (0,0)
False
Prelude> product even odd (0,1)
True
Prelude> product even odd (1,1)
False

Axiom, 186 bytes
union(a,b)==removeDuplicates concat(a,b)
intersection(a,b)==[x for x in a|member?(x,b)]
complement(a,b)==[x for x in a|~member?(x,b)]
product(a,b)==concat[[[x,y]for y in b]for x in a]

All input for above function has to be List [of ints] that have not repetition (for to be a set).
Here the necessary functions for see if one List is a set and for see if two set are equals:
isEq?(a,b)==(#a~=#b=>false;(sort(a)=sort(b))@Boolean)
isSet?(a)==isEq?(removeDuplicates(a),a)

Some results
(9) -> union([1,2,3], [2,3,4])
   (9)  [1,2,3,4]
                                               Type: List PositiveInteger
(10) -> intersection([1,2,3], [2,3,4])
   (10)  [2,3]
                                               Type: List PositiveInteger
(11) -> complement([1,2,3], [2,3,4])
   (11)  [1]
                                               Type: List PositiveInteger
(12) -> product([1,2,3], [2,3,4])
   (12)  [[1,2],[1,3],[1,4],[2,2],[2,3],[2,4],[3,2],[3,3],[3,4]]
                                          Type: List List PositiveInteger

TypeScript's Type System, No Ignore, 353 339 222 219 Bytes
type X<S>=S extends`${infer O extends"u"|"i"|"c"|"p"}${any} ${infer A} ${infer B}`?{u:X<A|B>,i:X<A>&X<B>,c:Exclude<X<A>,X<B>>,p:{[K in X<A>]:{[I in X<B>]:[K,I]}}[X<A>][X<B>]}[O]:S extends`${infer A},${infer R}`?A|X<R>:S

Explanation
We can check the first character (infer O) to check if it's union, intersect, complement, or product. However, if it doesn't extend it, we can parse the array of values provided (as this is a self-recursive function). Set operations are native to TypeScript's Type System, so implementing each one is trivial, with union and intersect being native TS operators (| and & accordingly), cartesian joins using a joined json object, and complement using the Exclude type.
TypeScript Playground

Here's 222 bytes with ignore or 260 bytes without ignore. BTW complement is Exclude

209 with ignore or 247 without ignore

You can also inline the type you have into the type, saving 23 characters.

Huh, when I tried that it ended up adding more bytes due to the longer variable names. I must have made a mistake

By the way, you might want to add explanations of how your submissions work in the future for people who know nothing about advanced TS types.

I think X<A>|X<B> can be X<A|B> for -3

PowerShell, 131
param($o,[array]$a,[array]$b)switch($o[0]){'u'{$a+$b|sort -u}'i'{$a|?{$_-in$b}}'c'{$b|?{$_-notin$a}}'p'{$a|%{$x=$_
$b|%{"$x,$_"}}}}

Fairly straightforward rendition of all the operators. Sets are given as comma-separated lists and the script takes arguments:
PS> .\set.ps1 union 1,2,3 8
1
2
3
8
PS> .\set.ps1 intersect 1,2,3,6,7 7,2,1,5
1
2
7
PS> .\set.ps1 complement 1,2,3,6,7 7,2,1,5
5
PS> .\set.ps1 product 1,2 7,5
1,7
1,5
2,7
2,5

R, 105 bytes
function(A,B)list(U<-unique(c(A,B)),U[U%in%A&U%in%B],A[!A%in%B],cbind(rep(A,sum(B|1)),rep(B,e=sum(A|1))))

Try it online!
Returns a list with four elements, the Union, the Intersection, the Difference, and the Cartesian Product, in that order.
Takes input as an R vector of integers.
The Union is the unique values in the concatenation of the two vectors, U=unique(c(A,B)).
The Intersection is the subset of the Union where x in A & x in B, so U[U%in%A&U%in%B].
The Set Difference is those a in A where a notin B, so A[!A%in%B]
The Cartesian Product is returned as a matrix where each row is an ordered pair. It repeats A |B| times and the elements of B |A| times each, then binds them together as matrix columns, i.e.:
cbind(                # bind as matrix columns
 rep(A,sum(B|1)),     # repeat A |B| times (concatenate |B| copies of A)
 rep(B,e=sum(A|1)))   # repeat each element of B |A| times

APL NARS 100 chars
union←{∪⍺,⍵}⋄intersection←{(⍺∊⍵)/⍺}⋄complement←{(∼⍺∊⍵)/⍺}
∇r←x product y;i;j
r←⍬⋄:for i:in x⋄:for j:in y⋄r←r,⊂(i,j)⋄:endfor⋄:endfor

the symbol ∪ in union above means "each elment appear one time only"
so it doesn't make union. They are about 135 chars but if i cut the names of anonimous functions
it would be 100 chars(25+19+56=100 chars). Test
  1 2 3 union 2 3 4
1 2 3 4
  1 2 3 intersection 2 3 4
2 3
  1 2 3 complement 2 3 4
1
  1 2 3 product 2 3 4
1 2  1 3  1 4  2 2  2 3  2 4  3 2  3 3  3 4

The APL functions for doing above union, intersection, complement and product could be:
  sysunion←∪
  sysintersection←∩
  syscomplement←∼
  sysproduct←{,⍺∘.,⍵}
  1 2 3 sysunion 2 3 4
1 2 3 4
  1 2 3 sysintersection 2 3 4
2 3
  1 2 3 syscomplement 2 3 4
1
  1 2 3 sysproduct 2 3 4
1 2  1 3  1 4  2 2  2 3  2 4  3 2  3 3  3 4
  x←1 3
  y←2 3
  x sysproduct y
1 2  1 3  3 2  3 3