text:
When does (x == x+2)?
The challenge: Define x in such a way that the expression (x == x+2) would evaluate to true.
I tagged the question with C, but answers in other languages are welcome, as long as they're creative or highlight an interesting aspect of the language.
I intend to accept a C solution, but other languages can get my vote.

Correct - works on standard-compliant implementations. Exception - assuming an implementation of the basic types, if it's a common implementation (e.g. assuming int is 32bit 2's complement) is OK.
Simple - should be small, use basic language features.
Interesting - it's subjective, I admit. I have some examples for what I consider interesting, but I don't want to give hints. Update: Avoiding the preprocessor is interesting.
Quick - The first good answer will be accepted.

After getting 60 answers (I never expected such prticipation), It may be good to summarize them.
The 60 answers divide into 7 groups, 3 of which can be implemented in C, the rest in other languages:

The C preprocessor. #define x 2|0 was suggested, but there are many other possibilities.
Floating point. Large numbers, infinity or NaN all work.
Pointer arithmetic. A pointer to a huge struct causes adding 2 to wrap around.
The rest don't work with C:
Operator overloading - A + that doesn't add or a == that always returns true.
Making x a function call (some languages allow it without the x() syntax). Then it can return something else each time.
A one-bit data type. Then x == x+2 (mod 2).
Changing 2 - some language let you assign 0 to it.

Why the explicit hate for the preprocessor?  It's a legitimate part of the language, and in C's case, of the culture.

@JB, I don't hate the preprocessor. But it makes this specific question too easy. Without it, there's a challenge.

Why 4. Quick? You mean "Whoever knows one and is lucky enough to read this question first"?

@Luc, Basically yes. I think it's more fair than "the answer I like best", and I saw no better way to choose between the correct answers.

@ugoren Let the community vote (and vote yourself for ones you like), then choose the top answer after 7 days or so :)

@Luc, I do let the community vote (and vote myself for ones I like). But as the question owner, I think I have the right to determine the accepted answer, regardless of the votes.

It should be pretty trivial to define a class with overloaded operators that would take care of this.

Regarding possibility 2: NaN doesn't work. NaN+2 is again NaN, but NaN==NaN is false.

@MartinB, I guess you're right, fixed. You could make another question of it - when does x != x?

Shame... in old versions of Sage, you could just set 2=0

The Scala solution, where x is a Set containing '2', and + means add to Set by the standard library, without redefining + yourself, doesn't fit into these 7 categories, IMHO.

@userunknown, You're right, though I'd call it a sub-category of overloading. The main point is that + does something other than addition.

When Jon Skeet.

You can use bitfields like a one-bit data type, so actually it works with C

does javascript x=NaN work?

Why are this question and all the answers Community Wiki?

Could x be declared as volatile int, and its memory location mapped to some device that decrements it by 2 the first time it is read?  I guess this requires the C standard to specify a left-to-right order of evaluation for the operands of ==. I don't recall if it does (but I suspect that it leaves the order unspecified).

main()
{
double x=1.0/0.0;
printf("%d",x==x+2);
}

Outputs 1.
Link: http://ideone.com/dL6A5

float x=1./0 is a bit shorter and perhaps more elegant. But anyway, this surely is the first good answer.

Ahh good old divide by zero. That took me longer to figure out than I'd like to admit. haha

Argh, I also though of this, but on Windows is doesn't compile so I dropped it. :( +1 though

x=1e999 is another way of doing this.

@shiona float x=1e20 would be enough

Fortran IV:
2=0

After this every constant 2 in the program is zero. Trust me, I have done this (ok, 25 years ago)

All the more reason for me to never touch Fortran.

Does it at least throw a warning?

@MichaelStern WARNING: YOU ARE CHANGING THE VALUE OF 2!

This seems to work:
#define x 2|0

Basically, the expression is expanded to (2|0 == 2|(0+2)). It is a good example of why one should use parentheses when defining macros.

Certainly works, and I think it's the most elegant preprocessor based solution. But I think doing it without the preprocesor is more interesting.

Is it just me or should 2|(0+2) be 1?

@phunehehe: | is bitwise OR; || is logical OR.

Uh, I thought it was /, silly me :">

This somehow reminds me of little Bobby Tables.

can anybody tell me how does (2|0 == 2|0+2) become (2|0 == 2|(0+2)) ?

@rakeshNS: I added the extra set of parentheses to show operator precedence. That's why I said "Basically".

Brainfuck
x

This does of course stretch "evaluate to true" a bit, because in Brainfuck nothing actually evaluates to anything – you only manipulate a tape. But if you now append your expression
x
(x == x+2)

the program is equivalent to
+

(because everything but <>+-[],. is a comment). Which does nothing but increment the value where we are now. The tape is initialised with all zeros, so we end up with a 1 on the cursor position, which means "true": if we now started a conditional section with [], it would enter/loop.

+1 Must be the most creative bending of the rules.

Why do you need the x?

@James The question says to define x so here x is defined as x.

@James the answer doesn't need anything except the +

F#
let (==) _ _ = true
let x = 0
x == (x + 2) //true

I like this one. Instead of juggling numbers, simply redefine the meaning of ==

Hang on, isn't the equality operator in F# simply =? == isn't even defined by default.

C
int main() { float x = 1e10; printf("%d\n", x == x + 2); }

Note: may not work if FLT_EVAL_METHOD != 0 (see comments below).

+1 for real-world applications. Too many people don't understand floating point mathematics.

@mbomb007: I think they are different - the answer you link to relies on INF + 2 == INF, whereas my answer uses a single precision float which is large enough that 2 is less than one ULP.

@mbomb007: I also think they're very different - ∞ + 2 = ∞ is something anyone could understand and doesn't depend on anything computer specific, whereas adding 2 to a concrete number and it having no effect is a bit more surprising and specific to the limited precision of computers, and more interesting IMHO

This can readily fail when FLT_EVAL_METHOD == 1 as the math is done as double.  Recommend a larger FP value sure to exceed even long double precision like 1.0e37f

@chux: thanks - I wasn't aware of FLT_EVAL_METHOD - out of interest, do you know of any platforms/environments where it's set to something other than 0 ?

@PaulR float x = 1e10; printf("%d %d\n", x == x + 2, FLT_EVAL_METHOD); prints 0 2 on 64-bit PC "gcc version 5.4.0".  x = 1e37f; works there as hoped.

@chux: interesting - so are both float_t and double_t typedef'd to long double in that environment ? ("all operations and constants evaluate in the range and precision of long double. Additionally, both float_t and double_t are equivalent to long double")

@PaulR Do not use float_t much.   C11 §7.12 2 confirms your comment and my printf("%d %zu %zu\n", FLT_EVAL_METHOD, sizeof (float_t), sizeof (long double)); --> 2 12 12  LSNED

@chux: thanks for the confirmation - that's definitely something I may need to watch out for in future, as much of my code ends up being cross-platform.

C#
class T {
  static int _x;
  static int X { get { return _x -= 2; } }

  static void Main() { Console.WriteLine(X == X + 2); }
}

Not a shortie, but somewhat elegant.
http://ideone.com/x56Ul

Dang it, just got a 'Nice Answer' badge for this post. Seriously, getting badges for EVIL stuff?! Don't do this at home!

It's evil, but it's so beautiful...

Scala: { val x = Set(2); (x == x + 2) }

Haskell: Define ℤ/2ℤ on Booleans:
instance Num Bool where
    (+) = (/=)
    (-) = (+)
    (*) = (&&)
    negate = id
    abs    = id
    signum = id
    fromInteger = odd

then for any x :: Bool we'll have x == x + 2.
Update: Thanks for the ideas in comment, I updated the instance accordingly.

You can simplify: fromInteger = odd

Also (+) can be defined as (/=) I believe.

Shorter solution would be to make an instance for ().

GNU C supports structures with no members and size 0:
struct {} *x = 0;

Very nice! I thought about pointer arithmetic with very large data leading to wraparound, but didn't think of the opposite.

Python
class X(int):__add__=lambda*y:0
x=X()

# Then (x == x+2) == True

Nice. All languages which support operator overloading can use similar solutions, but C isn't one of them.

Also works with overloading __cmp__ as class X(int):__cmp__=lambda*x:0 (or __eq__ though slightly longer class X(int):__eq__=lambda*x:True

A couple characters shorter if you dont extend from int.. class X:__add__=lambda s,o:s

May I ask what that multiplication does?

@TheRare it's not actually multiplication. Because __add__ is normally given multiple arguments (lambda x,y:), I save some characters by using * to pack all the arguments into a tuple (lambda *y:). See the docs for more info.

Ah. I forgot that completely.

PHP:
$x = true;
var_dump($x == $x+2);

Or:
var_dump(!($x==$x+2));

Output:

bool(true)

I was actually trying to come up with this dead-simple PHP answer, but you beat me to it.

It's a common misconception that in C, whitespace doesn't matter. I can't imagine somebody hasn't come up with this in GNU C:
#include <stdio.h>
#define CAT_IMPL(c, d) (c ## d)
#define CAT(c, d) CAT_IMPL(c, d)
#define x CAT(a, __LINE__)

int main()
{
    int a9 = 2, a10 = 0;
    printf("%d\n", x ==
        x + 2);
    return 0;
}

Prints 1.

Nice, though perhaps not technically valid (x == x+2 is still false). But once you bring up the idea, I think #define x -2*__LINE__ is more elegant.

@ugoren thanks! If you want all this to be on one line, use COUNTER instead of LINE - requires GCC 4.3+ though.

_CAT is reserved identifier. Anything that starts with underscore, and uppercase letter is reserved in C.

@xfix that's exactly right, updated to remove UB.

C
It's more interesting without using macros and without abusing infinity.
/////////////////////////////////////
// At the beginning                 /
// We assume truth!                 /

int truth = 1;
int x = 42;

/////////////////////////////////////
// Can the truth really be changed??/
truth = (x == x + 2);

/////////////////////////////////////
// The truth cannot be changed!     /
printf("%d",truth);

Try it if you don't believe it!

0. Nope, still don't believe it.

@MSalters: What compiler do you use? You might have trigraphs disabled.

VS2010. Quite possible that trigraphs are disabled by default. Either that or line concatenation doesn't work with ??\

MSalters: the trigraph ??\  is to be converted into a single \ , so there is no ??\ . Some modern compilers however give warnings by default to both trigraphs and line concatenations even if enabled.

Mathematica:
x /: x + 2 := x
x == x + 2

I think this solution is novel because it uses Mathematica's concept of Up Values.
EDIT:
I am expanding my answer to explain what Up Values mean in Mathematica.
The first line essentially redefines addition for the symbol x. I could directly store such a definition in the global function that is associated with the + symbol, but such a redefinition would be hazardous because the redefinition may propagate unpredictably through Mathematica's built-in algorithms.
Instead, using the tag x/:, I associated the definition with the symbol x. Now whenever Mathematica sees the symbol x, it checks to see whether it is being operated on by the addition operator + in a pattern of the form x + 2 + ___ where the symbol ___ means a possible null sequence of other symbols.
This redefinition is very specific and utilizes Mathematica's extensive pattern matching capabilities. For example, the expression x+y+2 returns x+y, but the expression x+3 returns x+3; because in the former case, the pattern could be matched, but in the latter case, the pattern could not be matched without additional simplification.

I think you should explain what it does. Most people don't know Mathematica (or what Up Values are).

Thank you @ugoren, I spend most of my time on the Mathematica Stack Exchange website, so I forgot to explain what made my example meaningful. I made an edit that explains the concept as concisely I could.

scheme
(define == =)
(define (x a b c d) #t)
(x == x + 2)
;=> #t

Nice. Scheme's (x == x + 2) looks just like C's, but means a totally different thing.

Now do it for (= x 2).

(define (x a b c d) #t) :)

@ugoren this is defined to do this by this program. x is simply a name of a function here. And so is ==

Javascript:
var x = 99999999999999999;
alert(x == x+2);

Test Fiddle

You could use Infinity, or -Infinity, and because of this you could use the shortcut of x = 1/0.

@zzzzBov: That's definitely a better code golf.  I chose (99999999999999999 == 99999999999999999+2) because I think it's a bit more interesting than (Infinity == Infinity+2), though as the OP says, "it's subjective" :)

This is the only real-world case in which I saw a check like this for a good reason (besides programming riddles):  A (float-based) faculty-function was checking its input for being too great to be counted down by -1 and recursing.  The language itself was Python, but that does not really matter in this case.

Smaller: x="";alert(x==x+2). == in javascript always compares two strings as true.

@NicoBurns not ture :(

@NicoBurns, running that code in the console produces false; wherever you're getting that info on JS is wrong and should not be trusted.

I stand corrected. I did try this out in the chrome console to test it, but I must have done something wrong as I am also getting false now.

@NicoBurns You must have been caught by the fact most dynamic languages evaluate strings to true in an if statement (as in if('string')...), or some other kind of type juggling. But different strings are != between each other.

Obvious answer:
When this terminates:
while (x != x+2) { }
printf("Now");

+1 http://meta.codegolf.stackexchange.com/a/1070/8766 but this is actually ingenious.

I think while(!(x == x+2)) {} would be more in spirit

This answer predates that meta post with two years. Everything that is considered a cliche today was novel at some point.

Here is a solution for JavaScript that does not exploit the Infinity and -Infinity edge cases of floating-point addition. This works neither in Internet Explorer 8 and below nor in the opt-in ES5 strict mode. I would not call the with statement and getters particularly "advanced" features.
with ({ $: 0, get x() {return 2 * this.$--;} }) {
    console.log(x == x+2);
}

Edited to add: The above trick is also possible without using with and get, as noted by Andy E in Tips for golfing in JavaScript and also by jncraton on this page:
var x = { $: 0, valueOf: function(){return 2 * x.$++;} };
console.log(x == x+2);

A nice concept - making x be a function call, although it looks like a variable read. I assumes left-to-right evaluation order, but it's OK since it's specified in JS (unlike C).

The following is not standards compliant C, but should work on just about any 64-bit platform:
int (*x)[0x2000000000000000];

Great in principle, but seems to be implemented wrong. x would be incremented in steps of 2^61, so x + 8 would equal x.

@ugoren, it works for me, on Linux with 4-byte int.

You're absolutely right. I missed the fact that it's an array of int, not char.

Common Lisp
* (defmacro x (&rest r) t)
X
* (x == x+2)
T

It's pretty easy when x doesn't have to be an actual value.

Sage:
x=Mod(0,2)
x==x+2

returns True
In general for GF(2**n) it's always true that x=x+2 for any x
This is not a bug or an issue with overflow or infinity, it's actually correct

Same trick works with PARI/GP

Perl 6
I'm surprised to not see this solution before. Anyway, the solution is - what if x is 0 and 2 at once? my \x in this example declares sigilless variable - this question asks about x, not Perl-style $x. The ?? !! is ternary operator.
$ perl6 -e 'my \x = 0|2; say x == x + 2 ?? "YES" !! "NO"'
YES

But...
$ perl6 -e 'my \x = 0|2; say x == x + 3 ?? "YES" !! "NO"'
NO

x is multiple values at once. x is equal to 0 and 2 at once. x + 2 is equal to 2 and 4 at once. So, logically they're equal.

APL (Dyalog)
X←1e15
X=X+2

APL does not even have infinity, it's just that the floats aren't precise enough to tell the difference between 1.000.000.000.000.000 and 1.000.000.000.000.002. This is, as far as I know, the only way to do this in APL.

I really like this because it's the first answer to exploit float precision.

@AndrewKS: Actually Paul R was a bit earlier.

Python 2.X (Using redefinition of (cached) integers)
I've noticed all of the python answers have defined classes that redefine the + operator. I'll answer with an even more low-level demonstration of python's flexibility. (This is a python2-specific snippet)
In python, integers are stored more or less this way in C:
typedef struct {            // NOTE: Macros have been expanded
    Py_ssize_t ob_refcnt;
    PyTypeObject *ob_type;
    long ob_ival;
} PyIntObject;

That is, a struct with a size_t, void *, and long object, in that order.
Once we use, and therefore cache an integer, we can use python's ctypes module to redefine that integer, so that not only does x == x+2, but 2 == 0
import ctypes
two = 2 # This will help us access the address of "2" so that we may change the value

# Recall that the object value is the third variable in the struct. Therefore,
# to change the value, we must offset the address we use by the "sizeof" a
# size_t and a void pointer
offset = ctypes.sizeof(ctypes.c_size_t) + ctypes.sizeof(ctypes.c_voidp)

# Now we access the ob_ival by creating a C-int from the address of
# our "two" variable, offset by our offset value.
# Note that id(variable) returns the address of the variable.
ob_ival = ctypes.c_int.from_address(id(two)+offset)

#Now we change the value at that address by changing the value of our int.
ob_ival.value = 0

# Now for the output
x = 1
print x == x+2
print 2 == 0

Prints
True
True

Python
exploiting floating point precision makes this very simple.
>>> x = 100000000000000000.0
>>> (x == x+2)
True

To make it less system specific requires an extra import
>>> import sys
>>> x = float(sys.maxint + 1)
>>> (x == x+2)
True

This should work in other languages too.
This works because the reprensentation of 100000000000000000.0 and 100000000000000002.0 are exactly the same for the machine, because of the way floating points are represented inside the machine.
see http://en.wikipedia.org/wiki/IEEE_floating_point for more information.
So this will basically work in any language that allows you to add integers to floats and have the result of this be a float.

Perl
using a subroutine with side-effects on a package variable:
sub x () { $v -= 2 }
print "true!\n" if x == x + 2;

Output: true!

sub x{} "works" as well.. (at least in my 5.10.1), but i can't figure why..

Because sub x{} returns either undef or an empty list, both of which are a numeric zero. And x + 2 is parsed as x(+2). perl -MO=Deparse reveals print "true\n" if x() == x(2);

That's awesome, @mykhal and @Perleone!

Here is a solution for C++ based on operator overloading. It relies on implicit conversion from an enum to an int.
#include <iostream>

enum X {};
bool operator==(X x, int y)
{
    return true;
}

int main()
{
    X x;
    std::cout << std::boolalpha << (x == x+2) << std::endl;
    return 0;
}

You can use std::boolalpha instead of ?:.

I know it's a code challenge... but I golfed it. Sorry.
Ruby - 13 characters - Infinity solution
x=1e17;x==x+2

returns true
Ruby - 41 characters - Op Overloading solutions
class Fixnum;def + y;0 end end;x=0;x==x+2

or
class A;def self.+ y;A end end;x=A;x==x+2

If it is ok to exploit the question a little bit, then I will add some new Java. The trick is for sure not new, but perhaps interesting that this is possible in Java.
static void pleaseDoNotDoThis() throws Exception {
    Field field = Boolean.class.getField("FALSE");
    field.setAccessible(true);
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    field.set(null, true);
}

public static void main(String args[]) throws Exception {
    pleaseDoNotDoThis();
    doit(1);
    doit("NO");
    doit(null);
    doit(Math.PI);
}

static void doit(long x) {
    System.out.format("(x == x + 2) = (%d == %d) = %s\n", x, x+2, (x == x + 2));
}

static void doit(String x) {
    System.out.format("(x == x + 2) = (%s == %s) = %s\n", x, x+2, (x == x + 2));
}

static void doit(double x) {
    System.out.format("(x == x + 2) = (%f == %f) = %s\n", x, x+2, (x == x + 2));
}

And the results:
(x == x + 2) = (1 == 3) = true
(x == x + 2) = (NO == NO2) = true
(x == x + 2) = (null == null2) = true
(x == x + 2) = (3,141593 == 5,141593) = true
(x == x + 2) = (Infinity == Infinity) = true

This VBScript solution works similarly to my JavaScript solution. I did not use a preprocessor yet the solution seems trivial.
y = 0
Function x
x = y
y = -2
End Function

If x = x + 2 Then
    WScript.Echo "True"
Else
    WScript.Echo "False"
End If

I was going to post the very same solution in ruby, until I saw yours - it's possible because both languages permit omission of the parentheses.

Java
double x = Double.POSITIVE_INFINITY; // Double.NEGATIVE_INFINITY also works
System.out.println(x == x + 2);      // prints true

This is essentially the same as the accepted answer at http://codegolf.stackexchange.com/a/7169/12205

Common Lisp
(let ((x   42)
      (x+2 42))
  (= x x+2))
;=> true

C#
I didn't see any rule stating x had to be a number:
class Program {
    public static Program operator +(Program x, int y) {
        return x;
    }

    static void Main(string[] args) {
        var x = new Program();
        Console.WriteLine(x == x + 2);
    }
}

I defined x in such a way, but I also defined the + operator for the object stored in x.
http://ideone.com/ylNyM

JavaScript
Here's a way do it without exploiting Infinity:
x = {
    value: 0,
    valueOf: function () {
        this.value += 2;
        return this.value;
    }
};

alert(x == x+2);

C
If you evaluate x == x+2 directly you will get a false, but I think it is interesting because it makes usage of a different language feature.
#include <stdio.h>

typedef struct {
  int bit:1;
} bitpack;

#define x a.bit
#define y b.bit

main()
{
  bitpack a, b;
  y = x + 2;
  if (x==y)
    printf("true\n");
  else
    printf("false\n");
}

C
let the computer find a value for x
int main()
{
  float x=0;
  while(x!=x+2)x+=2;
  printf("%f\n",x);
}

Haskell

Prelude> instance Num Bool where (+) _ _ = True
Prelude> let x = True
Prelude> (x==x+2)
True

You could call that cheating but I assume that's what this is about :D
To make it work with more than just bool:

import Prelude hiding ((==),(+))
infixl 9 ==
(==) _ _ = True
(+) _ _ = True

Ada
procedure test() is
  type x_type is mod 2;
  var x: x_type := 0; -- 0 or 1
begin
  if x /= x + 2 then
    put('Error');
  else
    put('Equal!');
  end if;
end test;

This is similar to Sage. We use a 1 bit integer which is allowed to wrap. We could also use a floating point, obviously.

GAP
gap> x:=[];
[  ]
gap> x=x+2;
true

Here x is an empty array.
gap> x:=Z(2);
Z(2)^0
gap> x=x+2;
true

Here x is a generator of GF(2).
gap> x:=Integers;
Integers
gap> x=x+2;
true

Here x is the set of integers.

Bash (0 character)
According to the rule, it looks like I can suggest my 0 character definition of x in bash, since without any definition, I have:
if (x==x+2); then echo "true"; fi

Output
true

Is it fair?

You need the expression x == x+2 to evaluate to true in some way. What you are doing is trying to output true regardless of the comparison result.

Your comment and downvote isn't totally fair; my piece of bash code is merely here for proving the test is true (because bash doesn't display 'true' by itself); if you replace the expression with something evaluating to false, the result will be different: if false; then echo "true"; fi

Sorry, I misunderstood your code. What you actually do is define x to be =x+2, and the definition is always true (the rule allows this, since it shows an interesting aspect of the language). I mistakenly thought the true on its own is a command.

Scala
case object x {
  def +(n:Int) = this
}
//defined module x

x == x + 2
//res0: Boolean = true

Java:
Float x = Float.MAX_VALUE;
System.out.println(x == (x + 2));

It prints "true"
System.out.println(x);

prints 3.4028235E38
System.out.println(x+2);

prints 3.4028235E38
I think this is caused by the loss of precision.

In my opinion, x must have a data type of just ONE BIT.
Since C99, there is the data type _Bool ; So this should probably work:
_Bool x;
x = 0;
if (x == x + 2) ...

shouldn't x be promoted to int in expresseon x+2?

PHP
<?php
  $x = 1e17;
  echo $x==$x+2;

Works in many other languages as well.

Ruby
def x;1.0/0;end
puts (x == x+2) #=> true

Tcl, 22 chars.
proc (x args return\ 1

I don't know tcl but where is x+2 here?

if you execute (x == x+2) after that, it will return 1.

J
x =: 1

There is no == operator in J, sox==x+2 would actually mean x=(=(x+2)). Unary = is an operator, that will return 1 acting on any number, and as binary it is just an equality. So 1=(=(1+2)) => 1=(=3) => 1=1 => 1.

JavaScript
x=Math.log(0)
x==x+2

Prints
True

C#
Using infinity
Double x = Double.PositiveInfinity;
Console.WriteLine(String.Format("Result: {0}", x == x + 2));

Also works with
Double x = Double.NegativeInfinity

(this is actually the same as 1.0 / 0.0 approach)

PHP
$isi = 1.0E+17;
var_dump($isi == $isi + 2);

$isi = 1e18;
var_dump($isi == $isi + 2);

$isi = 4.2E+20;
var_dump($isi == $isi + 2);

$isi = 9.2233720368548E+18;
var_dump($isi == $isi + 2);

$isi = 5.0E+19;
var_dump($isi == $isi + 2);

$isi = 6.0822444802213E+18;
var_dump($isi == $isi + 2);

$isi = 0x5468792130ABCDEF;
var_dump($isi == $isi + 2);

$isi = 6082244480221302255;
var_dump($isi == $isi + 2);

Python:
>>> x=float('inf')
>>> x==x+2
True

Haskell
f x = x == (x+2) where (==)=(<)

Always returns True, except when x is 1/0.

Pascal
Here's a solution that takes a different approach (not the usual infinity trick).
Program xplus2;

Var value: integer;

Function x: integer;
Begin
   value := value-2;
   x := value;
End;

Begin
   If x=x+2 then
      Writeln('They are the same')
   else
      WriteLn('They are different');
End.

Works with 2+x too.

Nice idea but I don't the think the order of evaluation for your x=x+2 expression is guaranteed, so whether this works or not will be compiler-dependent.

Python
>>> x=1e999
>>> x==x+2
True

JavaScript
var x = Infinity;

So if you add anything to infinity it will remain infinity.

Trying to come up with something that doesn't fall under one of the existing seven groups is tough:
def x
  rand(1..3)
end

puts x==x+2

33% of the time, it's right all the time...

I get 100% of the time “TypeError: can't convert Range into Integer”. (At least with Ruby 1.9.2.) In case you correct the syntax to rand 3 (that will result range 0..2, but should not matter for the result), you will get 11.11% correct answers. That is because you are comparing 2 random numbers and both have to take a certain value: the 1st number must be 0 and the 2nd 2. The 1st will be 0 in 33.33% of the tries, the 2nd will be 2 also in 33.33% of the tries. The 1st will be 0 and the 2nd will be 2 in 11.11% of the tries.

Ha, yeah I was joking about the statistic - I knew it would be calling rand twice. I was just grasping at straws for something 'different'. Kernel#rand accepts ranges in 1.9.3

Thanks for the version information. Didn't knew that.

Missing GolfScript?
0:2;
Then e.g. 15 2+ -> 15

Because in GS you can't write x == x+2 with any sense... Nice idea though, does it redefine 2?

@tomsmeding well the syntax is different, but you can write e.g. x.2+= and yes, basically it does "2=0".

Haskell
f x = (x == x + 2)
    where x + 2 = x

Calling f with any argument (whose type is in the Eq typeclass) will evaluate to True.

$x == $х+2 for infinite pairs of numbers. Let's try it out.
PHP
$х = 1;
$x = 3;

if ($x == $х+2)
    echo "LOL it works. Sort of black magic?";

Nah, it's not black magic. Truth is that one x is Kha, that as Wikipedia states, it looks the same as the Latin letter X, in both uppercase and lowercase, both roman and italic forms.
There's actually no difference between them, so even if there are two different variables, rules are not broken, since I assumed that a x is a Kha.

SWI-Prolog
In query mode:
?- X = X+2, X == X+2.
X = X+2.

You just need to "assign" X = X + 2, then X == X + 2 will be true. Why make things so complicated?

Real explanation
In Prolog, x is an atom, so it is not possible to make x == x + 2 returns true. Variables in Prolog must start with an uppercase letter or underscore.
Therefore, my solution will define (uppercase) X so that X == X+2.
In Prolog, == compares 2 terms according to standard order of terms. Therefore, we only need to unify (= operator) X and X+2 before doing the comparison.
Note that the unification X = X+2 unifies X with the infinite term X = (((...)+2)+2)+2, much like how the unification X = f(X) unifies X with the infinite term X = f(f(f(...))).
In Prolog, when a query succeeds, it will return true if there is no variable, or it will return the variable binding which satisfies the query. This explains the output X = X+2.

C
Defining x as 1==-2
#include<stdio.h>
#define x 1==-2

main()
{
  printf("%d", (x==x+2) ) ;
}

Scheme / Unicode
(let
  ((２ 0) (x 9))
  (= x (+ x ２)))

I knew there had to be a Unicode character that looks like a 2 - and that there would be a language or interpreter lenient enough to accept it as a variable name.

ECMAScript (also known as JavaScript):
x=1e17

Haskell, denotational semantics
x = undefined
As most of you probably know, undefined :: a can be cast to any type - or in other words, every type contains a special value undefined, also called ⊥ (pronounced "bottom").
We say that ⊥ is less defined than any other inhabitant of that type, and while its a little too in-depth for this post, ⊥ can also be seen as a computation that never finishes.
Let's import Data.Function.
In there, there is a function called fix, which according to the Haskell docs finds the least-defined fixpoint of f, by repeatedly applying the function to itself. Let's recap:
We need to find a value x, for which x = x + 2, or, equivalently x = (+2) x. Lets factor (+2) into a function called f. We get x = f x, which is precisely the definition of a fixed point for the function f. Since we don't know x yet, we need a function that knows how to calculate a fixpoint, like fix; x is our placeholder for said fixpoint (x = fix f), so our whole equation becomes fix f = f (fix f).
This is just the definition of fix, so fix indeed finds a fixed point for a given function!
What I'm trying to say is: To solve OP's problem, all we need to do is pipe fix (+2) through ghci. When we do that however, we see nothing, as ghci gets caught in an infinite loop. But since I said that infinite loops can be seen as ⊥, we arrive at the fact that x = ⊥, which by the way turns out to be the only solution to OP's question (who would have guessed).

Ruby
1.9.3p125 :006 > x = Float::INFINITY  # or x = -Float::INFINITY
 => Infinity
1.9.3p125 :007 > x == x +2
 => true

1.9.3p125 :015 > x =Float::MAX
 => 1.7976931348623157e+308
1.9.3p125 :016 > x == x +2
 => true

In Scala, just override the "+" operator (really a function):
scala> class X { def +(a:Int)=this }
defined class X

scala> val x = new X
x: X = X@26e7127

scala> x == x+2
res3: Boolean = true

scala>

Processing
float x=1e30;
print(x==x+2);

The output will be true
Not very creative, but yeah.

Ruby
That's surely cheating, but hey ...

#/usr/bin/env

class Fixnum
  def +(y)
    if self == 42
       self
    else
       self + y
    end
  end
end

Then for x being exactly 42 ... /me => [ ]

Python
>>> x=99999999999999999999999999999999999.
>>> x==x+2
True

Note the . at the end, which makes x a floating point number.

Javascript
Most compact, correct that I could figure.
x=1/0;x==x+2

I also tried futzin around with toString() and clever output variance with casting, but while the results were correct sequentially, the == would never be true.

C++
I'm aware there have been a couple of similarly themed solutions, but here's mine nonetheless:
#include <iostream>

struct Plus {
  int x;
  Plus(int _x):x(_x){}
  Plus operator+(int _x) {
    return Plus(this->x + _x);
  }
  bool operator==(Plus _x) {
    return true;
  }
};

int main() {
  Plus x(0);
  std::cout << bool(x == x + 2);
}

Python
I'm always looking for an excuse to use a class for golfing Python... alas, this isn't golf.
class foo:__add__=lambda a,b:a
x=foo()

Here, x+2 is x, though 2+x blows up with an error (I'd have to implement __radd__).  I could have hacked equality testing instead, but I'd still need to implement __add__.

class foo(int):__cmp__=lambda*a:0 is easier

@gnibbler, I'd agree if addition didn't raise an exception.

Which version of Python are you using? It doesn't raise an exception on 2.7.3

@gnibbler, ooh, I missed the (int).  sneaky sneaky.  don't know that I'd call it 'easier'.

well it's easier because you get to support 2+x for free

@gnibbler, but I get out of defining a compare!

Python
Any language with floats - no need to go all the way to infinity
x=9e9**9
x==x+2

q/k
Pretty trivial using infinity (or null):
q)x:0w

x=x+2
1b

Lua, used in various products including World of Warcraft, Wireshark, Nmap, Adobe Photoshop Lightroom, and the Nspire line of Texas Instruments graphing calculators, supports operator overloading (using "metamethods") for tables (associative arrays). This code works in both Lua 5.1 and 5.2:
local x = setmetatable({}, {
  __add = function(a, b)
    return a
  end
})

print(x == x + 2) -- true

Python

class X():
 def __eq__(a,b):
  return True
 def __add__(a,b):
  return True
x = X()
print x==x+2

$ python x.py
True

Sage
sage: print oo
+Infinity
sage: oo+2==oo
True

Groovy
Integer.metaClass.plus = { Integer y -> delegate }
def x = 0
assert x == x+2

The plus method is overridden to return the first number :-D

C (GCC at least)
Using pointer arithmetic on an struct of size 0
#include <stdio.h>
typedef struct {} empty;

main(){
    empty *x;
    printf("%d\n", x==x+2);
}

@han already suggested exactly the same.

Coffeescript, 18 chars
x=1/0;alert x==x+2

the answer is infinity or - infinity because infinity+2=infinity you can't find any other number that it's bigger than itself+ a number

Infinity is an answer, but not the only one (as you can see here).

GolfScript
In Golfscript, you can redefine +, 2, or = in order to make the statement true for any value of x!  Any of the following lines would suffice:
{;}:+; #Redefine + to ignore the second summand
0:2;; #Redefine 2 to be 0
{;;1}:=; #Redine = to always return true

Then:
10:x; #Any x would work
x x 2+ = #x==x+2
-> 1

If you want the answer in the exactly format of the question, we can do some other nonsense:
{0}:(:x:=:+:2; #redefine all the characters in the expression to 0
{];1}:); #redefine ) to pop everything off the stack and then return 1

So then:
(x == x+2)  #That doesn't look like GolfScript!
-> 1

Little know fact about Haskell is it doesn't always do divide by 0 errors.
let x=1/0 in x==x+2

This is because when you add 2 to infinity, it doesn't get bigger. It is weird that such a mathematical language would just deal with infinity so nonchalantly.

Rebol
Version of the Perl answer by memowe:
v: 0
x: does [v: v - 2]

With above defined you can now test in Rebol console...
>> x == (x + 2)
== true

>> equal? x x + 2
== true

And a Rebol version of Joshua Taylor Common Lisp answer:
x: 42
x+2: 42

In console...
>> x == x+2
== true

JavaScript
Exploiting the big number / infinity approach as shortly as possible.
12 chars:
9e99==9e99+2 // true

10 chars
1/0==1/0+2 // true

JavaScript
var x = {y: 0, toString: function() {return (this.y+=2)}};
console.log(x == x+2); // true

When you add number to an object you indirectly call toString method of this object. toString method returns number... Right side becomes number, then == operator converts x to primitive by using it's toString method.
Interesting article about related idea: Fake operator overloading in JavaScript.

Python (18)
>>> x=True;[x][x==2+x]
True

Gives True in interactive mode.

Groovy
x = Float.MAX_VALUE
assert x==x+2

Float.MAX_VALUE = 3.4028235E38
Float.MAX_VALUE + 2 = 3.4028234663852886E38
Which the == determines is close enough.

C++
Had some fun with operator overloading
#include <iostream>

class Tautology
{
  public:
    const Tautology& operator+(int n)
    {
        // Anything to make x + 2 compile
        return *this;
    }

    bool operator==(const Tautology& t)
    {
        // Any tautology equals any other
        return true;
    }
};

int main()
{
   Tautology x;
   std::cout << (x == x + 2 ? "true" : "false");

   return 0;
}

C++ / C-sharp
Here's another one depending on the definition of an infinite double according to the IEEE standard (http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlf101a.doc%2Fxlfopg%2Ffpieee.htm).
int main()
{
   double x = 0x7FF0000000000000; // Positive infinity
   cout << (x == x + 2 ? "true" : "false");

   return 0;
}

In C# this could be written more readably as
 double x = double.PositiveInfinity;

J
   x=:!123
   x=x+2
1

This is also reliant on the floating point trick: !123x=2+!123x returns 0(= actually is the comparison operator, so no trickery there)
Or, maybe even better:
   x=:_
   x=x+2
1

simply sets x to infinity.

Python 2.7, 46 chars
I see a lot of Python answers abusing real number limitations, I'm surprised no one's submitted this disgusting Python hack yet.
x=True;True=False;
if True is (x==x+2): print x

Returns:
True

Javascript
x=1/0;x==x+2

This doesn't work in strict mode, nor without a global variable (i.e window). Tested in Firefox 38.

Ruby
With some monkey patching, everything is possible.
class Fixnum
    def ==(obj)
        # Check if difference between self and obj is 0, -2 or +2
        "#{self-obj}"=~/0|\-?2/ ? true : false
    end
end

As I can't use self==obj || self==obj+2 || self==obj-2, as that would cause a StackError, I first transform them into Strings, then check if the difference matches "0", "-2" or "2"
Test cases
# Make sure `x` is from type Fixnum
x=0

p (x==x+2) # => true
p (x+2==x) # => true
p (x==x)   # => true
p (x==x+1) # => false
p (x==x+3) # => false

ForceLang
def x set y -2+y
io.write x=x+2

Mathematica
x=∞

Mathematica is perfectly happy to reason (within reason) with infinity, and knows that ∞ and ∞+2 are the same!

 cout << bool(x == x+2);

! is not needed at all

It outputs 1, which means x == x+2 is false. I want x == x+2 to be true.

yeah, sorry, fixed :D

I still don't get it. x == x+2 is false in this case.

DevC++  says that it is true

I don't have DevC++ at hand, so could you please detail in the comments how/why that's possible?

It depends on the initialization of x, which isn't shown. So, no points for this answer.

#include <iostream> using namespace std; int main (){ int x=5; cout << bool(x == x+2); }
Works in DevC++. The reason is that the bool function is not looking for that expression to be true, it just looks if there an expression, if there is one, it is true, if no, it is false, imho

@bla2e, this means your solution is wrong. I want x == x+2 to be true. Your code just checks that it exists.

The answer u set as best, is not even dealing with variables, double x=1.0/0.0;

JavaScript
!!("x==x+2") // true

Can you really say this is defining x?

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.

it was just a joke.

authors: n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳


text:
Minimum number of transactions so everyone has paid the same
On a road trip, N people pay for fuel. Each pays a different amount. At the end of the trip, calculate the minimum number of transactions so that each person has paid the same amount.
e.g. on the road trip, these people pay for fuel

Dave - $50
John - $25
George - $5
Barry - $0

After the road trip:

Barry pays Dave $20
George pays John $5
George pays Dave $10

Added: The output of the program should list the transactions.
Bonus points if the solution is written in Visual Basic.

Why the Visual Basic bonus?

@Hasturkun - Because I'd like to try this on an Excel spreadsheet.

id recommend having an exact win condition; before the heavy-handed moderators swing on by :)

you need to specify a winning condition for the question in order for it to be on-topic

Python, 308 Characters
I chose not to go after the bonus because the last time I used VB was over a decade ago, and I am still suffering from the PTSD ;-)
I didn't try and golf this very much because I'm not sure if that's the goal.  This code is guaranteed to return a solution with the minimum number of transactions.
def t(p):
 a=sum(p)/float(len(p))
 q=[([],p)]
 l=len(p)
 r=range(l)
 while q:
  n=q.pop(0)
  g=1
  for i in r:
   d=n[1][i]-a
   if d>0:
    g=0
    for j in r:
     if n[1][j]<a:
      v=min(d,a-n[1][j])
      y=list(n[1])
      y[i]-=v
      y[j]+=v
      if i!=j:q+=[(n[0]+[(j,i,v)],y)]
  if g:return n[0]

Usage
The t function takes a list of the amounts that each person paid.  Using the example from the question:
> print t([50,25,5,0])
[(2, 0, 15.0), (3, 0, 15.0), (3, 1, 5.0)]

So the solution is for person 2 (George) to pay person 0 (Dave) $15 and for person 3 (Barry) to pay 0 (Dave) $15 and also to pay 1 (John) $5.

Many thanks. I'll try to convert this to VB.

The basic idea is that I start off with no transactions and perform a breadth-first traversal of the search tree generated by enumerating all possible transactions that can occur at a given state from a person that owes money to a person that is owed money.

source: Stack Exchange

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

sort: votes


text:
A doubly linked list that only stores 1 pointer per element
A favorite puzzle of mine. Not massively difficult but a tad interesting.
The Objective
Using a low level language (C/C++/similar level) - create a doubly linked list of elements that only stores a single pointer instead of storing both a previous and next element pointer as you normally would.
You must be able to find each element in your linked list, starting from either the first element you created, or the most recently created element.
You must use malloc(sizeof(*node)) or similar to store each element (the addresses are likely to be non-sequential as a result)
The Restrictions

The data type you use to store your value must be the length of a function pointer (No using long values to store 2 pointer addresses one after another)
You may not use any external libraries (only the standard libc methods are permitted if you're using C/C++, apply the spirit of this rule to other languages)
You may not store any additional metadata elsewhere (or in the list elements themselves) to solve this. The list element may only contain two fields - the 'data' value and the value you will use to find the previous and next elements. It may look something like:

    struct node
    {
       int myValue;
       struct node* prevAndNextNode;
    }

Golf or Challenge?
You can either find the most elegant/interesting solution, or the shortest. Take your pick!
Have fun ;)

the common term for this type of list is "doubly linked list"

Indeed, I didn't call it that originally because in the context of the problem its a slight misnomer.

Is this a code-golf or a code-challenge ? You currently have it tagged as both.

Both! Either for the shortest solution, or the most elegant without worrying about code length.

-1.  That's not an objective winning criterion. (plus, it's so much of a classic)

"You must use malloc(sizeof(node))" - now that's a wrong conception. One mustn't malloc sizeof(type) but sizeof(*variable) since that's less fragile and less prone to human errors in case the type changes.

That wasn't meant to be exact, just to express that it must be something akin to that instead of some feature presented by the language of choice.

@PhonicUK: please see the FAQ: *All questions on this site, whether a programming puzzle or a code golf, should have …
An objective primary winning criterion, so that it is possible to indisputably decide which entry should win.*

This is an xor linked list:
struct node {
  int myValue;
  uintptr_t xor_prev_and_next;
  node *next(node *prev) {
    return (node*)((uintptr_t)prev ^ xor_prev_and_next);
  }
  node *prev(node *next) {
    return (node*)((uintptr_t)next ^ xor_prev_and_next);
  }
}

struct list {
  node *first;
  node *last;
  int sum_forwards() {
    int sum = 0;
    node *prev = NULL;
    node *curr = first;
    while (curr) {
      sum += curr->myValue;
      prev, curr = curr, curr->next(prev);
    }
    return sum;
  }
}

but DO NOT use this on a garbage collected system!

The XOR approach is what I've always considered the 'correct' answer - now I'm interested to see what else people can come up with!

EDIT
Problem Definition

For a given node, find the next node (null if tail)
For a given node, find the previous node (null if head)
Return a node at a specified offset from the start of the list (null if out of bounds)
Return a node at a specified offset from the end of the list (null if out of bounds)

The constraints have been revised by the OP, and include restricting the nodes as well as external structures from storing any metadata. My initial implementation of a Circular Linked List did not meet this criteria since it required knowing the head node with a flag value.
I present now a clever workaround:
A Circular Linked List with Forced Node Address Parity
Note that lately I am a C# programmer, but I will try to do this C-style as possible.
The List Node Structure
Nothing fancy here:
struct ListNode
{
    ListNode *next;
    int value;
};

Adding Nodes with Even Addresses Only
Since this implementation still requires that we be able to find the start of the list, we can use the LSB of the next pointer as a flag. If the last bit of the next pointer is 1, it means we are at the end of the list. A few helper functions:
bool isPtrOdd(void * addr)
{
    if((unsigned int) addr & 1)
        return 1;
    return 0;
}

ListNode * GetNodeAddr(ListNode * node)
{
    if(isPtrOdd(node))
        return node - 1;
    return node;
}

The only special considerations are that we must ensure that nodes are allocated only on even addresses. There are several ways of doing this, but I will show a basic one which allocates an extra byte for each node:
ListNode * NewNode()
{
    void * memBlock = malloc(4 + 4 + 1); // 32 bit address, 32 bit value, 1 padding byte

    if(isPtrOdd(memBlock)) // if the block started on an odd address
        memBlock++;                 // shift over to an even address

    ListNode * newNode = memBlock;

    newNode->value = 0;
    newNode->next = newNode + 1; // a new node circularly points to itself

    return newNode;
}

void AddNode(ListNode * list, ListNode * newNode)
{
    while(!isPtrOdd(list->next))
        list = list->next;         // Get to the end of the list

    newNode->next = list->next;    // Point the new node to the list head + 1
    list->next = newNode;
}

Traversing the List
And using C-style external functions (no classes) we define each of the desired functions:
ListNode * NextNode(ListNode &Node)
{
    if(isPtrOdd(Node->next))
        return 0;
    return &(Node->next);
}

ListNode * PrevNode(ListNode &Node)
{
    ListNode curNode = Node;
    while(&(GetNodeAddr(curNode->next)) != &Node) // We compare addresses instead of values
        curNode = GetNodeAddr(curNode->next);     // since the == operator is not defined for structs

    if(isPtrOdd(curNode->next)) // if the 'previous node' is actually the end of list
        return 0;

    return &curNode;
}

ListNode * NodeFromStart(ListNode &Node, int offset)
{
    // This function returns offset from head node given
    // any node in the list

    ListNode Head = Node;
    while(!isPtrOdd(Head->next))       // Loop completes when tail is found
        Head = GetNodeAddr(Head->next);
    Head = GetNodeAddr(Head->next);    // Move once more and get to head

    for(int n=0; n<offset; n++)
    {
        if(isPtrOdd(Head->next))       // if we reach the end of the list
            return 0;
        Head = Head->next;
    }

    return &Head;
}

ListNode * NodeFromEnd(ListNode &Node, int offset)
{
    // This function returns offset from tail node given
    // any node in the list

    ListNode Head = Node;
    while(!isPtrOdd(Head->next))       // Loop completes when tail is found
        Head = GetNodeAddr(Head->next);
    Head = GetNodeAddr(Head->next);    // Move once more and get to head

    // Determine number of nodes in List
    int count = 1;
    while(!isPtrOdd(Head->next))
    {
        Head = GetNodeAddr(Head->next);
        count++;
    }

    if(count<=offset)
        return 0;

    return NodeFromStart(Head,count - offset);
}

I've updated the original question to perhaps make clearer what the objectives and limitations are.

@PhonicUK: Following the added requirement that the nodes not contain any additional meta-data (such as a bool flag denoting the head) I have created a clever - to some, sloppy - workaround using the LSB of the next pointer as a end of list flag

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


text:
Solving Three Open Problems with a Halting Oracle
You are given the functions: h1(f,*args) and h2(f,*args)
Both are methods which are already defined for you (here the asterisk indicates a variable number of arguments)
f is a function, *args is a list of parameters to be passed to that function
h1 returns a boolean value: True if the function f ever halts when called on *args and False if it doesn't (assuming the machine running it has infinite time and memory and that the interpreter/compiler for the language you're writing in knows how to handle infinite time and memory).
If f(*args) would ever make a call to h1 or h2, h1 throws an exception
h2 behaves exactly like h1 except that if f makes calls to h1, then h2 will not throw an exception
In as few characters as possible, write a program which takes no input and should output:
The Collatz Conjecture is {True/False}
Goldbach's Conjecture is {True/False}
The Twin Primes Conjecture is {True/False}

based on the validity of each of those conjectures.
Here are wikipedia links explaining each of the conjectures:
http://en.wikipedia.org/wiki/Collatz_conjecture
http://en.wikipedia.org/wiki/Goldbach%27s_conjecture
http://en.wikipedia.org/wiki/Twin_prime
You may assume any big integer library in whatever language you choose to use will successfully represent arbitrary large integers. In other words, we'll assume any language/library which is capable of expressing 3**(3**10) is also capable of expressing 3**(3**(3**10)) on a sufficiently beefy machine.
Obviously since it's impossible to run your program, please provide an explanation of how it works along with the code

This still needs an objective scoring criteria.  Also, proving that the pseudo-program works might be really challenging.

I said fewest characters.  It's a codegolf problem.

That is an, interesting, scoring procedure for this problem. "Solve the twin prime conjecture in the fewest number of characters."

man, what a cool question

J, 207
(('The Collatz';'Goldbach''s';'The Twin Primes'),.<'Conjecture is'),.((>:^:((((-:`>:@*&3)^:(~:&1))^:_)&f)^:_ g 2)((+&2)^:(+./@1&p:@(-p:@_1&p:))^:_ f 4)(>:^:((4&p:)^:(2&~:&(-~4&p:))&f)^:_ g 3){'True':'False')

I chose to use f and g in place of h1 and h2, as according to the bounty; two additional lines with 10 total characters prior is sufficient to switch: f=:h1,g=:h2.
And the actual logic:
Collatz
>:^:((((-:`>:@*&3)^:(~:&1))^:_)&f)^:_ g 2

((-:`>:@*&3)^:(~:&1))^:_ is the meat of it; it's essentially a loop that does while (x != 1) x = collatz(x). If we call that sentence reduce:
>:^:(reduce&f)^:_ g 2

reduce&f is meant to be a monadic verb (see end), where reduce&f n is true iff reduce(n) halts. The other loop-y bits, >:^:()^:_, are essentially an infinite loop (>: is increment, ^: can be used as a conditional and an iterator) which breaks upon encountering a Collatz reduction that does not halt. Finally the g is called to see if the infinite loop ever terminates.
Goldbach
(+&2)^:(+./@1&p:@(-p:@_1&p:))^:_ f 4

The same logic, for the most part, the obvious difference being the core calculation is now +./@1&p:@(-p:@_1&p:). -p:@_1&p: calculates the difference between a number and all the primes less than that number, 1&p: is an isPrime function, and +./ is logical OR. Hence, if the difference between a number and any prime less than that number is also a prime, then the Goldbach conjecture is satisfied, and the infinite loop continues on. Again, f is used in a final test of whether said infinite loop is truly infinite.
Twin Primes
>:^:((4&p:)^:(2&~:@(-~4&p:))&f)^:_ g 3

Same as above, excepting (4&p:)^:(2&~:@(-~4&p:)). 4&p: returns the next largest prime after a given number. -~4&p: returns the difference between a number and the next largest prime after it. 2&~: is != 2. So the innermost loop is analogous to while (nextPrimeAfter(p) - p != 2) p = nextPrimeAfter(p).
Notes
There may be syntactical errors, since I haven't tested with dummy f and g yet. Also, I assumed that f and g would take some sort of form that can be composed with a verb on the left and a noun on the right, which I'm not completely sure adheres to the J grammar in any way. They're inherently higher order functions, and I'm too tired to look up a proper construction as adverbs/conjunctions/what-have-you at the moment, if there even is such an appropriate construct.
I didn't really use proper string concatenation, and instead opted to leave individual strings boxed. The output (assuming all else is correct) would therefore be a 3 column table, with the left column being "The Collatz", etc., the middle column being "Conjecture is", and the right column "True"/"False".
I'm also pretty sure J doesn't convert integers to arbitrary precision by default, and the crucial prime number utility function p: does not have an arbitrarily large domain. On the other hand, given that J does support a standard arbitrary precision number type, I'm not sure how much effort it'd take to get this code up to par.

So, does it support arbitrary precision after all? I think the prime test is easily fixable like the APL answer.

Since I already wrote that in the bounty criteria (for CJam), I think I'll follow the rules and award the Haskell answer... But +1 from me.

Haskell, 242
p n=and[rem n r>0|r<-[2..n-1]]
c 1=1
c n|odd n=c$3*n+1|0<1=c$div n 2
s!f=putStr(s++" Conjecture is ")>>print(not$h2$all(h1.f)[4..])
main=do"The Collatz"!c;"Goldbach's"! \n->or[p$n-r|r<-[2..n-2],p r];"The Twin Primes"! \n->or[p$r+2|r<-[n..],p r]

because in Haskell variables can contain not only values, but computations (this is called laziness) I let myself make h1, h2 take a single argument and return weather or not it's evaluation will halt.
somewhat ungolfed code:
h1 = undefined
h2 = undefined

prime n=and[rem n r>0|r<-[2..n-1]]
collatz 1=1
collatz n
    |odd n=collatz (3*n+1)
    |0<1  =collatz (div n 2)

s!f=do
    putStr (s++" Conjecture is ")
    print$not$h2$all(h1.f)[4..]

main=do
    "The Collatz"!c                                         --collatz
    "Goldbach's"! \n->or[prime (n-r)|r<-[2..n-2],prime r]   --goldbach
    "The Twin Primes"! \n->or[prime (r+2)|r<-[n..],prime r] --twin primes

a bit of explanation:
when all is applied to an infinite list, it will halt iff one of the elements of the list is False, due to laziness (short-circuiting, for all non-Haskell folks out there). we use this to compute the collatz conjecture and the twin primes conjecture.
! packages this trickery along with printing.
the result is True when f terminates on all the numbers 4... (this doesn't matter for the collatz conjecture or the twin primes conjecture, because we already know they are true for such small numbers).
the code for the collatz conjecture is "The Collatz"!c. it prints "The Collatz Conjecture is " and the result, which is weather c terminates on all numbers 4...
the code for the goldbach conjecture is "Goldbach's"! \n->or[p$n-r|r<-[2..n-2],p r].
\n->or[p$n-r|r<-[2..],p r,r<n+1] is a function which given n, if it is a sum of two primes, returns True, but otherwise loops indefinitely. thus, if it halts for every 4.. goldbach's conjecture is true.
the code for the twin primes conjecture is "The Twin Primes"! \n->or[p$r+2|r<-[n..],p r].
\n->or[p$r+2|r<-[n..],p r] is a function which given n, if there are twin primes greater than n, returns True, but otherwise loops indefinitely. thus, if it halts for every 4.. the twin prime conjecture is true.

Would you mind posting an ungolfed version of this as well? (with proper spacing and some type signatures)
I didn't know you could put the bars all on one line like you did for c

Shouldn't the primality tester go from [2..n-1]? (otherwise everything's composite)

oh, also, does p test for primality or compositeness?

I like the natural extension to haskell: h1 determines whether the evaluation of this thunk will halt, or better yet, h1 returns True for all computations that are not _|_ where it returns False (unless the computation uses h1 in which case the result itself is _|_).

@dspyz hmm. that's nice. but that would allow us to abuse the fact that exceptions are bottoms, and that h1 throws exceptions when it is improperly used... I wonder how useful would that actually be.

Let us continue this discussion in chat.

Yeah, I'm pretty sure prime should be: prime n=and[rem n r>0|r<-[2..n-1]]

@dspyz I had it my golfed  code but forgot to update

I went ahead and fixed it myself, I hope you don't mind

APL (234)
It's obviously untested, but the logic seems sound. Printing commands are all included, the output is 104 characters and the actual logic is 130.
Z←' Conjecture is '∘,¨'True' 'False'
⎕←'The Collatz',Z[1+{~{1=⍵:⍬⋄2|⍵:∇1+3×⍵⋄∇⍵÷2}h1⍵:⍬⋄∇⍵+1}h2 1]
⎕←'Goldbach''s',Z[1+{~⍵∊∘.+⍨N/⍨~N∊∘.×⍨N←1+⍳⍵:⍬⋄∇⍵+2}h1 2]
⎕←'The Twin Primes',Z[1+{~(T←{∧/{2=+/(⌈=⌊)⍵÷⍳⍵}¨N←⍵+1:N⋄∇N})h1⍵:⍬⋄∇T⍵}h2 4 2]

Ungolfed:
⍝ Environment assumptions: ⎕IO=1 ⎕ML=1
⍝ I've also assumed h1 and h2 are APL operators
⍝ i.e. x F y = f(x,y); x (F h1) y = h1(F,x,y)

⍝ 'Conjecture is True', 'Conjecture is False'
Z←' Conjecture is '∘,¨'True' 'False'

⍝⍝⍝ Collatz Conjecture
⍝ halts iff 1 is reached from given ⍵
collatzLoop←{
   1=⍵:⍬       ⍝ ⍵=1: halt
   2|⍵:∇1+3×⍵  ⍝ ⍵ uneven: loop with new val
   ∇⍵÷2        ⍝ ⍵ even: loop with new val
}

⍝ halts iff 1 is *not* reached from a value ≥ ⍵ (collatz false)
collatzHalt←{~collatzLoop h1 ⍵:⍬⋄∇⍵+1}

⍝ does it halt?
⎕←'The Collatz',Z[1+ collatzHalt h2 1]

⍝⍝⍝ Goldbach's Conjecture

⍝ Can ⍵ be expressed as a sum of two primes?
sumprimes←{
    N←1+⍳⍵         ⍝ N=[2..⍵+1]
    P←(~N∊N∘.×N)/N ⍝ P=primes up to ⍵+1×⍵+1
    ⍵∊P∘.+P        ⍝ can two P be summed to ⍵?
}

⍝ halts iff Goldbach is false
goldbachHalt←{
    ~sumprimes ⍵:⍬ ⍝ not a sum of primes: halt
    ∇⍵+2           ⍝ try next even number
}

⍝ does it halt?
⎕←'Goldbach''s',Z[1+ goldbachHalt h1 2]

⍝⍝⍝ Twin Primes

⍝ is it a prime?
isPrime←{
   2=+/(⌊=⌈)⍵÷⍳⍵    ⍝ ⍵ is a prime if ⍵ is divisible by exactly two
                   ⍝ numbers in [1..⍵] (i.e. 1 and ⍵)
}

⍝ find next twin
nextTwin←{
   N←⍵+1            ⍝ next possible twin
   ∧/ isPrime¨ N:N  ⍝ return it if twin
   ∇N               ⍝ not a twin, search on
}

⍝ halts iff no next twin for ⍵
twinPrimeHalt←{
   ~nextTwin h1 ⍵: ⍬  ⍝ if no next twin for ⍵, halt
   ∇nextTwin ⍵        ⍝ otherwise try next twin
}

⍝ does it halt?
⎕←'The Twin Primes',Z[1+ twinPrimeHalt h2 4 2]

But does APL support big integers?

@user23013: In theory, APL's number format is an arbitrary-precision float, thus, in theory it can store any number. Of course, in practice, there is a limit, but it is implementation-dependent, and the question says to assume it can handle numbers of arbitrary size.

The question says only big integers can be arbitrarily large.

@user23013: it only has the one number type

Big integers usually means arbitrary precision integers. As clarified in the question, it should be able to express 3**(3**10) (3*3*10 in APL), which gives a DOMAIN ERROR in tryapl.org.


text:
Shorten text with Run Length Encoding
Shorten (or not) text using run length encoding
Input:
heeeello
woooorld

Output:
1h4e2l1o
1w4o1r1l1d

Read lines from stdin.
Print to stdout.
Stderr is of course discarded.
Assume there are hidden testcases (no embedding of the output)
Input/Output as ASCII
Any language is accepted

You can (typically) save quite a bit if you ignore all ones, e.g. w4orld instead of 1w4o1r1l1d (you'd need to escape numerics, e.g. `f111 -> f3\1´). But then it would be a near-duplicate of this: http://codegolf.stackexchange.com/questions/6774

As it is it's close enough to Run-Length Encoding that I vote to close as dupe. It's not going to provide any new challenge or points of interest.

Bonus points for whoever manages to find a fixpoint.

Run-Length Encoding may be the same at its core but the input format and the required output format are very different.

@FUZxxl, 22 is a trivial fixpoint.

@PeterTaylor And the only nonempty one. We know it must begin with a digit. 11 is impossible. 22 must end there or be followed by another fixed point not beginning with 2. 333nnn is an impossible pattern, for you'll never find the same character at consecutive odd indices. 4444 and up fail for the same reason.

DIfferent input and output formats are not enough to render questions distinct.

Possible duplicate of Run-Length Encoding

@pppery I prefer to close that one as a duplicate of this one, since this one is for text, not just numbers.

@Khuldraesethna'Barya: Are we assuming that runs are limited to 9 repeats?  Or are the numbers variable-width, like 33a would be 33 repeats of a?  Question doesn't say, and existing answers seem to just count without limiting to 9.  IDK if that introduces more fixed points, but it does make the question under-specified.  (I think to be unambiguous, the encoding would need to handle a thirty-three a run as 9a9a9a6a, not 33a, unless ASCII digits aren't allowed in the input.)

Perl: 46 → 36 or 27 characters
perl -pe's|((.)\2*)|@x=split//,$1;@x.$x[0]|eg'
All hail @ardnew for coming up with the idea of using the tr///c operator to count the number of characters in the matched string instead of splitting:
perl -pe's|((.)\2*)|$1=~y///c.$2|eg'

Degolfed:
while(defined($_ = <>)) {
  $_ =~ s{((.)\2*)}           # match 1 or more consecutive identical non-newlines
         {
           ($1 =~ y///c )     # count the number of characters in $1
           .                  # and concatenate it
           $2                 # with the first matched character
         }eg;                 # execute substitution, match "global"
  print $_;                   # print the modified line
}

Usage:
$ perl -pe's|((.)\2*)|$1=~y///c.$2|eg' infile

or via STDIN
$ perl -pe's|((.)\2*)|$1=~y///c.$2|eg'
heeeello

prints
1h4e2l1o

You're short-changing yourself on your character count - I count 37 characters including 1 for the p option.

You can save 10 chars by using s|((.)\2*)|$1=~y///c.$2|eg, which sums to 27 total chars (using the same character counting rules as @Gareth)

Can shorten even further to 25 bytes (including -p) by eliminating the outer parens: Try it online!

Stax, 7 bytes
ûèB☼å°╤

Run and debug it st staxlang.xyz!
Unpacked (8 bytes) and explanation:
m|RFNppz
m           For each line of input:
 |R           Run-length encode: "heeeello" -> [[104,1],[101,4],[108,2],[111,1]]
   F          For each pair:
    N           Uncons-left: [104,1] -> push [104]; push 1
     ppz        Pop and print. Pop and print. Push "".
              Implicit print (always an empty string) with a newline

5 bytes, works only on a single line:
∩l↨me
|RmEp]    Unpacked
|R        Run-length encode: "heeeello" -> [[104,1],[101,4],[108,2],[111,1]]
  m       Map block over input:
   E        Explode array: [104,1] -> push 104, push 1
    p       Pop and print with no newline
     ]      Make a one-element list: 104 -> [104] (which is "h")
            Implicit print with newline

Run and debug it at staxlang.xyz!
Perhaps not legal. This program prints each pair on a line of its own. A bit sketchy.
If that output format is illegal, I give you 6 bytes:
╡δôZ→╬
|RFEp]p    Unpacked
  F        For each item in array, execute block:
      p      Pop and print with no newline
             No implicit print in for-each block, so no extra newlines

Run and debug it at staxlang.xyz!
The language's creator recursive points out that uncons-right (N) can shorten this to six bytes unpacked, as it handles the E and the ] on its own. Programs this short, however, often get no shorter when packed, and this is am example. Still six bytes: |RFNpp Edit: Had to update my main answer; this form is what I used.

NIcely done.  |RFNpp can give the specified output in 6 bytes unpacked, but unfortunately, doesn't pack.

@KevinCruijssen Yep. Whoops.

K (oK), 28 bytes
{,/($#:'c),'*:'c:(&~=':x)_x}

Try it online!
On mobile, explanation to follow...

I think three bytes can be saved with {($#x),*x}' instead of ($#:'c),'*:'c:

Scala, 150 144 134 bytes
io.Source.stdin.getLines.map(s=>println{val(x,y,z)=s.tail./:(("",s.head,1)){case((a,b,c),d)=>if(b==d)(a,b,c+1)else(a+c+b,d,1)};x+z+y})

Try it online!
UPDATE:

6 bytes saved thanks to @Kjetil S.
10 bytes saved thanks to @user

Here the pure Lambda de-golfed (97 bytes):
  s => {
    val (x,y,z) = s.tail./:(("", s.head, 1)) {
      case ((a, b, c), d) =>
        if (b == d)
          (a, b, c + 1)
        else
          (a + c + b, d, 1)
    }
    x+z+y
  }

You could cut scala. before io. Also I think some surrrounding code can be removed from the count. Only include the lambda to get 110 bytes: Try it online!

Thanks for pointing out that scala. is obsolete, which saves 6 bytes.
Regarding the lambda: I agree that it is generally ok to provide just a lambda. However, this challenge mentions explicitly that the solution should read from stdin and print to stdout, and other solutions (e.g., Python) do also include this in their byte count, so I think it is fair to keep it.

You can use map instead of foreach, and /: instead of foldLeft.

I really feel bad to use map for side-effects, but, hey, this is golfing, so it's a great tip :) Also I did not know about the /: alias, thanks!

Add++, 74 bytes
D,g,@:,BGd€q$€bLzBFJ
D,f,@,10C$t€g
]getchar
y:''
Wx,`y,+x,`x,]getchar
$f>y

Try it online!
This could be half the size if we could take input from the command line
How it works
The first line (the function g) actually performs RLE. The rest of it just reads the input char by char, passes it to a function f, which splits on newlines, then runs g on each line.
g simply groups equal adjacent characters with BG, then gets the lengths (€bL) and deduplicates (€q). We then zip these together, flatten, Join and print.

Remind me to upvote this in 20m :p

J, 35 31 characters
,(](":@#,{.);.1~1,2~:/\])1!:1[1

Usage:
   ,(](":@#,{.);.1~1,2~:/\])1!:1[1
heeeello
1h4e2l1o
   ,(](":@#,{.);.1~1,2~:/\])1!:1[1
woooorld
1w4o1r1l1d

Using modern site rules and a function, [:,(#,&":{.)/.~ for 15: Try it online!

Python 3, 84 bytes
def f(s,c=1):i,*j=s;b=j[:1]==[i];print(end='%s%s'%(c,i)*(b^1));f(j,1+b*c)
f(input())

Try it online!
Explanation
Checks if the first and second characters of the string are equal. If they are, increase the counter by 1. If they are not, print the counter and the first item and reset the counter to 1. In both cases, the function is called recursively with the first character removed.
Raises an error when end of string is reached.

Without I/O restrictions, but with minimal byte count:
Python 3.8 (pre-release), 70 bytes
f=lambda s:'%s%s'%(len(s)-len(t:=s.lstrip(p:=s[0])),p)+f(t)if s else''

Try it online!
Python 3 equivalent (77 bytes)
Explanation
Strips all repeating characters off the start of the string. Then it returns a string containing (1.) the difference in lengths between the original string and the stripped string; (2.) the first character of the original string; (3.) the result of the recursive function applied to the stripped string. Recursion ends when an empty string is encountered.

05AB1E, 9 bytes
|εÅγs.ιJ,

Try it online.
Or alternatively:
|εÅγøí˜J,

Try it online.
Explanation:
|          # Read all lines of input as list
 ε         # For-each over the lines:
  Åγ       #  Run-length encode, pushing the list of characters and lengths separately
    s      #  Swap so the characters at at the top and lengths below it
     .ι    #  Interleave the two lists
       J   #  Join the list of characters and lengths together to a single string
        ,  #  And output it with trailing newline

|εÅγ       # Same as above
    ø      #  Zip/transpose; creating pairs of [character, length]
     í     #  Reverse each pair to [length, character]
      ˜    #  Deep flatten the pairs to a single list
       J,  #  Join them together to a single string, and output it with trailing newline

Ruby, 42 bytes
->s{s.gsub(/(.)\1*/){|m|"#{m.size}"+m[0]}}

Try it online!

Recently re-visited this and noticed you can replace m[0] with $1 for -2 and if you switch to ruby -p you can drop the ->s{s. ... } for another -7 :)

Wolfram Language (Mathematica), 98 bytes
Print[""<>StringCases[#,s:x_..:>ToString@StringLength@s<>x]]&/@StringSplit[$ScriptInputString,"
"]

Try it online!
A more flexible I/O format reduces this solution to 54 bytes:
""<>StringCases[#,s:x_..:>ToString@StringLength@s<>x]&

Try it online!

If you are wondering why this code does not work in Mathematica's front end (but works fine in TIO and in WolframScript): There are significant differences between the input parsers.

CJam, 2 bytes
e`

e` is a built-in for run-length encoding. CJam's implicit output ignores array brackets, and so turns [[1 'h] [2 'e]] into "1h2e"
Try it online!

Husk, 10 bytes
m(ṁ§:osL←g

Try it online!

Haskell, 78 bytes
import Data.List
m@main=getLine>>=putStrLn.(>>=shows.length<*>take 1).group>>m

Try it online!

05AB1E, 5 bytes
Åγsø˜

Try it online!
Åγsø˜  # full program
    ˜  # flatten each sublist of...
   ø   # list of all elements of...
Åγ     # chars and corresponding run lengths of chars in...
       # implicit input...
   ø   # with each element from...
  s    # second...
   ø   # sublist paired with corresponding element in...
  s    # first...
   ø   # sublist
       # implicit output

JavaScript (V8), 66 bytes
-10 thanks to @Original Original Original VI
r=>r.split`
`.map(d=>d.replace(/(.)\1*/g,g=>g.length+g[0])).join`
`

My first time using \1 in a regular expression, which is a super overpowered way to approach this problem (looks like a few answers already use it). The rest of the code is basically just I/O.

Scala, 116 bytes
_ split "\n"map{def d:Seq[_]=>Any={case e+:f=>val(g,h)=f span e.==
""+e+(g.size+1)+d(h)case x=>x}
d(_)}mkString "\n"

Try it online!
Is it short? No. Does it use best practices where it wouldn't make the code longer? No. Did I do it for ethical reasons? No. Is it creative? No. Am I proud of it? Yes.

Brachylog, 11 bytes
ḅ⟨{lṫ}ch⟩ᵐc

Try it online!
(If output really has to be on stdout, add one byte for w at the end.)
          c    The output is the concatenation of
 ⟨    c ⟩ᵐ     the concatenated pairs of
  {lṫ}         length converted to a string
       h       and first element
ḅ        ᵐ     for every run in the input.

Python 3 iterative, 115 99 97 bytes
while 1:
 a=b='';k=0
 for c in input():e=a!=c;b+=(str(k)+a)*e;k+=1-k*e;a=c
 print(b[1:]+str(k)+a)

Try it online!
Python 3 recursive, 136 130 129 bytes
f=lambda r,c,s,k=1:s and(c==s[0]and f(r,c,s[1:],k+1)or f(r+str(k)+c,s[0],s[1:]))or r[1:]+str(k)+c
while 1:print(f('','',input()))

Try it online!
The iterative approach seems quite successful, while the recursive version has a lot of room for improvement.

Nice approach! It looks like the while loop in your code is only there to demonstrate the input. Without it, your code is still valid. In that case, the loop does not need to be part of the code and you can reduce the first example to 85 bytes like so: Try it online!

Your second example can be reduced to 121 bytes like this: Try it online!

Yea, the while loop is only for linewise input. But the question requires to read all lines, not just one, so externalising the loop would be against the rules.

Julia 1.1, 94 84 81 bytes
foldl(((n,l),c)->(c==l||print(n,l);((c==l&&n)+1,c)),readline()*'\n',init=("",""))

Try it online!

Here is 80 bytes. I think it can go shorter though

Unfortunately, your code didn't work on Julia 1.1 for me. I still managed to get 81 by adding an extra '\n'  to readline() instead of printing the last tuple manually

Retina, 12 bytes
(.)\1*
$.0$1

Try it online.
Explanation:
Get a part of 1 or more of the same character, capturing the character in capture group 1.
(.)\1*

Replace it with the length of the total match, concatted with the character from capture group 1:
$.0$1

Vyxal, d, 2 bytes
øe

Try it Online!
That is,
øe  # run length encode the implicit input
    # the d flag deep sums the top of the stack before outputting

Pyth, 6 5 bytes
jksr8

Relatively self explanatory, just joins together Pyth's run length encode instruction
Edit: -1 byte because while working on something completely different I remembered flattening a 2D list is just summing the elements.
Try it online!

Zsh, 117
while read s;do n=1;for i in {1..$#s};do if [[ $s[i] != $s[i+1] ]];then echo -n $n$s[i];n=0;fi;((n++));done;echo;done

Run it like this:
zsh script.zsh < infile

De-golfed
while read s; do                      # while stdin has more
  n=1                                 # repeat counter
  for i in {1..$#s}; do               # for each character
    if [[ $s[i] != $s[i+1] ]]; then   # same as next one?
      echo -n $n$s[i]                 # print if no
      n=0
    fi
    ((n++))
  done
  echo                                # newline between words
done

Are those white spaces necessary or can you shorten `if [' to 'if[' etc?

The [[ construct is a command on it's own (like [) and has to be separated from other commands. As to using [ over [[, it requires the arguments to be quoted so four " need to be added.

Bash: 104 characters
while read s;do e=;while [[ $s ]];do c=${s:0:1};n=${s##+($c)};e+=$[${#s}-${#n}]$c;s=$n;done;echo $e;done

Sample run:
bash-4.2$ while read s;do e=;while [[ $s ]];do c=${s:0:1};n=${s##+($c)};e+=$[${#s}-${#n}]$c;s=$n;done;echo $e;done <<END
heeeello
woooorld
END
1h4e2l1o
1w4o1r1l1d

Burlesque (17B)
{=[{J[-jL[Q}\m}WL

{=[{^^[~\/L[Sh}\m}WL

Older/Alternative and longer versions:

{=[{^^L[Sh\/-]Sh.+}m[\[}WL
{=[{^^L[Sh\/-][-.+}m[\[}WL
{=[{^^L[Sh\/-~.+}m[\[}WL
{=[{^^L[Sh\/-].+}\m}WL
{=[{^^L[Sh\/[~.+}\m}WL
{=[{^^L[Sh\/[~_+}\m}WL
{=[{^^L[Sh\/fc.+}\m}WL
{=[{^^L[Sh\/-~.+}\m}WL
{=[{^^L[Sh\/-]\/}\m}WL

APL (24)
,↑{(⍕⍴⍵),⊃⍵}¨B⊂⍨B≠¯1⌽B←⍞

rs, 19 chars
This doesn't really count because I created rs way after this was posted...but it was fun anyway!
(.)(\1*)/(^^\1\2)\1

Try it here!

https://codegolf.meta.stackexchange.com/questions/12877/lets-allow-newer-languages-versions-for-older-challenges

Zsh, 44 bytes
44 bytes: try it online. Based on this.
echo ${(s::)1}|xargs -n1|uniq -c|tr -d \\n\

70 bytes: try it online. Based on this.
for ((n=1;i++<#w;n++))[[ $w[i] != $w[i+1] ]]&&printf $n$w[i]&&n=0
echo

Note to self: Try using the mode of an array..

See also this crazy solution for 28 bytes

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


text:
Visualise long multiplication with ASCII art
The challenge
Write a program that takes two integers from standard input, separated by a comma, and then prints a visualisation of long multiplication of those two integers to standard output.
Eg:
Input
14, 11

Program output
     14
    x11
   _____
     14
    14
  ______
    154

Input
-7, 20

Program output
     -7
    x20
   _____
     00
    14
   _____
   -140

Assume always correct inputs and numbers in the range [-999, 999]
Winning criteria
Shortest code wins!

Tweaked for consistency with http://codegolf.stackexchange.com/questions/1624/visualize-long-division-with-ascii-art

Perl, 108 chars
Best of breed 108 char solution, incorporating some ideas from Orabig.
($x,$y)=<>=~/[-\d]+/g;printf"%7s
",$_ for$x,x.$y,"-"x7,(map{abs($x*$_).$"x$i++}reverse$y=~/\d/g),"-"x7,$x*$y

Earlier 139 char solution
sub P{sprintf"%*d",@_}
($x,$y)=<>=~/[^,]+/g;$,=$/;
print P(7,$x),"  x".P(4,$y),"-"x7,(map{P 7-$i++,abs$_*$x}reverse$y=~/\d/g),
"-"x7,P 7,$x*$y

/me bow in respect... I didn't see the possibility to include the map in the printf part. And the $y=~/\d/g trick was clever

Mathematica 213 217 197 193 186 184 193 184 177
Code
a_~g~b_ :=
With[{e = IntegerDigits@b}, Column[Flatten@{a, UnderBar["x " <> IntegerString[b]],
Table[Row @@ {PadRight[{a Reverse[e][[i]]}, i, " "]}, {i, Length@e}], OverBar[a b]},
Alignment -> Right]]

Usage
g[845, 921]

Surely by IntegerString[921] you mean IntegerString[b]?

Yes, good catch!

I think the spec allows for the removal of the space in "x ".

Your're correct.  I decided to leave it in because it looked better (and I wasn't going to have the shortest code anyway).

Python, 174 170:
a,b=input();r,s=str(a),str(b);h=len(r+s)*'-';print'\n'.join(["%9s\n%9s\n%9s"%(r,'x'+s,h)]+["%%%ii"%(9-i)%(int(d)%10*a)for i,d in enumerate(s[::-1])]+["%9s\n%9i"%(h,a*b)])

Usage: exactly as requested, run and input the values in standard input.
To see running: http://ideone.com/S8xNb
Output:
     1234
    x5678
 --------
     9872
    8638
   7404
  6170
 --------
  7006652

Thanks to fabiocerqueira and beary605 and David Carraher

You can remove 4 characters of whitespace: print '\n' -> print'\n', 10*a) for i,d in enumerate -> 10*a)for i,d in enumerate, "%9s\n%9i" % (h,a*b) -> "%9s\n%9i"%(h,a*b)

Python, 145, another answer with a little bit different output.
Code
a,b=input();h=6*'-';print'\n'.join(["%6i\nx%5i\n%s"%(a,b,h)]+["%%%ii"%(6-i)%(int(d)%10*a)for i,d in enumerate(str(b)[::-1])]+["%s\n%6i"%(h,a*b)])

Usage
just as requested
Output
   999
x  999
------
  8991
 8991
8991
------
998001

To see running: http://ideone.com/mdR18

Perl, 157 151 150 144 141 133 chars :
($x,$y)=<>=~/[-\d]+/g;map{$z=~s/z/ z/g;$z=(abs$x*$_)."z$z"}split//,abs$y;map{printf"%6s
",$_}$x,"x$y",$b="-"x6,(split/z/,$z),$b,$x*$y

Usage :
>echo "-123, 456" | perl mult.pl
   -123
   x456
-------
    738
   615
  492
-------
 -56088

Had an idea this morning : using printf make me improve my solution by 8 characters :)


text:
Traverse all numbers with only one bit flip per step
You can count 0, 1, 2, 3, 4.
But to get from 3 to 4 you have to change 3 bits at once.
Given a number of bits, how can you go through all numbers once,
but change at each step only 1! bit.
Here is an example for 3 bits:
000 100 110 010 011 111 101 001

so the output is:
0 1 3 2 6 7 5 4

Rules:

given a number of bits n, return a list of 2^n unique numbers
between to consecutive numbers only one bit is different
the shorter the code the better

This is fundamentally the same question as http://codegolf.stackexchange.com/questions/4094 with a different winning criterion.

Python 3:
for i in range(2**n):i^i//2

(Doh. Overlooked that this solutions is already known. Would delete it if stackexchange allowed it)

GolfScript, 13 chars
~2\?,{.2/^}%`

For example, the input 3 produces the output [0 1 3 2 6 7 5 4].
Here's a de-golfed version with comments:
~              # evaluate the input, turning it from a string into a number
2 \ ?          # raise 2 to the power given by the input...
,              # ...and turn it into a list containing the numbers from 0 to 2^n-1
{ . 2 / ^ } %  # xor each number in the list with itself divided by 2
`              # un-eval the list into a string for output

It's perhaps interesting to note that there are no particular "golfing tricks" involved — this is basically the most obvious and straightforward way to solve this task in GolfScript.

C++, 188 bytes
#include <cstdlib>
#include <iostream>
#define y if(b)f(b-1)
int x=0;
void f(int b){y;std::cout<<(x^=1<<b)<<' ';y;}
int main(int,char**v){int b=std::atoi(v[1]);std::cout<<x<<' ';y;}

Specify the number of bits on the command line and it will print a list of space separated integers.

F# (32)
[for i in 0..(1<<<n)-1->i^^^i/2]

If explicit output is not required, this will do the job (45 chars):
for i in 0..(1<<<n)-1 do printf"%i "(i^^^i/2)

Disclaimer: Very similar to the answer I provided here, just simplified to fit the output specified here.

Jelly, 6 bytes
2*Ḷ^H$

Try it online!
How it works
2*Ḷ^H$  Main link. Argument: n

2*      Yield 2ⁿ.
  Ḷ     Unlength; yield [0, ..., 2ⁿ].
     $  Combine the two links to the left into a chain.
   ^H       XOR each k in the range with k/2.


text:
Create a GUI Piano
Challenge
Create a GUI Keyboard with as few characters as possible.
Example
Because this was an assignment in one of my courses, I can't show the source code.  However, here is a screen shot of my keyboard.

In this example, my keys were of type JButton and I used a Midi Synthesizer to produce the sound (with the default ADSR envelope values).
Rules

You are allowed to use standard external libraries.
Be creative with your sound.  You can use 8-bit, a sitar, etc.
For simplicities sake, you may have five keys; black and white, from C to E (the first five keys on my keyboard).
Most importantly... showcase your work!

NOTICE: Depending on what language you choose to work with, this may be a rather large task.
This is my first question on SE Code Golf.  If anything is unclear, please ask for further details.

EDIT: The due date for this challenge will be 9/22/12.  If you post an answer after this date, I will look over it regardless (and possibly +1 it).

Restrictions on which language to use are not liked very much here. Consider dropping your restriction or name an important reason.

I agree with FUZxxl. Java and C♯ suck at CG anyway so I can see even less why you would want to forbid them. Still, I like this task.

@FUZxxl As stated under the Example section, this was a term project for our Java class.  It is still being used as a term project for that very class.  But I suppose I'm just paranoid so I'll drop the restrictions.  I think you meant which languages not to use... but whatever, I removed them.

@leftaroundabout Thank you, I made some changes to the Rules.

What are the minimal requirements to be considered a "GUI keyboard"? I infer from what's already present that it must display a GUI and produce some sound, but what restrictions are there on: a) the input mechanism; b) the sound envelope; c) the scale used; d) the accuracy of the tuning; e) the proportions of the keys?

@PeterTaylor I used buttons for my piano along with a midi synthesizer (default ADSR values) in Java.  Since I am only asking for five keys, you can use C, C#, D, D# and E.  These keys correspond to the first five keys farthest to the left in the image that I provided.

@MikeDtrick, that answers 0/5 of my questions. I'm not asking how your implementation worked: I'm asking how I can know whether my (hypothetical) implementation is a valid competitor, because there's no point shortening an entry by 20% if so doing takes it from being a valid entry to an invalid one.

@MikeDtrick: For example, you could require that the buttons look exactly like the ones in your example, pixel by pixel.  At the other extreme you could allow any arrangement of five GUI buttons of any type.

@PeterTaylor As long as it looks like a piano and sounds like a piano (perfect pitch), then it's a valid answer.

Mathematica 319 259 255

Edit:
Keys now depress (as buttons) when clicked.

This will play the grand piano notes {"C","C#","D","D#","E"}, where "C" is middle C.  z[n_] plays the note.
z@n_ := EmitSound@Sound[SoundNote[n, .3, 1]]; w = {10, 300}; b = {35, 180};
Graphics[Inset[Button["", z[#[[1]]], Background -> If[#[[2]] == w, None, Black],
ImageSize -> #〚2〛], #〚3〛] & /@ {{"C", w, {-.4, 0}}, {"D", w, {0, 0}}, {"E", w, {.4, 0}},
{"C#", b, {-.2, 0.31}}, {"D#", b, {.2, 0.31}}}, PlotRange -> 1]

The keyboard can be extended to 18-keys by using fewer than double the characters:
z@n_ := EmitSound@Sound@SoundNote[n, .3, 1];
w = {"C", "D", "E", "F", "G", "A", "B", "C5", "D5", "E5", "F5"};
b = {"C#", "D#", "", "F#", "G#", "A#", "", "C#5", "D#5"}; i = ImageSize; t = Thread;
l = List; s = Inset; m = Table; u = Button;
Graphics[Join[t[s[u @@@ t[l["", y /@ w, i -> {5, 350}]] /. y -> z, m[{90 k, 0}, {k, -5, 5}]]],
Delete[t[s[u @@@ t[l["", y /@ b, Background -> Black, i -> {28, 212}]] /.
  y -> z, m[{90 k + 45, 220}, {k, -5, 3}]]], {{3}, {7}}]],
AspectRatio -> .45, PlotRange -> {{-500, 500}, {-610, 610}}, i -> {800, 430}]

+1 I have no doubt in my mind that this will work... I just wish I could play on it.

I left a .cdf version of the file in my DropBox at https://www.dropbox.com/sh/m3y0fs0v0nidqt5/UTv_0YGpz5   You can share this with others. There should be no licensing problems because it is being used for non-commercial, educational purposes.  You will need to download the free Wolfram CDF player if you don't already have it.

David, I need w = {67, 300} to get your result; any idea why the difference?  Also, may I edit this code to shorten it, if I am able?

Mr.Wizard.  w = {67,300} works fine on v. 9 so if you want to change it, or for that matter, shorten any of the code, go right ahead.  Adjusting the button size was hit or miss.  Strange things happened for reasons I cannot explain. (For instance, adding more buttons affects the proportions of the original buttons.)

Web page (840/796 characters)
>>> Start playing (Internet Explorer is not supported for multiple reasons; Google Chrome and Opera work best.)
I probably could make this a bit shorter, yet it is a good start. The lower score is after replacing all occurrences of   with the character itself and removing the keyword new, the latter change breaking Google Chrome compatibility.

Save this code as a text file with a name ending in .htm or .html and open it in Chrome or Opera (Safari might also work), or just open the solution's JSBin page to start playing. I reused the WAV file header from my solution to the Twinkle Twinkle Little Star code golf problem.
An important feature is that the sound diminishes as time passes. To observe this behavior, try holding down a key for a few seconds and listening to what happens.
Here is a more readable version of the code:

+1 Works nice in Firefox 15, although I would have chosen a better sounding instrument.

Groovy: 577 (703 with whitespaces)
The first 5 notes. Others could be added easily, it's somewhat dynamic.
Damn swing. Probably with a swing lib it would be better.

Plays through JFugue.
On github: https://github.com/wpiasecki/glissando/blob/master/src/br/glissando/Piano.groovy
On groovy 2.0.2
import java.awt.event.*
class Note { def n; boolean s; def p() { new org.jfugue.Player().with {play n;close()}} }
notes=['C','C#','D','D#','E'].inject([]){ l,n -> l<< Note[n:n,s:n=~/#/]}
h=300
l=0
w=60
x=0
new groovy.swing.SwingBuilder().edt {
  frame size:[notes.size()*30+30,h],
    show:true,
    defaultCloseOperation:javax.swing.JFrame.EXIT_ON_CLOSE,
    { l = layeredPane() }
  notes.each { n ->
    C=java.awt.Color
    s=n.s
    p=panel bounds:(s ? [x-15,0,w-30,h-100] : [x,0,w,h]),
      background: s ? C.BLACK : C.WHITE,
      border: lineBorder(1, color: C.BLACK)
    p.addMouseListener({ if(it.id==MouseEvent.MOUSE_CLICKED)n.p() }as MouseListener)
    if(!s)x+=w
    l.add p,s?0:1
  }
}

R - 491 characters
I'm a little late but I just saw this post yesterday.
Works on a Mac, uses playRWave and packages tuneR and splancs.
a=array
x=c(7,2)
y=c(5,2)
z=c(1,1,3,3)
par(mar=rep(0,4))
plot(NA,xli=c(0,9),yli=c(0,3))
N=list(a(c(0,3,3,2,2,0,0,0,0,z,0),x),a(c(3,6,6,5,5,4,4,3,3,0,0,z,1,1,0),c(9,2)),a(c(6,6,7,7,9,9,6,0,z,0,0),x),a(c(2,4,4,2,2,z,1),y),a(c(5,7,7,5,5,z,1),y))
c=c(NA,NA,NA,1,1)
for(i in 1:5){polygon(N[[i]],c=c[i])}
h=c(261.63,293.66,329.63,277.18,311.13)
library(tuneR)
setWavPlayer("~/Library/Audio/playRwave")
repeat{P=data.frame(locator(1));play(sine(h[sapply(N,function(x)splancs::inout(P,x))],bit=16))}

Ungolfed:
par(mar=rep(0,4))
plot(NA,xlim=c(0,9),ylim=c(0,3)) #Create empty plot: due to fuzzy matching of arguments, xlim can be reduced to xli
N=list(array(c(0,3,3,2,2,0,0,0,0,1,1,3,3,0),dim=c(7,2)), #C polygon
       array(c(3,6,6,5,5,4,4,3,3,0,0,1,1,3,3,1,1,0),dim=c(9,2)), #D polygon
       array(c(6,6,7,7,9,9,6,0,1,1,3,3,0,0),dim=c(7,2)), #E polygon
       array(c(2,4,4,2,2,1,1,3,3,1),dim=(5,2)), #Db polygon
       array(c(5,7,7,5,5,1,1,3,3,1),dim=(5,2)))  #Eb polygon
c=c(NA,NA,NA,1,1) #Colors: by default 1 is "black"
for(i in 1:5){polygon(N[[i]],color=c[i])}
h=c(261.63,293.66,329.63,277.18,311.13) #Notes frequency in hertz: C4, D4, E4, Db4 and Eb4
library(tuneR)
setWavPlayer("~/Library/Audio/playRwave") #This can be change to other wav player I think
repeat{
    P=data.frame(locator(1)) #Grab coordinates of selected point
    H=h[sapply(N,function(x)splancs::inout(P,x))] #In which polygon does the selected point belong to, then map it to its ferquency
    s=sine(H,bit=16) #By default create a 1sec note at the given frequency with 44100 sampling rate
    play(s)
    }


text:
Generate a valid sequence of numbers with specific rules
The challenge
The program must return a valid sequence of numbers into some rules
Rules

x is the size of the sequence;
x cannot be less than 4 or greater than 9 (Thanks David Carraher);
Digits of the sentence can't repeat, each one must appear once;
All digits between 1 to x must be in the sequence;
A valid sequence never begins nor ends with 1 or x;
Into the sequence, numbers can never appear "together";

Examples
If x=4:
2413 valid
3142 valid
1423 not valid, because begins with 1 and 23 are "together".
2134 not valid, because ends with x and 34 are "together".
Still don't get it?
Other example:
If x=8:
28375146 valid, because don't start with 1 nor x(8), don't end with 1 nor x, and no numbers are "together"(no numbers touches, no numbers are the next or previous)
Sorry, I really don't know how to explain the last rule. Hope the example make it understandable.
Additional Information

x does not need to be an input, you can show the outputs for x=4 and x=9 working;
Since any language will be accepted and, I don't know how all of them work, I will ask you people to help me with this;
The winner will be the one who got more up-votes in 1 week, so please, vote the answer you find the best; I will mark it as the Correct one;

Good, luck. =)

Is it correct to assume that x can not be greater than 9?

Sure, forgot it but already edited. Thanks!

23 are together; Are 32 together?

Yes, they can never be the previous or the next

I recommend you amend the challenge to allow for numbers greater than 9. (Otherwise it is trivial to solve. Consider 952647183, for example.) You can make the challenge much harder by requiring that the answer be given as a list.  E.g. {2,4,1,3}

I understand your idea of the list answer, but i can't figure why would it be harder for x > 9, since the program is done, it would work for any x... The only impasse would be the missing of the comma

Is x an input for the program ? Is 20000 a valid sequence ?

There's no need for inputs, x can be just a variable... 20000 isn't a valid sequence, it repeats 0, five times

So 00 are "together" too ? You really should have defined this word !

Ok @Orabîg, it is now, thanks for the comment

How is input provided and what is the winning criteria?

@DavidCarraher, it depends on the language. My current GolfScript solution actually produces a list and relies on the interpreter to flatten it; converting it to a string representing a list would be one character more.

Answered @ardnew !

GolfScript (17 16 chars)
Assuming input on stdin and output on stdout.
~:^),(;{-2\^%?}$

Almost alphanumeric-free...

Oct 31, 2011: Happy Halloween! '?' operator now works correctly for finding substrings in strings, or strings in arrays. Thank you Peter Taylor! Omg Who are you?

@BernaMariano, that was a pretty small patch. I just happened to notice someone else's question on StackOverflow and realise that string string ? or string array ? could never return anything useful, so I proposed making them do something slightly different.

@PeterTaylor Hahahah my next challenge I will add a rule: "Peter Taylor is not allowed to answer" hahaha

May I try to answer my own challenge?
Javascript (35 chars)
a="1";for(i=x;i>1;i--)a=i%2?a+i:i+a

Outputs
document.write(a);

4 => 2413
5 => 24153
6 => 246153
7 => 2461753
8 => 24681753
9 => 246819753

Surely i%2?a+=i:a=i+a can be shortened to a=i%2?a+i:i+a? And i>=2 is trivially i>1

@PeterTaylor Thanks! Actually I tried a=i%2?a+i:i+a but maybe I was doing something wrong because it didn't work, but I did tried this way... The i>1 you are totally right, my bad :P Already edited, now you can vote it up haha

Mathematica 38
This simply returns the digits less than or equal to x, in the order in which they appear below.
Row@Select[{2, 9, 6, 4, 7, 1, 8, 5, 3},#<x+1&]

The results from 4 through 9:

When x=9 the output breaks a rule, the sequence starts with 9

Good catch. I missed that rule.  That means that the answer for 5 also doesn't work.

Haskell 78
a 4=[3,1,4,2]
a x=let b=filter even [1..x]++filter odd[1..x]in tail b++[b!!0]

This defines a function a that takes one parameter, the desired length of the sequence. This function returns a list of numbers in that sequence. I believe this works for x >= 4
This can probably be golfed further (I don't have that much experience in haskell)
Example (in ghci)
ghci> a 4
[3,1,4,2]
ghci> a 9
[4,6,8,1,3,5,7,9,2]

Haskell 25
This version is from before a rule change that now requires that every digit from 1 to x be used exactly once in the sequence
This should work for any sequence of length > 2 (even though the rules only required 4 <= x <= 9)
putStrLn$take x$cycle"02"

Input
The number of digits in the sequence is stored in x.
Output
x = 6 :: Int
020202

x = 4 :: Int
0202

A recent rule change made this solution wrong. I will fix it soon.

Looking forward your fix, @Matt!

Perl 96 chars (obsolete solution since the new rules)
For what I can understand from the rules, we can assume that X is predefined.
Then this solution should work :
for(2x$x..9x$x){if(!/^$x/+/$x$/+/1$/){$L=0;map{$d=$L-$_;abs$d>1||next;$L=$_}split//;print;exit}}

which is 96 characters long, although the algorithm is very naive.
It gives the following solutions :
2
30
240
2402
24020
240202
2402020
24020202
240202020

Thus, it seems obvious than there is room to a much simpler program which directly computes a solution of this form...

The following program outputs all valid sequences with any given length X (takes X in STDIN)
$x=<>;$b=10**$x;for($b/10..$b-1){if(!/^$x/+/$x$/+/1$/){$L=0;map{$d=$L-$_;abs$d>1||next;$L=$_}split//;print"$_
"}}

If you want to output ALL possible solutions (for any X), then the program becomes (102 chars) :
for(;;){$x=length$_++;if(!/^$x/+/$x$/+/1$/){$L=0;map{$d=$L-$_;abs$d>1||next;$L=$_}split//;print"$_
"}}

You updated your solution, but it doesn't follow all the rules. (Your old solution was posted before the rule change) specifically All digits between 1 to x must be in the sequence

Hey, you're right. This is a huge change ! How are we supposed to play on a moving ground ? ^^ Ok, I'll update my solution if I get some time...

Yeah I'm sorry for not pointing this rule, actually I thought that by just mentioning some examples it would be visible, my fault.

PHP, 64
If I understand the rules correctly, this should work:
for($i=1;$i<=$x;$i++)echo($x%2?2*$i%$x+1:2*$i-($x+1)*($i>$x/2));
If x is odd, this simply cycles through multiples of 2 % x + 1 to produce sequences like 357924681. If x is even, this does the same, but halfway through subtracts 1+x because 2i%x+1 would otherwise never produce even values.

sequences like 357924681 - that one's invalid, because it ends in 1.

Ah, ok. I thought it could only not begin in 1. In that case, this type of solution will not work.

There is a similar approach which works: count down in odd numbers to 1; then have the largest number; then count up in even numbers from 2.

I was hoping to utilize non-trivial generators of the set Z/xZ so that I didn't have to use too many branches.

GolfScript, 22 20 chars
~.1|,.+2%(;(@.1&,~;\

Outputs the following sequences for the inputs 4 through 9:
2413
41352
246135
4613572
24681357
468135792

For even inputs, just ~),.+2%(; would suffice.  I'm not too happy with the kluge for handling odd input values; there's got to be a more efficient way to do it.
Edit: Saved two chars by changing the output for odd inputs a bit and playing silly stack manipulation tricks.  Still not too happy with the length.

I really don't get this GolfScript, how can I compile and run this?

Download the interpreter (a Ruby script) from this site and run it e.g. like this: echo 9 | ruby golfscript.rb program.gs, where program.gs contains the code above.

You can also check out the GolfScript Interpreter too.

@Mike: ...but if you do, you'll need to hardcode the input into the program (e.g. by prepending ;"INPUT GOES HERE" to the code), since that interpreter doesn't seem to provide a separate field for input.

@IlmariKaronen, I still don't get it, the echo 9 | ruby golfscript.rb program.gs thing... =(

@IlmariKaronen Correct, I should have mentioned that.  Thank you for doing so.

Python, 37
range(3,x+1,2)+[1]+range(4,x+1,2)+[2])

http://ideone.com/xK40m

Python,30:
' 3579'[:(1+x)/2]+'1468'[:x/2]+'2'

http://ideone.com/3csRh