# Question
Title: -ENDED- Do something that looks like something else
Write a snippet, a function, a programm, ... that is obfuscated in a way that it looks clear at the first sight that it does something else.

For example: write a bit of code that adds two number, but when you ask someone "what does it do?", he will tell you it prints "Hello, World!".

**Rules**

* The code must be readable for someone who roughly knows the language you use (avoid intrinsic obfuscated language like APL, in your own interest).
* The code must do something unexpected that the reader initially couldn't predict.
* When you ask different readers, they must have the same (wrong) opinion about what the code does.

**Rating**

* Please read other contestants' codes during maximum 10-20 seconds, just to have a good idea of what happens there.
* Add a comment to the answer saying what you *think* the code does. If the answer you want to give is already there, simply *+1* the comment. (if you miss that answer and add another comment, don't worry, it won't be counted as another answer).
* The points will be awared this way: (`maxFalseOpinion` \- `goodGuess`) / `totalOpinion` (see example below).
* **Rate other contestants with fairplay** and don't comment your own code.
* Only add useful comments. Avoid "I don't know" and "good one!", they are not taken into account for the rating, but it's the code and not the ratings that must be obfuscated.

**Rating example**

The snippet adds two numbers. The comments say:

(3) It displays "Hello, World!"
(1) It substracts 2 numbers.
(2) It adds 2 numbers.

The total amount of points is the maximum number of opinions (3) - the number of good guesses (2) divided by the total amount of guesses (3 + 1 + 2 = 6). Result: (3 - 2) / 6 = 1/6 = **16.67%**.

---

**MORE ABOUT POINTS**

People seem to have some trouble figuring out the points.

Here is a perfect score:

```
printf('Hello World');

```

*comments:*
It displays the number of time you have clicked a button. (17 comments).
TOTAL: 17 comments

Score: (17 - 0)/17 = 1 = 100%

Here is a lame score:

```
printf('Hello World');

```

*comments:*
It prints "Hello World". (13 comments).
TOTAL: 13 comments

Score: (0 - 13) / 13 = -1 = -100%

Here is a not so bad score:

```
printf('Hello World');

```

*comments:*
It prints the user name. (2 comments).
It displays the current time (15 comments).
It returns what you entered without modification. (3 comment).
It prints "Hello World" (1 comment).
TOTAL: 21 comments

Score: (15 - 1) / 21 = 0.6667 = 66.67%
Explaining :
15 is the main guess, what people said the most. 1 is the correct number of guesses. 21 is the sum of all comments.

# Answer
## Javascript

```
var а;
a = 1;
а++;
alert( a );

```

Answer: **It outputs `1`.** The comments below explain it pretty well - there are two different variables here, a - 'LATIN SMALL LETTER A' and а - 'CYRILLIC SMALL LETTER A'.

There was **1** correct answer, **50** people thought it outputs 2, and with a total of **52** answers, the score is (50 - 1) / 52 = 49 / 52 = **94,23%**
> 79 votes

# Answer
## C, Score 33.3%

```
#include <stdio.h>
int main(int ac, char **av) {
        const char *arg = av[1];
        #define valid_ch(ch) (ch!='&' && ch!='\\')  // All valid except & and \
        while (*arg)
        {
                if (valid_ch(*arg)) putchar(*arg);
                arg++;
        }
        puts("");
        return 0;
}

```

Run `./prog 'Hello & goodbye, world!'`

## Score

The correct answer is `H\n` (the `while` is part of the comment, thanks to the line ending with `\`, so there's no loop), given by 6 people.
The most popular mistake was `Hello goodbye, world\n`, given by 25 people.
(25 - 6) / 57 = 33.3%.
Thanks to Olivier Dulac for bothering to calculate.
> 32 votes

# Answer
# Python

```
a = []
for i in range(10):
    a.append(i * ++i)
for a[i] in a:
    print(a[i])

```

**Rating**

1. **Good answer:** Prints `0
1
4
9
16
25
36
49
64
64`, each number on one line.
2. **Explanation:** Despite nobody getting the right answer, I consider this mostly a failed attempt, because nobody made the mistake I had intended. (I'll add a real explanation later if nobody else does.)
3. Number of good answers: 0
4. Number of peoply with same wrong answer: 7
5. Total number of answers: 11
6. **Score:** 63,64 % (rounded to two decimals)

## Explanation

First, a list `a` is created and filled with values `i * ++i`. There is no `++` operator in Python, but there is a unary `+` operator, which does nothing for integers, and applying it two times still does nothing. So `a` contains the squares of the integers from `0` to `9`.

I had put the `++` as a distraction and hoped that most voters would go on, thinking they had found the trap, and fall into the real trap. It didn't work out. Some thought that `++` is a syntax error, and the others still looked for the trap.

**The trap** The trap was in the second for loop:

```
for a[i] in a:
    print(a[i])

```

I was sure that most people would think this prints out all the `a[i]`, i.e. `0 1 4 9 16 25 36 49 64 81`, each number on one line. That's what you get with this variaton, for example:

```
for x in a:
    print(x)

```

`x` is assigned the values in `a`, and then `x` is printed. In the first version, `a[i]` is assigned the values in `a`, and then `a[i]` is printed. The difference is, that in our case we have `i == 9`, and thus the value of `a[9]` is changed each time through the loop. When finally `a[9]` is printed, it has the value of `a[8]`, and thus `64` is printed again.
> 27 votes

# Answer
**JavaScript**, Score of **-100%**

I did not invent this, Gary Bernhardt did but it is one of my favourites

```
alert(Array(16).join("wat?" - 1)+", BATMAN!")

```
> 26 votes

# Answer
# Perl, 26.67%

**Results:**

**This prints "I am ambivalent about saying anything at all."**

`my $num1,$num2 = @_;` is missing parentheses. Therefore, it is equivalent to `my $num1; $num2 = @_;`. `$num1` doesn't get set to anything.

Thus `$num1` is never greater than zero. The bit about the secret fish world hidden off the screen is, err, a red herring, so that people think they have found the "trick".

Furthermore, the ternary operator is an l-value in Perl: `1 ? $a = 1 : $b = 2` actually means `(1 ? $a = 1 : $b) = 2`. Which means `($a = 1) = 2` is evaluated, setting `$a` to `2`. Contrary to appearances, The second string is assigned to `$num1`.

In case you are wondering,`//` is the defined-or operator. If the sub returned an undefined value, the string `"Stuff did not happen."` would be printed. But it doesn't actually happen. It was just to give people another option.

**Scoring:**

Total correct: 5

Total guesses: 30

Score: (13 - 5) / 30 = 26.67%

```
no warnings;
no strict;
no feature;
no 5.16;
no Carp;

sub do_mysterious_stuff
{
    my $num1,$num2 = @_;

    if ($num1 > 0)
    {                                                                                eval q; $num1="This is a secret fish world. Carp cannot be repressed!" or
       $num1 = "Hello, world!";
    }
    else
    {
        $num2 > 0 ?
            $num1 = "What's up, world?":
            $num2 = "I am ambivalent about saying anything at all.";
    }

    return $num1;
}

print do_mysterious_stuff(1,1) //"Stuff did not happen.";

```
> 14 votes

# Answer
# Python, -54.8%

Answer: Raises `SyntaxError: not a chance`

```
from __future__ import braces

if (input() > 0) {
print 'You entered a positive number';
}
else {
print 'You didn\'t enter a positive number';
}

```
* Good guesses: 24
* Same bad guesses: 7
* Total guesses: 31

Explanation:

`from __future__ import braces` is one of the easter eggs in Python. It is meant as a joke, saying that Python will never use braces for scoping in the future.
> 14 votes

# Answer
## **PHP** 52%

```
  $arg = 'T';
  $vehicle = ( ( $arg == 'B' ) ? 'bus' :
               ( $arg == 'A' ) ? 'airplane' :
               ( $arg == 'T' ) ? 'train' :
               ( $arg == 'C' ) ? 'car' :
               ( $arg == 'H' ) ? 'horse' :
               'feet' );
  echo $vehicle;

```

(Copied verbatim from here)

**Explanation & Score**

> The correct answer is **horse**. This isn't a trick or sleight of hand. Bizarrely, this is how the ternary operator is defined in PHP.
> **3** chose the correct answer: **horse**,
> **16** people chose **train** which is correct in literally every other language ever invented, except PHP.
> **25** answers total, giving a score of (16 - 3) / 25 = 52%
> 14 votes

# Answer
# C++ 28.9%

```
#include <iostream>

using namespace std;

void print( void ) {
  static int times = 0;

  switch( times ) {
  case 0:
     cout << "Hello";
     break;
  case 1:
     cout << "World";
     break;
  default:
     cout << "Goodbye";
     break;
  }
  times++;
}

int main(int cout, char* argv[]) {

  print();
  cout << '\n';
  print();
}

```

## Solution

> The point of this code is to trick the user into thinking that a newline character will be printed between the text "Hello" and "World". Notice that the first parameter to main is named cout. Since, in the scope of main, cout is an integer, the \<\< operator actually performs a left shift operation with a parameter of '\n', rather than printing a newline. The print function is there mainly to take attention away from the input parameters in main, but also to allow std::cout to be used without adding the namespace prefix.

## Score

Courtesy of Alvin Wong

* Total 38 answers:
* 12 thought `HelloWorld` (considering minitech's and zeel's are the same)
* 23 thought `Hello\nworld` 3 thought something else.
* Score is (23 - 12) / 38 = **28.9%**
> 12 votes

# Answer
# Ruby, 100%

```
display = lambda { puts "Hello, world!" }
display()

```

Correct answer:

> Prints "main" with no newline. Explanation: In Ruby, you can't call a lambda using the normal parentheses syntax. Instead, display() is interpreted as the built-in method all objects have: o.display prints o.to\_s to standard output. Methods called without an object are interpreted as methods of "main", an Object that includes the Kernel module.

Score: 3 of the same wrong answer, no other answers.
> 10 votes

# Answer
# Python, -28.13%

```
x = 0
while x < 10:
    if (x%2)==0: x += 2
else: x += 1

print x

```

---

This prints `11` because the `else` block, which belongs to the `while`, is executed after the loop is exited.

* Maximum number of false guesses: 8
* Correct guesses: 17
* Total guesses: 8 + 17 + 7 = 32

Score: (8 - 17) / 32 = -28.13%
> 8 votes

# Answer
## Python: Rating: -27%

```
name = "Robin"
seek = "Seek and find holy grail"
favorite_color = "blue"

from os import *

print "What is your name: %s" % name
print "What is your quest: %s" % seek
print "What is your favorite color: %s" % favorite_color

```

The program prints:

```
What is your name: <value of os.name>
What is your quest: Seek and find holy grail
What is your favorite color: blue

```

Rating: Total opinions: 22 12 correct 3 + 1 + 6 wrong \[for Bakuiru's answer, I would say it was close but still incorrect as os.name is a string (os.uname is a function)\]

Rating based on that assumption and my understanding of the rating system: Maximum wrong = 6 Correct = 12 Score = (6-12)/22 = -27%
> 8 votes

# Answer
## JavaScript, -46.7%

```
var getResult = function(n, notReadyYet) {
    alert("Calculating results...");
    if (notReadyYet) {
        setTimeout(getResult, 100, n);
    } else {
        sayResult(n);
    }
    return arguments.callee;
}

var sayResult = function(n) {
    if (n >= 10) {
        alert("That's a big number!");
    }
    if (n < 10) {
        alert("That's a small number.");
    }
    return n;
}

(function() {
    var input = parseInt(prompt("Please enter a number:"));
    var result = getResult(input, true);
    return result;
})();

```

You can run it here when you're ready (have a guess first!). If you scroll down far enough in the JS panel, you will see the code with a brief explanation.

Correct answer:

> After asking the user to enter a number, it will enter into an infinite loop and display "Calculating results..." alerts until the maximum call stack size is exceeded (although the jsfiddle example will stop after about 20 times). However, if a semicolon is placed after the closing brace of the sayResult function, it will work as mgibsonbr described in the comments.

Scoring:

* Good answers: 9
* Most popular false opinion: 2
* Total answers: 15
> 7 votes

# Answer
Python

```
import sys

class TwoPlusTwoIsFive(object):
  def __bool__(self):
    if 2 + 2 == 5:
      return True
    else:
      return False

two_plus_two_is_five = TwoPlusTwoIsFive()

if two_plus_two_is_five:
  print('{} is company'.format(sys.version[0]))
else:
  print('{} is a crowd'.format(sys.version[0]))

```

---

edit:

score (8-1)/9 == 77.7 %

correct output is '2 is company' on python 2, '3 is a crowd' on python 3.
> 7 votes

# Answer
## Javascript

```
var a = [];
a.push( "Hello" );
a.concat( [ ", ", "world", "!" ] );
alert( a.join("") )

```

Answer: **It alerts `Hello`**. The `concat` method does not modify the array - it *returns* an array which contains the concatenation of the array it's called on and any other supplied arguments.

**15** correct, **26** wrong, **41** answers in total and the score is (26-15) / 41 = 11 / 41 = **26,83%**
> 6 votes

# Answer
**C# 62.5%**

```
int sum=0;
List<Task> threads = new List<Task>();
for (int i=1; i<=10; i++) {
  Task adder = new Task( ()=> sum += i );
  threads.Add( adder );
  adder.Start();
}
foreach (var t in threads ) {
  t.Wait();
}
Console.WriteLine("Sum of all numbers in 1..10 is: "+sum);

```

This is my first code golf.

The correct answer was: "something between 55 and 110". That's because whenever the "sum+=i" statement executes, it'll use the current value of i. This code might even execute *after the for loop is done*, at which point i has value 11. This makes the highest-possible value 110 (and you can make sure to see it if you slow down the lambda in your testing). The smallest possible value is sum(1..10), which is 55.

* Good answers: 0
* Only approximately good answers: 5
* Number of times the most popular answer was selected: 5
* Total answers: 8

score: strictly speaking, no one got it right so the score should be (5-0)/8=**62.5%.** If we're willing to count "approximately good" as a correct answer, then the score is (5-5)/8=0%
> 5 votes

# Answer
**Java**

```
public class Puzzle {

    public static void main(String[] args) {
        String out = "Some ungodly gibberish";
        //char x = \u000a; out = out + " and then some more. ";
        System.out.println(out);
    }
}

```

First attempt at codegolf...

good answer: Prints `Some ungodly gibberish and then some more.` and a newline

Rating:

* Maximum number of guesses 6
* Total number of guesses 11
* number of correct guesses 5 (0 if you're in pedanitc mode)

Score: 9% (55% in pedantic mode)
> 5 votes

# Answer
## Python 33.3%

```
def Test():
    False = True
    True = False
    if False:
        return False
    elif True:
        return True
    else:
        return None

a = Test()
print a

```

Note: Assume this is Python 2.x, and not Python 3.

---

When run, this code produced an `UnboundLocalError: local variable 'True' referenced before assignment`.
> 5 votes

# Answer
## PHP, 100%

First time posting to code gulf, hopefully this isn't to bad.

```
function word_to_num($word) {
 switch ($word) {
  case "one":
   return 1;
  case "two":
   return 2;
  case "three":
   return 3;
  default:
   return "error";
 }
}
function print_word($num) {
 switch ($num) {
  case 1:
   print "hello";
   break;
  case 2:
   print "world";
   break;
  case "error":
  default:
   print " ";
  }
}

$words = array("one", 0, "two");
foreach ($words as $word) {
 $result = word_to_num($word);
 print_word($result);
}

```

---

correct output is 'hellohelloworld'

score is (10 - 0) / 10 = 1 = 100%
> 4 votes

# Answer
# Python, -83.3%

Answer: Prints `a < b` if the inputs are equal, `a = b` if the first is larger, and `a > b` if the second is larger.

```
a = input()
b = input()
print 'a', '<=>'[cmp(a, b)], 'b'

```
* Good guesses: 11
* Same bad guesses: 1
* Total guesses: 12

Explanation:

`cmp(a, b)` returns `0` if both arguments are equal, `1` if the first is larger, and `-1` if the first is smaller, which is why the wrong comparison symbol is printed.
> 4 votes

# Answer
## Perl: 100% (4-0)/4

```
print (1 + 2) * 3, "\n";
#

```

This program prints "3" without a new line. Perl parses this instruction as

```
((print (1+2)) * 3, "\n")

```

so only the `(1+2)` is passed as an argument to `print`.
> 4 votes

# Answer
# C (Score: 4.45%)

Good guesses: 7
Maximum of wrong guesses: 6+2 = 8
Total guesses: 6+7+3+2+4=22

**Solution:** `??/` is a trigraph for `\`, so the newline is escaped and the `scanf` line is commented out. Therefore the program runs forever, printing `Guess a number between 1 and 10:`. The comments are a quote from Mozart (via `fortune`).

```
// Why not?/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// What?/
int main(int argc, char** argv)
{
    // Why not?/
    int number;

    // Why should I not send it?/
    srand(time(NULL));

    while(1)
    {
        // Why should I not dispatch it?/
        printf("Guess a number between 1 and 10: ");

        // Why not??/
        scanf("%d", &number);

        // Strange! I don't know why I shouldn't/
        if(number == rand() % 10 + 1)
        {
            // Well, then/
            printf("You guessed right!\n");
            // You will do me this favor./
            exit(0);
        }
    }
}

```

Spoiler, how to compile and run:

> gcc test.c -trigraphs
> 3 votes

# Answer
# Java

```
public class Test {
    public static void main(String[] args) {
        String fmt = "%s - %04d\n";
        System.out.println(fmt.format("Padded value: ", 0x0c));
    }
}

```

## The Answer

It prints `Padded value:` (with a newline).

String's `format` method is `static`, with the format being passed as the first parameter. I.e. the call above is equivalent to:

```
        System.out.println(String.format("Padded value: ", 0x0c));

```

Number of good answers: 2 Wrong answers: 9

**Score**: (9-2) / 11 = 63%
> 3 votes

# Answer
CPython

```
if 'Hello' + 'World' is 'HelloWorld':
  print 'Hello'
if 'Hello' + 'World!' is 'HelloWorld!':
  print 'World!'

```

---

correct output is 'Hello'

score (14-3)/19 == 57.9 %
> 3 votes

# Answer
**C**

```
#include <stdio.h>
#define SIX  1+5
#define NINE 8+1

int main()
{
    printf("%d\n", SIX * NINE);
}

```

Score = (3-16)/19 == -68.4%

Don't forget your towel.
> 3 votes

# Answer
**C#**

```
static void Main(string[] args)
{
     Console.WriteLine('H' + 'e' + 'l' + 'l' + 'o');
     Console.ReadLine();
}

```
> 3 votes

# Answer
# C++

```
#include <cstdio>

int main()
{
    int f;

    f or (f = 0, f < 1000, ++f,
        printf("H ello world !\n"));

    return 0;
}

```

### Score = (1 - 6) / 7 = -0.71428571428571 = -71.428571428571%
> 3 votes

# Answer
## R: 100%

Not that imaginative but might puzzle some people:

```
sum(data.frame(rep(1,10),stringAsFactors=TRUE))

```

What do you think is the result?

**Edit**:

The answer was 20. Because of a missing `s` in `stringAsFactors` (instead of `stringsAsFactors`), the argument is not recognized so the function create a new column called `stringAsFactors`. Because of vector recycling, the column contains 10 times `TRUE` which are converted to `1`s in the sum, hence a total of 20 and not 10.

This answer was not given in the comments. 3 answers were given (all saying `10` more or less). Hence a score of an 100%, I guess.
> 2 votes

# Answer
## Tcl

Inspired by ugoren

```
foreach c [split [lindex $argv 0] {}] {
    # Don't print the invalid chars & and \
    if {$c in "& \\"} {continue}
    puts -nonewline $c
}

```

Sorry, forgot an example string. Ok, run as

> ./charfilter.tcl 'Hello & goodbye, world!'

**Edit** Right solution: It does not filter at all. (**6x**)
Max wrong answer: **4x**
Total answers: **10**
Score: **-0.2**
> 2 votes

# Answer
Python

```
def greeting():
  try:
    return 'Hello World'
  finally:
    return 'HELL0 W0RLD'

print greeting().lower()

```

correct output is 'hell0 w0rld'

score (8-14)/22 == -27.3 %
> 2 votes

# Answer
**JavaScript**

```
var x = 0;
var y = !x * 4;
var z = !y;
alert("Z = "+z);

```
> 2 votes

# Answer
```
<?php
for ($i = 'a'; $i <= 'z'; $i++)
    echo "$i\n";

```

That is my code, asked only two php developers and they were wrong, can you think that it should do and make a test, comments about that are welcome.
> 2 votes

# Answer
## Python

I'm new to code golf so correct my if anything is wrong or I have misunderstood something

```
a = 0
b = 1
print b**a

```

New try:

```
print -1**0.5

```
> 1 votes

# Answer
# Q - 100%

```
server:":localhost:1234:username:password";
h:hopen server;
h@(-1;"Alert Message");

```

### Score

The correct answer was not given. This exploits the fact that the underlying k instruction for `hopen` (opening a handle to a remote instance) is the same as `iasc` (the indices needed to sort a list).
> 1 votes

# Answer
# C# - 100%

```
static void Main(string[] args)
    {
        var h = "Hello, world.";
        var key = "\u007C\u002D\u007C\u0033\u0031\u0031\u0030\u002C\u0020\u005C\u002F\u005C\u002F\u0030\u0052\u0031\u005B\u0029\u0021";
        var StringToHash = h + key;
        System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
        byte[] b = System.Text.Encoding.ASCII.GetBytes(StringToHash);
        byte[] hashBytes = md5.ComputeHash(b);
        try {
            System.Text.StringBuilder sb = new System.Text.StringBuilder(0, -32);
            for (int i = 0; i < hashBytes.Length; i++) {
                sb.Append(hashBytes[i].ToString("x2"));
            }
            Console.WriteLine(sb.ToString());
        }
        catch {
            Console.WriteLine(StringToHash.Substring(13));
        }
        finally {
            Console.ReadLine();
        }
    }

```

### Answer: Prints "|-|3110, \\/\\/0r1{)!"

* Number of good answers: **0**
* Number of people who answered mostly the same thing: **5**
* Total number of answers: **5**
* Score: **(5-0) / 5 = 1 = 100%**
> 1 votes

# Answer
# JavaScript (V8)

```
(function a() {
    /* (function(package) {
     *  (function(a) {
     *      "use strict";
     *      var a\u005f = package;
     *      with(a_)
     *          this && a();
     *  })(a);
     * })();
     */

    var code = "";
    var match;
    var re = /[ /]\* (.+)$/gm;

    while(match = re.exec(a)) {
        code += match[1];
    }

    try {
        var package = {a: a};
        eval(code);
    } catch(ex) {
        console.log(/SyntaxError: (.+)/.exec(ex.stack)[1]);
        return;
    } finally {
        console.log(";-)");
    }
})();

```

The correct output is:

> Unexpected strict mode reserved word
> ;-)

So my result is sort of 100%, but it was probably too confusing. The only important part is the commented code, actually; the rest of it finds the code, executes it, and gets the error. But JavaScript doesn't have multiline strings.

(`package` is an ECMAScript 5 future reserved word and so can't be used inside the strict-mode inner function. `a\u005f` is a valid variable name. I'd expect people to expect that the error was "Strict mode code may not include a with statement" or just "Unexpected token ILLEGAL".)
> 1 votes

# Answer
# Python, -20%

Answer: Raises a `TypeError`.

```
from os import *

with open('random_bytes.txt', 'wb') as f:
        f.write(urandom(10))

```
* Good guesses: 3
* Same bad guesses: 2
* Total guesses: 5

Explanation:

When everything from `os` is imported (`from os import *`), the builtin function `open` is overwritten. `os.open` expects an integer as the second parameter, hence the `TypeError`.
> 1 votes

# Answer
**Perl: 100%**

```
my $x;
print $x++ ? 'Hello' : 'world';
print ++$x + ++$x . "\n";

```

**Answer:** world6 (with a line feed).

**Explanation:**

For perldoc :

> Note that just as in C, Perl doesn't define when the variable is incremented or decremented. You just know it will be done sometime before or after the value is returned. This also means that modifying a variable twice in the same statement will lead to undefined behavior.

**Score:**

total answer : 4
good answer : 0
score : (4-0)/4 = **100%**
> 1 votes

# Answer
**(C)Python:**

```
text_a = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc sed orci leo. Quisque ac semper leo. Nulla a justo id nulla viverra gravida. Donec ornare semper venenatis. In fringilla placerat sapien, ut pretium nibh pharetra ut. Aliquam mauris mi, venenatis nec lobortis id, fringilla sit amet leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam consectetur turpis at neque pulvinar sit amet congue tortor luctus. '''

text_b = '''Per me si va nella città dolente,
Per me si va nell'etterno dolore,
Per me si va nella perduta gente.
Giustizia mosse il mio alto fattore:
Fecemi la divina potestate,
La somma sapienza, e 'l primo amore.
Dinanzi a me non  fuor cose create
Se non etterne, e io etterna duro:
Lasciate ogni speranza, voi ch'entrate.'''

if (1, 2) is (1, 2) and (1, 2)[0] is (1, 2)[0]:
    print(text_a)
elif (1, 2) is not (1, 2) and (1, 2)[0] is (1, 2)[0]:
    print(text_b)
else:
    import __phello__.spam

```

Good answer:

> It prints the contents of `text_b`.

# good answers: `2`

# total answers: `5`

# score = (3 - 2) / 4 = 25%

**Explanation:**

Python's compiler is smart enough to use a single value for integer constants but this optimization is not (*currently*) applied to tuples, hence `(1, 2) is not (1, 2)` but `(1, 2)[0] is (1, 2)[0]`.
> 1 votes

# Answer
**Python:**

```
def f(n):
    result = []
    for i in range(n):
        result.append(lambda x: i - x)
    return result

n = 10
A = f(n)
for i in range(n):
    print(A[i](i))

```

**Rating**

1. **Good answer:** Prints `9
8
7
6
5
4
3
2
1
0`, each number on one line.
2. **Explanation:** Ten functions are created, each subtracts its argument from `i` from, and each is defined with a different value of `i`. So `A[i](i)` should subtract `i` from `i`, shouldn't it? No! The value of `i` that is subtracted is the value of the local variable `i` of the function `f`. This is `9` after `f(10)` finishes, independent of which `A[i]` is called. Too bad only one voter fell into the trap ;-)
3. Number of good answers: 4
4. Number of peoply with same wrong answer: 1
5. Total number of answers: 5
6. **Score:** -60 %
> 1 votes

# Answer
## Python

Please give the expected output without executing the below line.

---

```
print -1 ** 0.5

```
> 1 votes

# Answer
## Python

Tested using Python 2.7 and 3.3. I've updated this post with a more readable version:

```
def e(code):
    return eval(code)

try:
    items = sorted(globals().items())[0][1]
    for item in dir(items):
        if item[4:] * 2 == '':
            globals()[item[0]] = getattr(items, item)
finally:
    e('print("Ni hao, shijie!")')
    print('What, you don\'t speak Chinese?')

```

The previous, more obfuscated version:

```
def e(s):
    return eval(s)
#

glob = globals()
items = sorted(glob.items())[int()][True]
s = type(type('', (), {'__getitem__': lambda a, b: b})()[:])(0b100, None)
try:
    for item in dir(items):
        if item[s] * 2 == '':
            glob[item[0]] = getattr(items, item)
finally:
    e('print("Ni hao, shijie!")')
    print('What, you don\'t speak Chinese?')

```

### Score

The program exits without printing anything. The code within the try block loops through each item in `__builtins__` and looks for names of 4 characters or less. It registers them in the global namespace, using the first character of their original name. By doing so, the 'exit' function becomes available as 'e', replacing the function defined before the try block.

2 incorrect answers, 2 answers total: (2 - 0) / 2 = 100%
> 1 votes

# Answer
## Perl: -33% (1-2)/3

```
sub foo {
  ($TRUE,$FALSE) = ("0 but true",0);
  return $TRUE and $FALSE;
}
print &foo;

```

This program prints `0 but true` because Perl parses the `return` statement like

```
(return($TRUE)) and $FALSE;

```

not

```
return ($TRUE and $FALSE);

```
> 1 votes

# Answer
A little late, but I got some inspiration.

# JavaScript

```
// I miss Python :(
function print(x) {
    console.log(x)
}

// Build the points.
x = (1, 2, 3)
y = (4, 5, 6)
z = (7, 8, 9)

// Swap x and y.
[x, y] = [y, x]
print(x) // Prints (4, 5, 6)

```
> 1 votes

# Answer
# C++

```
#include <iostream>

#define ONE 1
#define TWO ONE+ONE
#define FOUR 2*TWO

int main()
{
    std::cout << FOUR << std::endl;
    return 0;
}

```

Output is `3`.

Actually to have `FOUR`, definition should be `2 * TWO * 2`, that looks really confusing.
> 1 votes

# Answer
**PHP**

```
<?php
function num2alpha($n) {
    $r = '';
    for ($i = 1; $n >= 0 && $i < 10; $i++) {
        $r = chr(0x41 + ($n % pow(26, $i) / pow(26, $i - 1))) . $r;
        $n -= pow(26, $i);
    }
    return $r;
}
echo num2alpha(3752126) . " " . num2alpha(10786571);
?>

```
> 0 votes

# Answer
# VBA

```
Sub a()
    b = c = 1
    Debug.Print b, c
End Sub

```
> 0 votes

# Answer
# Python

```
def test(foo, bar=[]):
    bar.append(foo)
    for i in bar:
        bar = bar * 2
    else:
        return i * len(bar)
    return bar

print [test(i) for i in range(3)]

```
> 0 votes

# Answer
**Python**

```
i = 1j
i = i ** 4
while (i ** 0.5).real:
    i -= 1
print(i)

```

**Rating**

1. **Good answer:** Prints `0j`.
2. **Explanation:** The first line was inteded to make the reader aware of the fact that Python works with complex numbers out of the box. Then, the counter `i` is set to `1 + 0j` and then is decreased until... well, until its `real` attribute has a falsey value. I had hoped to trick somebody into thinking that `real` means "this is a real number"; the loop would then go until `i` was `-1`. Apparently everybody knowing about complex numbers in Python also knows that `real` is just the real part of the number, and then `0j` is the first falsey value. Also, everybody remmbered that it's `0j`, not `0`. I'm impressed!
3. Number of good answers: 2
4. Number of peoply with same wrong answer: 0
5. Total number of answers: 2
6. **Score:** -100 %
> 0 votes

# Answer
## Erlang

What will be printed?

```
-module(confusion).
-compile(export_all).
go() ->
    Pi = "3",

    case Pi of
        3 ->
            io:format("Phew; pi is still the same");
        _ ->
            io:format("Pi has changed: ~p~n", Pi)
    end.

```

## The Answer

It prints:

```
 Pi has changed: 51

```
> 0 votes

# Answer
# JavaScript

I tried to keep it under 20 chars width. I hope the comments help.

```
f=function//functify
(s){
    var X;
    return new (X=
    function()
    {this.s=s},X.
    prototype.
    toString=
    function(){return
    this.s},X)(s)
}
w=function//wordify
(n) {
    return n
    ? f('world')
    : f('hello')
}
s=function//spacify
(a,b){
    return a
    + ' ' + b
}
m=function//main
() {
    alert(s(w(0),
    w(1)))
}
m()

```

If anyone figures it out, they probably know real pain. When I first stumbled across this a few years ago, it took me hours until I figured it out and I only understood it several months later when I read an article on JavaScript and I made the connection. You see, th͝e̸ ͢t̨hin͞g ̵is i̧͜n̶҉́ ̛͘͠J̷͟a͜͞v̶̧͠a̢̨͟͞S̷͞͞c͝r҉̶i̴͞͞p̷͟t̷̕҉ ̡͠z̨̢b͘͢ơ̢͜͞d̨̡͘i̷̛͜s̛͞è̡ a̵͘҉̕l̨͟͞s̶̶̀o͠͞ ̶͟͠͠b͢͟r̵i̶̡̛͟n̨҉̶g̸̴̕͡ ̕͞i̴̧n̢͜͡ ̵̧̀́͞ş͡͞o̷̧̧͜͜m̴̧ę̶b̶͞͠͝ee͜͡r̶̵̢.̴̶̸̢̨ a͢n̢d͜ ̸͟͞t̶͞h̶́a̕͘ţ ̴͢͟c̢a҉́n͘͟ r̴ea̧ll̸y͢ ̕m͞e̴s͡s with what you're expecting from your program.
> 0 votes

# Answer
# PHP

No comments this time. Comments should be on the HTML source that it will output, use backticks ( \` ) to escape HTML code in comments so Stack Exchange won't eat them up.

```
$funcs = array_shift(array_slice(get_defined_functions(), 1));
global $output;

function one() { return '<b>hello'; }
function two() { return ' '; }
function three() { return 'world'; }
function four() { return '!</b>'; }
function five() { echo '<pre>' . print_r($output); return '\n'; }

$output = array();
while ($funcs) {
    foreach ($funcs as $func) {
        $output = $output + array($func());
    }
    array_shift($funcs);
}

```

Whoever gets the answer is either a wizard or a liar.
> 0 votes

# Answer
I know the competition is over, but I couldn't resist to post this idea.

# Java:

```
public class QuadraticEq {
    /** Prints the roots of x^2 + bx + c = 0 (if they exists). */
    public static void root(double b, double c) {
        //System.out.print("x^2 + " + b + "x + " + c + ": ");
        double d = Math.sqrt(b*b - 4*c);
        double r1 = (d - b) / 2;
        double r2 = (-d - b) / 2;
        System.out.format(java.util.Locale.US, "%f, %f\n", r2, r1);
    }

    public static void main(String argv[]) {
        // Compute some square roots
        root(-0.9, 0.20);
        root(-0.4, 0.04);
        root(-1.4, 0.49);
        root( 0,   1);
    }
}

```
> 0 votes

# Answer
Yet another piece of code (after the deadline):

# Scala

```
object HW extends App {
  val yes = 1;
  val no  = 0;

  (6*7 % 2) match {
    case yes  => println("Hello world.");
    case no   => println("No, thanks.");
  }
}

```
> 0 votes

# Answer
Here it is for **C**

```
int main(){
    int a = 10;
    int b = 20;
    int c = a + b;
    printf("Hello World!");
}

```
> -1 votes

# Answer
# Ruby

```
puts "Please enter a boring sentence"
sentence = gets <<"!!!!!!!!111"
puts sentence
!!!!!!!!111

```

Edit: This might be getting downvoted because the user interaction makes it hard to test. Is that why? Hint:

> $ Try typing this at the prompt it gives you: puts sentence
> -1 votes

---
Tags: code-challenge, obfuscation
---


title: Wikipedia: Philosophy!

text:
# Question
Title: Wikipedia: Philosophy!
As many geeks may know most pages (95% i think) on wikipedia eventually lead to Philosophy like this:

Click on the first non-italic or in parentheses link that is to another normal article: (i.e. not File: or Special:, but things like Wikipedia: are OK) and repeat on that one until you hit philosophy.

The script must:

* Take a first page as input
* Print the name of each article it gets to
* And print how many articles it took to get to Philosophy, and if it didn't say so.

You start with 1000 points, and lose one for each character in the code, Bonus points for:

Detecting looping articles and stopping: +50

Detecting looping articles and requesting if the user should go to the next link on the article: +170

Allowing for a default on the former check as a command-line arg or similar: +140

Highest score wins.

# Answer
# Ruby, 1000 - ~~303~~ ~~299~~ ~~337 - 50~~ ~~373 - 170~~ ~~382 - 170 - 140~~ 379 - 170 - 140 chars = ~~697~~ ~~701~~ ~~713~~ ~~797~~ ~~928~~ 931

I'm sure there are *many* improvements to be made.

(This requires Nokogiri)

```
require'open-uri'
require'nokogiri'
x="/wiki/"+gets.chomp
r=[n=i=0]
until x=~/\/Philosophy/
d=Nokogiri.HTML open"http://en.wikipedia.org#{x}"
x=d.css('p a').select{|a|t=a.xpath('preceding::text()').map(&:text)*'';t.count('(')==t.count(')')&&a.attr('href')=~/^.wiki[^:]+$/}[i].attr'href'
i=0
puts r.index(x)?"#{$><<'i=';i=($*[0]||gets).to_i;''}": r.push(x)[-1][6..-1]
n+=1
end
p n

```

Example run:

```
c:\a\ruby>wikipedia_crawl_philosophy
Latin (note: this is my input)
Classical_antiquity
History
Umbrella_term
Terminology
Word
Linguistics
Science
Knowledge
Fact
Proof_(truth)
Argument
Logic
Reasoning
Consciousness
Quality_(philosophy)
Property_(philosophy)
Modern_philosophy
Philosophy
18

```

Sample one where I had to go to a different link

```
c:\a\ruby>wikipedia_crawl_philosophy
Snow
Precipitation_(meteorology)
Meteorology
Atmospheric_physics
Synoptic_scale_meteorology
i=2 // I put the 0-indexed number of the link I wanted to go to (so, the third link)

Weather
Atmosphere
Gas
State_of_matter#The_four_fundamental_states
Physics
Natural_science
Sciences
Knowledge
Fact
Proof_(truth)
Argument
Logic
Reasoning
Consciousness
Quality_(philosophy)
Property_(philosophy)
Modern_philosophy
Philosophy
25

```

Tricks I used:

* I used the selector `p a` to only get non-italic links, because all links in the actual article that are not italics are always in paragraph elements in Wikipedia.
> 8 votes

# Answer
# Scala (294 chars =\> 1000-294+140 = 846 points)

The updated solution which automatically takes the next link if one has already been consumed. ***Thanks for the 140 bonus points.***

**Logic:** Pick up the first "/wiki" link that doesn't have a ":" in it (so it ignores "File:" links). Rinse and repeat with recursion returning the count + 1 every time. I keep a list of all previous outputs handy so the program doesn't go into an infinite loop.

**Regular Expression:** I have 2 forms of the regular expression.

* `"<p>.*?\"/wiki/([^:]*?)\".*?/p>"` which finds links within the `<p>` tags
* `"p>.*?/wiki/([^:]*?)\""` which is a slightly more experimental tag that has proven to work but provide different results because it, at times, picks up links from the right side info bar. These are regular articles so I believe it is still valid. If it's adjudged to not be, the OP (or someone else) can leave me a comment and I can update my solution to a better reg-ex.

I'm going to be using the second regular expression until I find a test case where it doesn't work or the OP mentions picking up links from the side bar aren't allowed (in my opinion, the info bars are still part of the actual article itself; more of a summary).

---

**Minified Source:**

```
object W extends App{print(x(Seq(args(0))));def x(s:Seq[Any]):Int={val? =s.last;println(?);?match{case "Philosophy"=>1;case _=>x(s:+"p>.*?/wiki/([^:]*?)\".*?/p>".r.findAllMatchIn(io.Source.fromURL("http://en.wikipedia.org/wiki/"+ ?).getLines.mkString).map(_ group 1).filter(!s.contains(_)).next)+1}}}

```

**Readable Source:**

```
object W extends App {
  print(x(Seq(args(0))))

  def x(s: Seq[Any]): Int = {
    val ? = s.last
    println(?)
    ? match {
      case "Philosophy" => 1
      case _ => x(s :+ "p>.*?/wiki/([^:]*?)\"".r.findAllMatchIn(io.Source.fromURL("http://en.wikipedia.org/wiki/" + ?).getLines.mkString).map(_ group 1).filter(!s.contains(_)).next) + 1
    }
  }
}

```

**Sample Output:**

*Input*

```
Space_toilet

```

*Output*

```
Space_toilet
Weightlessness
G-force
Weight
Force
SI_unit
French_language
Second_language
Language_acquisition
Word
Linguistics
Science
Latin_language
Pontifical_Academy_for_Latin
Pope_Benedict_XVI
Pope_Benedict_(disambiguation)
Regnal_name#Catholic_Church
Monarch
State_(polity)
Community
Commutative_property
Mathematics
Quantity
Property_(philosophy)
Modern_philosophy
Philosophy
26

```
> 5 votes

# Answer
*"BASH*" – (If not mistaken: 1000 - 397 + 170 + 140 = 913 points)
*"BASH"* – (If not mistaken: 1000 - 386 + 170 + 140 = 924 points)

# *"BASH"* – (If not mistaken: 1000 - 381 + 170 + 140 = 929 points)

BASH is in quotes on purpose as this is a mix of tools used in \*nix shells but wrapped in a bash script.

## Edit 1:

* Removed `http://` as `curl` defaults to this.
* Changed `href=` match on anchors to `f=` as `<a>` does not have any other *normal* attributes ending in `f`. (It is a possibility of custom tags. Have not seen any so far.)
* Set exit message on not found to `!Phil` instead of `NoPhil`. This one is a bit quirky as One could also say e.g. `!`, `0`, `N`, `!P` or similar.
* Quirk two: `-s` on `curl` could be removed to reduce by three more bytes, but that would yield a messy output. Not sure if that is an issue.
* Updated *help* on this page.

Using quirks, code would end up at 379 bytes, 931 points.

I could also implement @plannapus usage of matching (hopefully) *navigation box* by adding `(p|ul).*?<(\1)` adding six bytes (subtracting six points).

## Edit 2:

Using `${#c[@]}` to print degrees of separation instead of `$i` counter.

Using quirks, code would end up at 374 bytes, 936 points.

---

I summon Cthulhu and go for a regexp + bash/shell/\*nix solution.

Stolen:

Implemented:

* Detect loop and ask if next link should be taken.
* Optionally select next link on duplicate as option.

Requirements:

* `bash` v.?
* `grep` with `-P` (PCRE) support.
* `sed`
* `curl`
* `cut`

Usage:

```
script PATH [OPTIONS]

Print separation of article from ``PATH'' to ``Philosophy'' on Wikipedia.
Degrees of separation, if found, is printed as last line.
If not found last line yields ``!Phil''.

PATH
     Absolute path to starting article, e.g: /wiki/Word
OPTIONS
     y   Automatically select next link if already visited.
     n   (Or other) Quit if next link already visited.
BUGS
     1. On previous visit; "next link" is not checked. Thus if next link
     has already been visited we get eternal loop. Not sure if this
     disqualify +170 points.
     2. Sure there are.

```

Inline code. Copy to file. `chmod +x filename`. Run by `./script /wiki/…` from bash shell.

```
u=($1);c=($1);while ! [[ "$u" =~ /Philosophy$ ]];do echo "$u";u=($(curl -s "en.wikipedia.org$u"|tr '\n' ' '|grep -Po '<p>.*?</p>'|sed 's/>[^<]*([^)]*)//g'|grep -o '<a [^>]*f="/wiki/[^":]*"'|cut -d\" -f2));for x in "${c[@]}";do if [ "$x" = "$u" ];then [ $2 ] &&s=$2||read -p "${u[0]}?" s;[ $s = y ] &&u[0]=${u[1]}||{ echo "!Phil";exit;} fi;done;c=("${c[@]}" "$u");done;echo ${#c[@]};

```

## Expanded and explained code:

```
u=($1); # Array of paths.
c=($1); # Array of visited paths.
# While $u != /Philosophy, ugly trick is to use $u instead of ${u[0]}.
while ! [[ "$u" =~ /Philosophy$ ]];do
        echo "$u";      # Print current page.
        # curl   : prints retreived page to stdout. "-s" could be skipped.
        # tr     : replace all newline with space. This is a ®sanity thing when it comes to
        #          twidling with html using regex.
        # grep 1 : match <p> tags. Using -P's ungreedy *?.
        # sed    : remove all occurences of "(" something ")".
        # grep 2 : match links where "href" attribute starts with /wiki/ and is not e.g. File:
        # cut    : match actual href value.
        # Result is added to array ``u''.
        u=($(curl -s "en.wikipedia.org$u" |
                tr '\n' ' ' |
                grep -Po '<p>.*?</p>' |
                sed 's/>[^<]*([^)]*)//g' |
                grep -o '<a [^>]*f="/wiki/[^":]*"' |
                cut -d\" -f2));

        # For previously visited pages as x.
        for x in "${c[@]}"; do
                # If x equals to first page ...
                if [ "$x" = "$u" ]; then
                        # Use option or ask.
                        [ $2 ] && s=$2 || read -p "${u[0]}?" s;
                        # If response is "y" use next link, else exit with status.
                        [ $s = y ] && u[0]=${u[1]} || {
                                echo "!Phil";
                                exit;
                        }
                fi;
        done;
        # Append current link to "visited"
        c=("${c[@]}" "$u");
done;
# Print number of visited pages.
echo ${#c[@]}

```
> 5 votes

# Answer
## JavaScript 726 (444 chars \[556\] + 170)

Now I appreciate that this might not be valid as a bookmarklet, but I've enjoyed tinkering with it anyway.

Usage: Navigate to the page you'd like to start from and run the following in the console:

```
(function(a){c=0,o="";$(u="html")[u](f=$('<iframe src="'+location+'?">').on("load",function(){$=f.contentWindow.$;p=f.contentDocument.title[s="split"](" - ")[0];c++;p=="Philosophy"?document.write("<pre>"+o+p+"\n"+c):(i=RegExp("^"+p+"$","m").test(o)?a||confirm("Loop, try next?")?2:0:1)&&(f.src=$("p>a").filter(function(){return(t=$(this).parent()[u]()[s](this.outerHTML)[0])[s]("(").length==t[s](")").length})[--i].href);o+=p+"\n"})[0])})(true)

```

For JavaScript the output is the following:

```
JavaScript
Interpreter (computing)
Computer science
Science
Knowledge
Fact
Proof (truth)
Argument
Logic
Reason
Consciousness
Quality (philosophy)
Property (philosophy)
Modern philosophy
Philosophy
15

```

This solution will assume you want to jump to the next link on a loop being detected, but if you change the `true` at the end to `false` it'll pop up a confirmation box instead (quite annoying...) not sure if that qualifies for the secondary bonus or not. I'll assume not.

Indented:

```
(function(l){
    c=0,o='';
    $(u='html')[u](f=$('<iframe src="'+location+'?">').on('load',function(){ // Firefox needs the ? to properly load the frame
        $=f.contentWindow.$; // reference repeated calls as strings to save more bytes
        p=f.contentDocument.title[s='split'](' - ')[0]; // get the title

        c++;
        p=='Philosophy'?
            document.write('<pre>'+o+p+'\n'+c): // pre for nice formatting
            (i=RegExp('^'+p+'$','m').test(o)?
                l||confirm('Loop, try next?')?
                    2: // desired index + 1 so we can use as a boolean
                    0
                :
                1)&&
            (f.src=$('p>a').filter(function(){
                return (t=$(this).parent()[u]()[s](this.outerHTML)[0])[s]('(').length == t[s](')').length // shorter, but still not overly happy with this...
            })[--i].href);
            o+=p+'\n' // update output
    })[0])
})(true) // change this to show confirm box when loop detected

```

So I originally missed the part about ignoring items in parens, adding that made it a lot more wordy, so I'm hoping to golf that filter function down (or hopefully replace it entirely).

Working in both Chrome and Firefox (tested in Firefox 26)
> 5 votes

# Answer
# C# - 813 chars

Score: 1000-813+50+170+140 = **547** :(

**No external libraries. Loop detection**.

First argument is the Source Article, second is the Target Article.

Golfed version:

```
class Program
{
    static void Main(string[] a)
    {
        Func<XmlDocument,IList<string>> G=delegate(XmlDocument xd){return xd.SelectNodes("//p//a[starts-with(@href,'/wiki/') and not(contains(@href,':'))]").Cast<XmlNode>().Select(n=>n.Attributes["href"].InnerText).ToList();};Action<string> W=delegate(string s){Console.WriteLine(s);};var h=new HashSet<string>();var c=new WebClient();var x=new XmlDocument();var t=c.DownloadString(@"http://wikipedia.org/wiki/"+a[0]);int i=0,C=0;
    GO:
        x.LoadXml(t);var ns=G(x);
    COL:
        var f=ns[i];if(f.Equals("/wiki/"+a[1],StringComparison.OrdinalIgnoreCase)){goto END;}if(h.Contains(f)){W("loop: "+f);i++;goto COL;}else{h.Add(f);i=0;C++;}W(f);t=c.DownloadString(@"http://wikipedia.org"+f);goto GO;
    END:
        W("Found in "+C);
    }
}

```

Intelligible version:

```
class Program
{
    // arg[0] source article. arg[1] target article
    static void Main(string[] arg)
    {
        Func<XmlDocument, IList<string>> G = delegate(XmlDocument xd)
        {
            return xd.SelectNodes("//p//a[starts-with(@href,'/wiki/') and not(contains(@href,':'))]").Cast<XmlNode>().Select(n => n.Attributes["href"].InnerText).ToList();
        };
        Action<string> W = delegate(string s) { Console.WriteLine(s); };
        var h = new HashSet<string>(); var c = new WebClient(); var x = new XmlDocument();
        var allText = c.DownloadString(@"http://wikipedia.org/wiki/" + arg[0]);
        int i = 0; int C = 0;
    GO:
        x.LoadXml(allText);
        var ns = G(x);
    COL:
        var f = ns[i];
        if (f.Equals("/wiki/" + arg[1], StringComparison.OrdinalIgnoreCase))
        {
            goto END;
        }
        if (h.Contains(f))
        {
            W("loop: " + f); i++; goto COL;
        }
        else
        {
            h.Add(f); i = 0; C++;
        }
        W(f);
        allText = c.DownloadString(@"http://wikipedia.org" + f);
        goto GO;
    END:
        W("Found in " + C);
    }
}

```

Example run, from "Sky" to "Philosophy":

```
C:\>wiki.exe Sky Philosophy

/wiki/Earth
/wiki/Geometric_albedo
/wiki/Phase_angle_(astronomy)
/wiki/Observational_astronomy
/wiki/Astronomy
/wiki/Natural_science
/wiki/Sciences
/wiki/Latin_language
/wiki/Classical_antiquity
/wiki/History
/wiki/Ancient_Greek
/wiki/Greek_language
/wiki/Modern_Greek
loop: /wiki/Greek_language
/wiki/Colloquialism
/wiki/Word
/wiki/Linguistics
/wiki/Science
loop: /wiki/Latin_language
/wiki/Knowledge
/wiki/Fact
/wiki/Latin
loop: /wiki/Classical_antiquity
/wiki/Italic_languages
/wiki/Indo-European_languages
/wiki/Language_family
/wiki/Language
/wiki/Human
/wiki/Extinct
/wiki/Biology
loop: /wiki/Natural_science
/wiki/Life
loop: /wiki/Earth
/wiki/Physical_body
/wiki/Physics
loop: /wiki/Greek_language
loop: /wiki/Natural_science
/wiki/Matter
/wiki/Rest_mass
/wiki/Center_of_momentum_frame
loop: /wiki/Physics
/wiki/Inertial_frame
loop: /wiki/Physics
/wiki/Frame_of_reference
loop: /wiki/Physics
/wiki/Coordinate_system
/wiki/Geometry
loop: /wiki/Ancient_Greek
/wiki/Mathematics
/wiki/Quantity
/wiki/Property_(philosophy)
/wiki/Modern_philosophy
Found in 41

C:\>

```
> 5 votes

# Answer
### R, 379 characters; 1000-379+170=791 points

Version that ask users how to proceed when looping detected

```
library(XML);w="http://en.wikipedia.org";W="/wiki/";n=1;A=c(scan(,""));while(A[n]!="Philosophy"){a=paste0(w,W,A[n]);d=sapply(strsplit(grep(W,sapply(xpathApply(xmlParse(readLines(a)),"//p/a[@href]|//ul/li/a[@href]",xmlAttrs),`[`,'href'),v=T),"/"),`[`,3);B=d[-grep(":",d)];n=n+1;if(B[1]%in%A)if(readline("Loop!2nd link?")=="n")break;A[n]=head(B[!B%in%A],1);cat(A[n],"\n")};cat(n-1)

```

With indentations and comments:

```
library(XML) #Uses package XML
w="http://en.wikipedia.org"
W="/wiki/"
n=1
A=c(scan(,"")) #Stdin + makes it a vector so we can store each iteration
while(A[n]!="Philosophy"){
    a=paste0(w,W,A[n])
    d=sapply(strsplit(grep(W,sapply( #The heart of the program
             xpathApply(xmlParse(readLines(a)),"//p/a[@href]|//ul/li/a[@href]",xmlAttrs),
             `[`,'href'),v=T),"/"),`[`,3)
    B=d[-grep(":",d)] #get rid of Templates, Files ,etc...
    n=n+1
    #Ask user if should proceed when loop encountered
    #(any answer other than "n" is considered agreement):
    if(B[1]%in%A)if(readline("Loop!2nd link?")=="n")break
    A[n]=head(B[!B%in%A],1) #Take the first link that is not redundant
    cat(A[n],"\n")
    }
cat(n-1)

```

Example run:

```
> library(XML);w="http://en.wikipedia.org";W="/wiki/";n=1;A=c(scan(,""));while(A[n]!="Philosophy"){a=paste(w,W,A[n],sep="");d=sapply(strsplit(grep(W,sapply(xpathApply(xmlParse(readLines(a)),"//p/a[@href]|//ul/li/a[@href]",xmlAttrs),`[`,'href'),v=T),"/"),`[`,3);B=d[-grep(":",d)];n=n+1;if(B[1]%in%A)if(readline("Loop!2nd link?")=="n")break;A[n]=head(B[!B%in%A],1);cat(A[n],"\n")};cat(n-1)
1: Extended_ASCII
2:
Read 1 item
Eight-bit
Computer_architecture
Computer_science
Science
Logic
List_of_aestheticians
Art
Human_behavior
Behavior
Organism
Biology
Loop!2nd link?y
Mathematics
Quantity
Property_(philosophy)
Modern_philosophy
Philosophy
16

```

### R, 325 characters; ??? points

Version that, by default takes first non-redundant link (i. e. non-looping).

```
library(XML);w="http://en.wikipedia.org";W="/wiki/";n=1;A=c(scan(,""));while(A[n]!="Philosophy"){a=paste0(w,W,A[n]);d=sapply(strsplit(grep(W,sapply(xpathApply(xmlParse(readLines(a)),"//p/a[@href]|//ul/li/a[@href]",xmlAttrs),`[`,'href'),v=T),"/"),`[`,3);B=d[-grep(":",d)];n=n+1;A[n]=head(B[!B%in%A],1);cat(A[n],"\n")};cat(n-1)

```
> 4 votes

---
Tags: code-challenge, internet
---


# Question
Title: Lua: Render a chess board in smallest code
I'm creating a simple challenge here as a first test of the community's reactions. Please let me know if this challenge is the kind of thing you guys like or what I can improve... :)

The task is this: Render a chess board in Lua in smallest code possible.

Here is an example solution: http://tinybrain.de/145

As you can see, there is definitely room for getting smaller than 657 bytes (# of bytes are printed on the page). All the information you need for coding should be on the page or, hopefully, on tinybrain.de. Mailed questions totally welcome too. Lua API overview: http://tinybrain.de:8080/tb/debug.php?cmd=144

I am not demanding your chess board to have the exact same colors or even the same size. It should look like a chess board, that's all.

You need to register on TinyBrain.de to submit and test code. (Sorry, hope that is OK... It's free and I'm not a data peddler, so no harm there... :)

Edit: For testing your code locally (without any registration or Internet connection), you can download the TinyBrain runtime (magic.jar). Here is the link: http://tinybrain.de:8080/magic.jar

# Answer
For a *fancy* ASCII art solution:

```
print("/"..("-"):rep(32).."\\")for y=0,15 do print("|"..("....    "):rep(5):sub(1+(y-y%2)*2%8):sub(1,32).."|")end print("\\"..("-"):rep(32).."/")

```

At 145 characters.

For a *small* ASCII art solution:

```
for i=1,8 do print(("# "):rep(9):sub(i,i+7))end

```

At 47 characters.
> 3 votes

# Answer
Starting with col6y's "small ASCII" solution (47):

```
for i=1,8 do print(("# "):rep(9):sub(i,i+7))end

```

sometimes brute force is better (43):

```
for i=1,4 do print("# # # # \n # # # #")end

```

:)
> 3 votes

# Answer
## 38

Combining 14921's and col6y's ideas:

```
print(("# # # # \n # # # #\n"):rep(4))

```
> 2 votes

# Answer
## 83 characters

This snippet takes advantage of the description's offer to omit one of the dimensions, and to use a single integer to represent the pixel color.

```
w=256
p={}
for i=0,65535 do p[i+1]=5595493-((i-i%32)/32+(i-i%8192)/8192)%2*26214 end

```

(The character count doesn't include the newline on line 2, which I've included solely for legibility.)

The logic is pretty straightforward. The expression `(i-i%32)/32` is equivalent to `math.floor(i/32)` -- in other words, integer division. Written in C's bitwise operators (which Lua lacks), the logic would look like this:

```
p[i] = (((i >> 5) ^ (i >> 13)) & 1) ? dark : light

```

This solution should produce identical output as the example given in the description.

You can shave off several characters by changing the colors to pure black and white, assuming `-1` can be used to represent the white color:

```
w=256
p={}
for i=0,65535 do p[i+1]=((i-i%32)/32+(i-i%8192)/8192)%2-1 end

```

If I also change the size to be 64x64 (which the description permits), I can bring it down to 65 characters:

```
w=64
p={}
for i=0,4095 do p[i+1]=((i-i%8)/8+(i-i%512)/512)%2-1 end

```

However, the description doesn't seem to have any *objective* limits as to the chessboard's appearance. (Rookie mistake.) Let's go ahead and use the color `0x000000` for the white squares, and `0x000001` for the dark squares. And let's have the chessboard squares be 1x1. I can then bring it down to 48 characters:

```
w=8
p={}
for i=0,63 do p[i+1]=(i+(i-i%8)/8)%2 end

```

Or, if we forgo graphics entirely and stick to ASCII, we can use this 54-character solution and still be legible:

```
for i=1,8 do print(('* * * * *'):sub(1+i%2,8+i%2))end

```
> 0 votes

# Answer
**27-29 letters :-þ** supersmall diagonal but not ascii ..

```
print(("♦♦♦♦♦♦♦♦\n"):rep(5));

```

3D version 35 letters :)

```
print(("◄►◄►◄►◄►◄►◄►◄►\n"):rep(8));

```

extra nice version :)

```
print(("▇   ▇   ▇   ▇\n  ▇   ▇   ▇   ▇\n"):rep(4));

```
> 0 votes

---
Tags: code-golf, graphical-output, lua
---


# Question
Title: Quine with prime sourcecode character distribution constraints
1. Your program should take no input, and no network or other connections.
2. Your program should output it's sourcecode.
3. The sourcecode must consist of **3 types** of characters: Numeric (0-9), Alpha (a-z|A-Z) and symbols !(0-9|a-z|A-Z). Constraints for the distribution of characters is:
    * 3.1. Every neighbouring characters with equal character-type makes a character-group.
    * 3.2. Each character-group **length in bytes** must be a **prime**-number (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, ...)
    * 3.3. The total number of **character-groups** of each character-type must be a **neighbouring (but not equal) fibonacci** sequence number. For example: 3 groups of numbers, 5 groups of alpha, 8 groups of symbols.
    * 3.4. A character-group of one charater-type cannot be adjacent to another character-group of the same character-type, because that will create one bigger group instead.

**Example** valid sourcecode (regarding character distribution, it does however not output it's sourcecode):

```
"."."."aa321'","/hithere' 12345678901,.,.,12345,.,

```

Character distribution in the example: 2 groups of Alpha. 3 group of numeric. 5 groups of other characters. The numbers 2, 3 and 5 are neighbouring numbers in the fibonacci sequence.

This is code-golf, good luck have fun!

# Answer
# PHP, some other languages - 12 bytes

```
22ab,,22,,22

```

PHP will print out the source code if it is not wrapped in some tag.

This is actually the smallest possible answer to the question. The smallest prime number is `2`, and the smallest distinct fibonacci numbers are `1`, `2`, and `3`. `3 + 2 + 1 = 6`. `6 * 2 = 12`

See a run here: http://ideone.com/0NDA8A
> 2 votes

# Answer
# Golfscript, ~~21~~ 15 characters

```
11{'aa.~' }aa.~

```

After removing all NOPs, their images, and the leading `11`, this becomes the quine

```
{`'.~'}.~

```

reading: block(string(dup, eval)); dup; eval.

~~Now to shoot for the stars (20 characters - the minimum for 2-3-5) or even galaxies (12 characters - the absolute minimum)~~ I've taken a short stop at Alpha Centauri B to refuel, now I'm drifting through intergalactic medium. Thanks, Goldbach's conjecture.

Live: http://golfscript.apphb.com/?c=MTF7J2FhLn4nMTE7fWFhLn4K
> 3 votes

# Answer
# Befunge 98 - 16 bytes

```
<@,*+982aa,,kd$"

```

This works only if your interpreter interprets line-wrap as adding a single space. This one works otherwise:

```
<@,*+982aa,,kd "

```

Character groups:

```
<@,*+ 5 chars, symbols
982   3 chars, numbers
aa    2 chars, alpha
,,    2 chars, symbols
kd    2 chars, alpha
$"    2 chars, symbols

```

So the fibonacci numbers are 1 (numbers), 2 (alpha), and 3 (symbols)
> 2 votes

# Answer
## Windows Command Script - 12 bytes (+ free folder bonus)

```
md  12##56##

```

Since every command is echoed by default, it's just a matter of finding the shortest command.
> 2 votes

---
Tags: code-golf, primes, quine, fibonacci
---


title: Find all problems that equal an integer

text:
# Question
Title: Find all problems that equal an integer
In this challenge, your job is to write a program that allows a user to enter an integer. Then, the program must find all the possible ways of multiplying two numbers to get the user's integer.
**Rules:**

* The program should not show any problem more than once.
* The user should be able to enter any integer.
* The program should only show problems that contain 2 numbers.
* The shortest program (in Bytes) wins.
* It does not matter what order the program outputs the problems in.

**Example Output (user enters 20, then the program outputs the problems):**

> > 20
> >
> > 1 * 20
> > 2 * 10
> > 4 * 5

# Answer
> 3 votes
## Perl 6, ~~54~~ ~~52~~ 49 characters

```
my \i=get;i%$_||say $_,"*",i/$_ for 1...^*>i.sqrt

```

Iterates through each integer from 1 to the first number greater than the square root of the input (`* > i.sqrt`), excludes that last number (`...^`), and prints (`say $_,"*",i/$_`) unless the number doesn't divide the input evenly (`i % $_ ||`)

# Answer
> 3 votes
Let's give **VIM** some love (96 chars)

```
let n=input('')|for x in range(1,n/2-1)|for y in range(1,n)|if x*y==n|ec x."*".y|en|endfo|endfo

```

The abbreviations `ec`, `en` and `endfo` stand for `echo`, `endif` and `endfor` respectively.

I was rather disappointed that I couldn't use `fo`; that expands to `fold`.

# Answer
> 1 votes
## python, ~~85~~ ~~79~~ ~~75~~ 73 characters

```
i,j=1,int(raw_input())
while i*i<=j:
    if j%i==0:
        print i,"*",j/i
    i+=1

```

This can probably be improved drastically...

# Answer
> 1 votes
## JavaScript, 64 characters

Algorithm: run for loop till square root of the input number and if `n % i == 0` alert the pair of numbers.

```
n=prompt();for(i=1;i<Math.sqrt(n);i++)if(!(n%i))alert(i+"*"+n/i)

```

# Answer
> 0 votes
## C, 75 71 70 characters

```
n;main(i){scanf("%d",&n);for(;i*i<n;i++)n%i||printf("%d*%d\n",i,n/i);}

```

Relies on the fact that the program is called with 0 arguments so `i` is initialized to `1`. I am currently beating the python solution, so I am quite estatic. :D

# Answer
> 0 votes
## perl 5 82 characters...

```
  my $n=20;
  for(1..sqrt($n)){
    say "$_ * ",$n/$_ if $n%$_ == 0;
  }

```

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


title: Metapoem equinox

text:
# Question
Title: Metapoem equinox
Objective:

* Write one program that outputs sourcecode for another program that outputs words.

General information:

* Any programming language.

Rules:

1. Your programs should not take any input. (from user, filename, network or anything).
2. The generated program sourcecode must not be in the same programming language as the original.
3. The output from the generated program should be exactly every third character from the original sourcecode, starting at character #3 (first character in sourcecode is #1).
4. Sourcecode constraints: **Maximum 1500 characters**
5. Sourcecode constraints for generated program: **Maximum 250 characters**

**Scoring** is based on the output from the generated program, you get points for the following words (any combination of upper/lowercase):

```
me - 2 points
ore - 3 points
freq - 5 points
pager - 7 points
mentor - 11 points
triumph - 13 points
equipage - 17 points
equipment - 19 points
equivalent - 23 points
equilibrium - 29 points
unubiquitous - 31 points
questionnaire - 37 points

```

Each word can be repeated but lose 1 point for each repetition. For example:

* four of `Equilibrium` (in any place) in the output gives: 29+28+27+26 points.

Letters in the output can be used in more than one word, for example:

* `equipager` = `equipage` and `pager` = 17+7 points.

Best score wins. Good luck, have fun!

# Answer
> 2 votes
## Befunge-98, produces zsh script: ~~150 1053 1113~~ 1139 points

The Befunge-98 program (1500)

```
:#q #u!#e!#sa#t7#i6#o*#n*#n*#aj#ib#r9#e*#q:#u:#i:#p:#a:#g:#e:#r:#e:#q3#u+#i,#pc#m+#e,#nf#t+#o,#r4#e8#q*#u,#i6#l+#i:#b,#r4#i8#u*#m,#e,#qb#u+#i:#p:#m:#e:#n:#t,#o4#r8#e*#q,#u,#i4#l8#i*#b,#r,#i4#u8#m*#u,#n,#u4#b8#i*#q,#u,#i4#t8#o*#u,#s,#q4#ua#e*#s-#t,#i2#o+#n,#n,#a5#i+#r,#ec#q+#u,#i4#v8#a*#l,#e9#n5#t*#-,#qb#ua#e*#s,#t4#i8#o*#n,#n #a #i #r #e #q #u #i #p #a #g #e #r #e #q #u #i #p #m #e #n #t #o #r #e #q #u #i #l #i #b #r #i #u #m #e #q #u #i #p #m #e #n #t #o #r #e #q #u #i #l #i #b #r #i #u #m #u #n #u #b #i #q #u #i #t #o #u #s #q #u #e #s #t #i #o #n #n #a #i #r #e #q #u #i #v #a #l #e #n #t #- #q #u #e #s #t #i #o #n #n #a #i #r #e #q #u #i #p #a #g #e #r #e #q #u #i #p #m #e #n #t #o #r #e #q #u #i #l #i #b #r #i #u #m #e #q #u #i #p #m #e #n #t #o #r #e #q #u #i #l #i #b #r #i #u #m #u #n #u #b #i #q #u #i #t #o #u #s #q #u #e #s #t #i #o #n #n #a #i #r #e #q #u #i #v #a #l #e #n #t #- #q #u #e #s #t #i #o #n #n #a #i #r #e #q #u #i #p #a #g #e #r #e #q #u #i #p #m #e #n #t #o #r #e #q #u #i #l #i #b #r #i #u #m #e #q #u #i #p #m #e #n #t #o #r #e #q #u #i #l #i #b #r #i #u #m #u #n #u #b #i #q #u #i #t #o #u #s #q #u #e #s #t #i #o #n #n #a #i #r #e #q #u #i #v #a #l #e #n #t #- #q #u #e #s #t #i #o #n #n #a #i #r #e #q #u #i #p #a #g #e #r #e #q #u #i #p #m #e #n #t #o #r #e #q #u #i #l #i #b #r #i #u #m #e #q #u #i #p #m #e #n #t #o #r #e #q #u #i #l #i #b #r #i #u #m #u #n #u #b #i #q #u #i #t #o #u #s:#q2#u+#e0#sg#t,#i3#o+#n:#n #a3#i9#rb#e*#q*#u #i`#v #a!#l #e1#n+jt@#-

```

produces the zsh shell script (127)

```
for i in n n n n n;echo -n questionnairequipagerequipmentorequilibriumequipmentorequilibriumunubiquitousquestionnairequivalent-

```

which in turn of course outputs (500)

```
questionnairequipagerequipmentorequilibriumequipmentorequilibriumunubiquitousquestionnairequivalent-questionnairequipagerequipmentorequilibriumequipmentorequilibriumunubiquitousquestionnairequivalent-questionnairequipagerequipmentorequilibriumequipmentorequilibriumunubiquitousquestionnairequivalent-questionnairequipagerequipmentorequilibriumequipmentorequilibriumunubiquitousquestionnairequivalent-questionnairequipagerequipmentorequilibriumequipmentorequilibriumunubiquitousquestionnairequivalent-

```

when executed. This is worth **1139** points (assuming my calculations are correct).

### Early version (saved here because it's much easier to try to understand)

The Befunge-98 program

```
:#m #e!#n!#tb#o9#r*#e*#qj#ub#i9#l*#i:#b:#r:#u2#m+#f,#r,#e5#q+#u,#ec#s+#t,#i8#o4#n*#n,#a #r #i #e #q #u #i #p #m #e #n #t #r #i #u:#m2#p+#h0#ug#n,#u3#b+#i:#qf#uf#i*#t`#o5ju @s#_

```

produces the Bourne shell script (including a bunch of trailing spaces)

```
echo mentorequilibrumfrequestionnariequipmentriumphunubiquitous

```

Here is the same program transposed, for easier reading.

```
: !!b9**jb9*:::2+,,5+,c+,84*,              :2+0g,3+:ff*`5 #
########################################################j@_
mentorequilibrumfrequestionnariequipmentriumphunubiquitous

```

# Answer
> 2 votes
## Shellscript and Python - 514 Points

My submission is written in shellscript:

```
echo   print"'h rthtq""u""e""s""t""i""o""n""n""a""i""r""e""q""u""e""s""t""i""o""n""n""a""i""r""e""q""u""e""s""t""i""o""n""n""a""i""r""e""q""u""e""s""t""i""o""n""n""a""i""r""e""q""u""e""s""t""i""o""n""n""a""i""r""e""q""u""e""s""t""i""o""n""n""a""i""r""e""q""u""e""s""t""i""o""n""n""a""i""r""e""q""u""e""s""t""i""o""n""n""a""i""r""e""u""n""u""b""i""q""u""i""t""o""u""s""u""n""u""b""i""q""u""i""t""o""u""s""u""n""u""b""i""q""u""i""t""o""u""s""u""n""u""b""i""q""u""i""t""o""u""s""u""n""u""b""i""q""u""i""t""o""u""s""e""q""u""i""l""i""b""r""i""u""m""e""q""u""i""l""i""b""r""i""u""m""e""q""u""i""l""i""b""r""i""u""m""e""n""t""o""r""e""q""u""i""p""m""e""n""t""o""r""e""q""u""i""p""m""e""n""t""o""r""e""q""u""i""p""m""e""n""t""o""r'"

```

It will output the following python code (249 characters):

```
print'h rthtquestionnairequestionnairequestionnairequestionnairequestionnairequestionnairequestionnairequestionnaireunubiquitousunubiquitousunubiquitousunubiquitousunubiquitousequilibriumequilibriumequilibriumentorequipmentorequipmentorequipmentor'

```

Whose output contains:

```
8 * questionnaire: 37+36+35+34+33+32+31+30
5 * unubiquitous: 31+30+29+28+27
3 * equipment: 19+18+17
4 * mentor: 11+10+9+8
3 * ore: 3+2+1
6 * me: 2+1

```

for a total of 514 Points.

Not very sophisticated, i am sure others can do better :)

# Answer
> 2 votes
## JavaScript & REBEL - 198

Initial program:

```
console.log( "nll(llf  r  e  q  u  e  s  t  i  o  n  n  a  i  r  e  q  u  i  p  a  g  e  r  u  n  u  b  i  q  u  i  t  o  u  s  e  q  u  i  p  m  e  n  t  o  r  e  q  u  i  v  a  l  e  n  t  r  i  u  m  p  h  e  q  u  i  l  i  b  r  i  u  m+.+ +.$0+;/ + +//.+/$>$0")+0 ;

```

Generated program:

```
nll(llf  r  e  q  u  e  s  t  i  o  n  n  a  i  r  e  q  u  i  p  a  g  e  r  u  n  u  b  i  q  u  i  t  o  u  s  e  q  u  i  p  m  e  n  t  o  r  e  q  u  i  v  a  l  e  n  t  r  i  u  m  p  h  e  q  u  i  l  i  b  r  i  u  m+.+ +.$0+;/ + +//.+/$>$0

```

Output:

```
nll(llfrequestionnairequipagerunubiquitousequipmentorequivalentriumphequilibrium+.+ +.$0+;

```

Notes:

Each word is output exactly once, except "me" which is output twice.

You will notice that the generated program is exactly 250 characters long. I didn't notice this until it was written. I consider myself lucky.

# Answer
> 2 votes
# Python that outputs C, 947

```
##q##u##e##s##t##i##o##n##n##a##i##r##e##q##u##i##p##a##g##e##r##e##q##u##i##p##m##e##n##t##o##r##e##q##u##i##v##a##l##e##n##t##r##i##u##m##p##h##u##n##u##b##i##q##u##i##t##o##u##s##q##u##e##s##t##i##o##n##n##a##i##r##e##q##u##i##p##a##g##e##r##e##q##u##i##p##m##e##n##t##o##r##e##q##u##i##v##a##l##e##n##t##r##i##u##m##p##h##u##n##u##b##i##q##u##i##t##o##u##s##q##u##e##s##t##i##o##n##n##a##i##r##e##q##u##i##p##a##g##e##r##e##q##u##i##p##m##e##n##t##o##r##e##q##u##i##v##a##l##e##n##t##r##i##u##m##p##h##u##n##u##b##i##q##u##i##t##o##u##s##q##u##e##s##t##i##o##n##n##a##i##r##e##q##u##i##p##a##g##e##r##e##q##u##i##p##m##e##n##t##o##r##e##q##u##i##v##a##l##e##n##t##r##i##u##m##p##h##u##n##u##b##i##q##u##i##t##o##u##s##q##u##e##s##t##i##o##n##n##a##i##r##e##q##u##i##p##a##g##e##r##e##q##u##i##p##m##e##n##t##o##r##e##q##u##i##v##a##l##e##n##t##r##i##u##m##p##h##u##n##u##b##i##q##u##i##t##o##u##s##q##u##e##s##t##i##o##n##n##a##i##r##e##q##u##i##p##a##g##e##r##e##q##u##i##p##m##e##n##t##o##r##e##q##u##i##v##a##l##e##n##t##r##i##u##m##p##h##u##n##u##b##i##q##u##i##t##o##u##s##q##u##e##s##t##i##o##n##n##a##i##r##e##q##u##i##p##a##g##e##r##e##q##u##i##p##m##e##n##t##o##r##e##q##u##i##v##a##l##e##n##t##r##i##u##m##p##h##u##n##u##b##i##q##u##i##t##o##u##s
print 'main(i,j){for (i=0;i<7;i++) printf("questionnairequipagerequipmentorequivalentriumphunubiquitous");printf("a(jf =i;+pn(utniqpeqpnruanipniiu)rt\"a(jf =i;+pn(utniqpeqpnruanipniiu)rt\"j=+(nppuii)\\)");}'

```

I use the longest words (that give the best score) and overlapping words too (equipage-pager, as for the example). This is how the score is computed:

me= 2+1+0+0+0+0+0=3
ore= 3+2+1+0+0+0+0=6
pager= 7+6+5+4+3+2+1=28
mentor= 11+10+9+8+7+6+5=56
triumph= 13+12+11+10+9+8+7=70
equipage= 17+16+15+14+13+12+11=98
equipment= 19+18+17+16+15+14+13=112
equivalent= 23+22+21+20+19+18+17=140
unubiquitous= 31+30+29+28+27+26+25=196
questionnaire= 37+36+35+34+33+32+31=238

Total is **947**.

Edit: now the generated program should output "exactly every third character from the original sourcecode" :)

# Answer
> 2 votes
## Javascript and Golfscript - 1074 points

Javascript (1500 chars):

```
/*e  q  u  i  l  i  b  r  i  u  m  u  n  u  b  i  q  u  i  t  o  u  s  q  u  e  s  t  i  o  n  n  a  i  r  e  q  u  i  p  a  g  e  r  e  q  u  i  l  i  b  r  i  u  m  u  n  u  b  i  q  u  i  t  o  u  s  q  u  e  s  t  i  o  n  n  a  i  r  e  q  u  i  p  m  e  n  t  o  r  e  q  u  i  l  i  b  r  i  u  m  u  n  u  b  i  q  u  i  t  o  u  s  q  u  e  s  t  i  o  n  n  a  i  r  e  q  u  i  p  a  g  e  r  e  q  u  i  l  i  b  r  i  u  m  u  n  u  b  i  q  u  i  t  o  u  s  q  u  e  s  t  i  o  n  n  a  i  r  e  q  u  i  p  m  e  n  t  o  r  e  q  u  i  l  i  b  r  i  u  m  u  n  u  b  i  q  u  i  t  o  u  s  q  u  e  s  t  i  o  n  n  a  i  r  e  q  u  i  p  a  g  e  r  e  q  u  i  l  i  b  r  i  u  m  u  n  u  b  i  q  u  i  t  o  u  s  q  u  e  s  t  i  o  n  n  a  i  r  e  q  u  i  p  m  e  n  t  o  r  e  q  u  i  l  i  b  r  i  u  m  u  n  u  b  i  q  u  i  t  o  u  s  q  u  e  s  t  i  o  n  n  a  i  r  e  q  u  i  p  a  g  e  r  e  q  u  i  l  i  b  r  i  u  m  u  n  u  b  i  q  u  i  t  o  u  s  q  u  e  s  t  i  o  n  n  a  i  r  e  q  u  i  p  m  e  n  t  o  r  e  q  u  i  l  i  b  r  i  u  m  u  n  u  b  i  q  u  i  t  o  u  s  q  u  e  s  t  i  o  n  n  a  i  r  e  q  u  i  p  a  g  e  r  e  q  u  i  l  i  b  r  i  u  m  u  n  u  b  i  q  u  i  t  o  u  s  q  u  e  s  t  i  o  n  n  a  i  r  e  q  u  i  p  m  e  n  t  o  r*/console.log(  "5{ 2{'equilibriumunubiquitousquestionnairequip'   'ager'}*   'mentor' \\;}*  'cseo 52eibuniiuutniqp ar* eo ; co2biui *o 2u*22  '" );

```

Generated Golfscript (128 chars): Test GolfScript online

```
5{ 2{'equilibriumunubiquitousquestionnairequip'   'ager'}*   'mentor' \;}*  'cseo 52eibuniiuutniqp ar* eo ; co2biui *o 2u*22  '

```

Output (500 chars):

```
equilibriumunubiquitousquestionnairequipagerequilibriumunubiquitousquestionnairequipmentorequilibriumunubiquitousquestionnairequipagerequilibriumunubiquitousquestionnairequipmentorequilibriumunubiquitousquestionnairequipagerequilibriumunubiquitousquestionnairequipmentorequilibriumunubiquitousquestionnairequipagerequilibriumunubiquitousquestionnairequipmentorequilibriumunubiquitousquestionnairequipagerequilibriumunubiquitousquestionnairequipmentorcseo 52eibuniiuutniqp ar* eo ; co2biui *o 2u*22

```

Score:

```
10 * questionnaire (37+36+35+34+33+32+31+30+29+28)    = 325
10 * unubiquitous  (31+30+29+28+27+26+25+24+23+22)    = 265
10 * equilibrium   (29+28+27+26+25+24+23+22+21+20)    = 245
5  * equipage      (17+16+15+14+13)                   = 75
5  * pager         (7+6+5+4+3)                        = 25
5  * equipment     (19+18+17+16+15)                   = 85
5  * mentor        (11+10+9+8+7)                      = 45
4  * ore           (3+2+1)                            = 6
10 * me            (2+1)                              = 3

```

Total: 1074

UPDATE: Managed to gain some points by changing GolfScript loops from 3\*3 to 5\*2.

---
Tags: code-challenge, word-puzzle
---


title: Mutual exclusive equinox

text:
# Question
Title: Mutual exclusive equinox
1. Your sourcecode **must not** contain any of the characters it outputs (case sensitive).
2. Your program **must not** output more than 500 characters/bytes. 1 byte = 1 char. Newline counts as 1 character.
3. Your program should **not** take any input. (from user, filename, network or anything).
4. Your program must output words/phrases worth a total of **minimum 700 points** according to the following score table (case sensitive):

*Score table:*

```
me                        - 2   points
ore                       - 3   points
freq                      - 5   points
pager                     - 7   points
mentor                    - 11  points
triumph                   - 13  points
equipage                  - 17  points
equipment                 - 19  points
equivalent                - 23  points
equilibrium               - 29  points
unubiquitous              - 31  points
questionnaire             - 37  points
Mutüal 3xcLUs1ve_Equino>< - 400 points

```
* 4.1 Each word can be repeated but lose 1 point for each repetition (with exception for the last phrase worth 400 points, you **must not** repeat that in the output). For example:

four of `equilibrium` (in any place) in the output = `29+28+27+26` points.

* 4.2 Letters in the output can be used in more than one word, for example:

`equipager` = `equipage` and `pager` = `17+7` points.

This is code-golf, shortest sourcecode in bytes wins! Good luck, have fun!

# Answer
# Golfscript, 24 characters

```
"QUESTIONNAIRE"{32+}%36*

```

Way too easy.

36 repetitions of "questionnaire" = 36\*13 characters = 468 characters.

36 repetitions of "questionnaire" = 37+36+...1 point = (37+1)(37)/2 points = 703 points.
> 4 votes

# Answer
## JavaScript, 391 chars

Could be golfed further. Port of Jan Dvorak's answer; alerts `"questionnaire"` 36 times (although, hardcoded instead of via a loop). `T` contains the string "true", `F` the string "false" and `O` the string "\[object Object\]". From these (and `(1/0)+[]` = "Infinity"), `R` = "return" and `C` = "constructor" are constructed. From this, we create a function `$` that does `alert("QUESTIONNAIRE"["toLowerCase"]())` and invoke it 36 times.

```
T=!![]+[]
F=![]+[]
O={}+[]
R=T[1]+T[3]+T[0]+T[2]+T[1]+(0[[]]+[])[1]
C=O[5]+O[1]+(0[[]]+[])[1]+F[3]+T[0]+T[1]+T[2]+O[5]+T[0]+O[1]+T[1]
$=0[C][C](_[F[1]+F[2]+T[3]+T[1]+T[0]]+'("QUESTIONNAIRE"[T[0]+O[1]+"L"+O[1]+"w"+T[3]+T[1]+"C"+F[1]+F[3]+F[4]]())')
$();$();$();$();$();$()
$();$();$();$();$();$()
$();$();$();$();$();$()
$();$();$();$();$();$()
$();$();$();$();$();$()
$();$();$();$();$();$()

```
> 3 votes

# Answer
## Perl 6 (33 chars)

```
EVAL "SAY 'QUESTIONNAIRE'x 35".lc

```

13 chars * 35 repetitions = 455 chars total output
\+ == 700 points; (3..37).elems = 35 repetitions.
> 2 votes

# Answer
## JavaScript (88342)

http://pastebin.com/6UNTNXeT

alerts **Mutüal 3xcLUs1ve\_Equino\>\<** once + **unubiquitous** 12 times

Score: 706
> 1 votes

# Answer
# C64 BASIC, 64 PETSCII chars

Should output 13 times the string "questionnaireunubiquitousequilibrium", with a score of:

equilibrium = 29+28+27+26+25+24+23+22+21+20+19+18+17=299
unubiquitous = 31+30+29+28+27+26+25+24+23+22+21+20+19=325
questionnaire = 37+36+35+34+33+32+31+30+29+28+27+26+25=403

**1027**.

(output is **481** chars long)
> 1 votes

---
Tags: code-golf, word-puzzle
---


title: Hello, new world! again

text:
# Question
Title: Hello, new world! again
Objective:

> This code-golf is about creating 2 different sourcecodes that both outputs exactly: `Hello, new world! again.` without linefeed, and when combining the two sourcecodes into one sourcecode it should still output exactly: `Hello, new world! again.`

Rules:

1. Your programs should take no input (from user, filename, network or anything).
2. You can choose any combination of programming languages, from one language for all three sourcecodes to three different languages.
3. The combination of the two sourcecodes to create the third is done by putting alternating characters from both from start to end and fill up the third sourcecode from start to end.
4. You must choose 10 different characters that both sourcecodes may use (case sensitive). All other characters is mutual exclusive between the two sourcecodes. Characters may be re-used without restriction. Exactly all 10 characters choosen must be used in both sourcecodes atleast once.

Clarification example on sourcecode combination:

```
Javascript          sourcecode: console.log("Hello, new world! again.");
GolfScript          sourcecode: 'Hello, new world! again.'
Combined (unknown?) sourcecode: c'oHneslolloe,. lnoegw( "wHoerllldo!,  angeawi nw.o'rld! again.");

```

The above example does however violate rule #4 as more than 10 characters is "shared" in both sourcecodes. And the combined sourcecode does not output: `Hello, new world! again.`

Be sure to declare what programming languages is used (all three) and what 10 characters that is allowed in both sourcecodes.

This is code-golf, least bytes in combined sourcecode wins! Good luck, have fun!

# Answer
## Python + dc (~~160,141,137,116~~ 81+27=108)

program1: (python)

```
'yyyyyyyyyyyyyyyyyyyyyyyyyy';exec'PRINT\'%sELLO, NEW WORLD! AGAIN.\''.lower()%'H'

```

program2: (dc)

```
[Hello, new world! again.]p

```

combined: (python)

```
'[yHyeylylyoy,y ynyeywy ywyoyrylydy!y yaygyayiyny.y]yp';exec'PRINT\'%sELLO, NEW WORLD! AGAIN.\''.lower()%'H'

```

Common characters (including space): `! ,.elorwH`

The parts `program1` and `program2` are quite simple to understand, where the first has some case switches to reduce the common characters.

As `program1` starts with a quotation `'`, in the combined code all the gibberish walks into a long string, becoming irrelevant for the interpreter. The string `'yy...y'` is of the same length as `program2`, so after its closing `'` the relevant code of `program1` is appended to the combined program.
> 2 votes

# Answer
## C99 + sh + C11, ~~165 162 146~~ 145 combined chars

Edit: using @flonk's trick I managed to put the "comment" in C (making use of C11's `u""` Unicode literals).

Common characters are: `acehinortu`.

**hello.c** (106):

```
*a="\2+++++++++++++++++++++++++++++++++";i;main(){for(;i<24;)putchar("Lipps0$ri{${svph%$ekemr2"[i++]+~3);}

```

**hello.sh** (39):

```
true
echo -n 'Hello, new world! again.'

```

**hello-combined.c** (145):

```
*tar=u"e\
2e+c+h+o+ +-+n+ +'+H+e+l+l+o+,+ +n+e+w+ +w+o+r+l+d+!+ +a+g+a+i+n+.+'";i;main(){for(;i<24;)putchar("Lipps0$ri{${svph%$ekemr2"[i++]+~3);}

```

---

Here are some utilities that might prove useful for other participants.

**combine.c**:

```
#include <stdio.h>
int main(int argc, char *argv[]) {
  FILE *f1 = fopen(argv[1], "r"), *f2 = fopen(argv[2], "r");
  while (!feof(f1) || !feof(f2)) {
    int c1 = fgetc(f1), c2 = fgetc(f2);
    if (c1 != EOF) putchar(c1);
    if (c2 != EOF) putchar(c2);
  }
  return 0;
}

```

**char-check.{ba,z}sh**:

```
comm -12 <(grep -o . "$1" | sort | uniq) \
         <(grep -o . "$2" | sort | uniq) | tr -d '\n'

```

---

Here's a variation that unfortunately ended up (considerably) longer, but it's pretty cool in how it works. (I didn't bother getting the intersection between the sets of characters down to 10, since it ended up longer anyway.)

**hello.c** (113):

```
*a="\5Lipps0$ri{${svph%$ekemr2+++++++++++",*b=&a,c=6;i;main(){char*p=*b;for(i=c/8;p[i]-50;)putchar(p[i+=c/4]-4);}

```

**hello.sh** (51):

```
true
echo -n 'Hello, new world! again.' #     tr  1

```

**hello-combined.c** (164):

```
*tar=u"e\
5eLcihpop s-0n$ r'iH{e$l{lsov,p hn%e$we kweomrrl2d+!+ +a+g+a+i+n+.+'+ +#" , * b = &tar, c =16;i;main(){char*p=*b;for(i=c/8;p[i]-50;)putchar(p[i+=c/4]-4);}

```

This one is fun, because it doesn't just "comment out" a bunch of characters, but actually stores the characters it prints inside the string literal and accounts for the extra characters in the for-loop of the generated program.
> 9 votes

# Answer
# Brainfuck + C (196+77)

Not a very golfy answer, but I just think it is fun

Brainfuck:

```
++++++++++[>+++++++>++++>++++++++++>+++<<<<-]>++.>>+.+++++++..+++.<++++.>>++.<-.---------.++++++++++++++++++.>.<.--------.+++.------.--------.>+.-.<---.++++++.------.++++++++.+++++.<++.printfHelo

```

C

```
main(){printf("Hello");putchar(44);printf(" new world! again");putchar(46);}

```

Combined (Also in brainfuck):

```
+m+a+i+n+(+)+{+p+r+i[n>t+f+(+"+H+e+l+l>o+"+)+;+p>u+t+c+h+a+r+(+4+4+)+;>p+r+i+n<t<f<(<"- ]n>e+w+ .w>o>r+l.d+!+ +a+g+a+i+n.".)+;+p+u.t<c+h+a+r+(.4>6>)+;+}.
<-.---------.++++++++++++++++++.>.<.--------.+++.------.--------.>+.-.<---.++++++.------.++++++++.+++++.<++.printfHelo

```

All the characters from the C code are considered as comments in brainfuck

The common characters are `printfHelo`, appended at the end of the brainfuck code as comments
> 5 votes

# Answer
## Befunge + sh + Befunge, 111 chars

Common characters are: `!,-Hehilor`

**hello.bef** (78):

```
vHelo----------------------------
<v"Lipps0$ri{${svph%$ekemr2"
_>4-:,b4*2+-!#@

```

**hello.sh** (33):

```
echo -n Hello, new world\! again.

```

**hello-combined.bef** (111):

```
veHcehloo ---n- -H-e-l-l-o-,- -n-e-w- -w-o-r-l-d-\-!- -a-g-a-i-n-.
<v"Lipps0$ri{${svph%$ekemr2"
_>4-:,b4*2+-!#@

```
> 3 votes

---
Tags: code-golf, hello-world
---


# Question
Title: Create a chain of spam generators in as many languages as possible
The goal of a challenge is to write solutions in as many languages as possible. Show off your programming multilingualism!

In this challenge, you will create a program that will generate spam messages, given an input seed-text. For example, given the input

```
[Thank you/Wow/Great], this [blog/post/writing] [gives/provides/delivers] [great/excellent/wonderful/superior] [content/information/data]. You [may/could] [find/get/retrieve] [similar/related] [content/information/data] at spammysite.com.

```

A possible output could be

```
Thank you, this writing delivers excellent data. You may find similar content at spammysite.com.

```

(idea from https://security.stackexchange.com/q/37436/29804)

There's a catch, though! You will also have to output a program in a *different* language. This program, when run, will also output the spam text and a program in a different language, which will also output the spam text and a program in a different language...

Your score will be `character count / (number of languages ^ 2)`.

For example, I could have a Ruby program. It would take the input seed-text as input, and output the random spam text and a Python program.

Running this Python program (with no input), it would output another random spam text and a Perl program.

Running this Perl program (no input), it would output another random spam text.

In this example, my score would be the length of the original Ruby program divided by 9 (I have 3 languages, and 3 ^ 2 is 9).

Other miscellaneous things:

* You must use at least 2 different programming languages.
* Please list each program that is output. This way if someone doesn't have all of the languages, they can still see their sources. You may use this short example text: `[Please/Kindly] [visit/see] my [site/blog].`, or you may just use a placeholder (like `{insert text here}`).
* You may assume that there will be no non-alphanumeric characters except `[]/.,`, to simplify some things.
* Different versions of languages do not count as different languages (ex. Python 2 == Python 3).
* It must be fully random, i.e. not predictable and outputting a different combination every run. It must also be able to output every combination in an arbitrary amount of runs.
* Since this is as well as , the shortest overall score (`charcount / (langs ^ 2)`) will win.

# Answer
# PHP 5.5 -\> Ruby 2.0 -\> Python 2.7 -\> Lua -\> C# -\> Java -\> PdfTeX -\> GolfScript 855 / 8^2 = 13.359375

The main ideas were:

1. Instead of actually creating the logic to create the n+1th language in all programming languages do this only one time, and only use the basic random and stdout writing facilities of each programming language
2. To shorten the template generator, just compress it with zLib. Make this generator the second language
3. Use PHP as the first language, as it has built-in zLib decompressor

So the initial code is:

```
<?php $x=file_get_contents("php://stdin");echo preg_replace_callback("/\[(.*?)\]/",function($m){$r=explode("/",$m[1]);return $r[array_rand($r)];},$x).gzuncompress("BINARY_DATA")."__END__\n".$x;

```

Where `BINARY_DATA` is the gzcompressed version of the template generator (e.g. the result of the php code, which is the ruby version)

The complete initial code in base64 (should be 855 bytes after decoding):

```
PD9waHAgJHg9ZmlsZV9nZXRfY29udGVudHMoInBocDovL3N0ZGluIik7ZWNobyBw
cmVnX3JlcGxhY2VfY2FsbGJhY2soIi9cWyguKj8pXF0vIixmdW5jdGlvbigkbSl7
JHI9ZXhwbG9kZSgiLyIsJG1bMV0pO3JldHVybiAkclthcnJheV9yYW5kKCRyKV07
fSwkeCkuZ3p1bmNvbXByZXNzKCJ42o2UwXKbMBCG7zyFZj0doElV55BLiNJmmump
7aHpTA+Yg4xErA6SGCQSZ4jevZIBx3biTHywzO6y/7+fYRm5uf5zjVtOGS5XWjbY
NLWwSZzHKVx4OTa06Z/oE51iRZw6XFzV1FquXiQ/+2TEMKflKsSbViiLfFx4OTbK
puYuajpr0OUlBDmIoqrVErVUMX8I2ejWXCIvL0oejVfm0USznk0y4Fx4YWaxsUx3
Fj+0wvJkKE9mPcVCmYaX1qUpuI+wUODlgvzwjeI4XHg5NtSu8CBnOGeJNthcbsmT
NN0ToWSnHbatx1DEp3Hv/GyZ0KMyzXfaJWen4Z6aqzu7cmmRZvseknQ8c0JyT2FZ
ixKVNTUGUdRPAWOp9ce9Fgz9pEIlqc/dPhrLJf49UGqJ4g9oL1x4OTak2a79Jfl0
JXs5eiHk7AuM5d+0Mrrm+O/G/8zXVKI19hlcXAYXICqUtPgXX9sb7V15OJdzfJ72
R3uYlah2ezheG97DyTKXxQk4D1wiW+YUs64pJiRceGFm9fohFA+THM19hTd5ycDr
1nrId3mBaHtnArx/9J7izop6n99h+N0Iw4M3/JELeAlwATsIlUf4vdbUHhA8bLHP
L7R4P8FtXHhhZloNI6wJUMjeGGS0fIFgMX5EpTp5Pp9fTYGGVZ0SlW4l4/eCWn42
n8/R1qqb6oJLNLmcgpXwbtdkjU1XXHg5Ntn0RlxcvULQW17AYnsj4xWafuvG+lEc
6mf9dnD3IVQHvgjgDQxceDAwLyi8audAq3e+MR3g+O7gXHgwMJ4fxgPMR1TZ8zLc
yiDIw17YJFx4OTZPEPuBXFwMG4FiZ2GEJUJceDAw+dHiEB1cXIx1x4zAdoTlI98U
uciNR1QQ4ndQ5HdeFFZt9B9+DwFHIikuIl9fRU5EX19cbiIuJHg7

```

Let's go through all of the languages with the test input string `[Thank you/Wow/Great], this is [awesome/wonderful].`

# PHP

```
$ cat ti2 | php a.php
Great, this is wonderful.
d=DATA.read.chomp.split('[').map{|a|a.split(']')}.flatten.map{|a|a.split('/')}
d.each{|a|print a.sample}
puts <<"DATA"

from random import choice
import sys
#{d.map{|a|"sys.stdout.write(choice(#{a.inspect}))"}*"\n"}
print
print '''math.randomseed(os.time())
#{d.map{|a|"a=#{a.inspect.tr('[]','{}')};io.write(a[math.random(1,#{a.length})]);"}*"\n"}
print()
print([==[
public class a {
public static void Main() {
System.Random r=new System.Random();
#{d.map{|a|b=->m{m.length==1?"System.Console.Write(#{m.first.inspect});":"if (r.NextDouble()<0.5){System.Console.Write(#{m.shift.inspect});}else{"+b[m]+"};"};b[a.dup]}*"\n"}
System.Console.WriteLine();
System.Console.WriteLine(@"class a {
public static void main(String[] args) {
java.util.Random r=new java.util.Random();
#{d.map{|a|b=->m{m.length==1?"System.out.print(\"#{m.first.inspect}\");":"if (r.nextFloat()<0.5){System.out.print(\"#{m.shift.inspect}\");}else{"+b[m]+"};"};b[a.dup]}*"\n"}
System.out.println();
#{x="a";d.map{|a|b=->m{m.length==1?m.first: "\\\\\\\\ifnum500>\\\\\\\\pdfuniformdeviate1000 #{m.shift}\\\\\\\\else "+b[m]+"\\\\\\\\fi"};x=x.succ;a.length>1?"System.out.println(\"\"\\\\\\\\def \\\\\\\\opt#{x} {#{b[a.dup]}}%\"\");": ""}*"\n"}
System.out.println(""#{x="a";d.map{|a|x=x.succ;a.length>1?"\\\\\\\\opt#{x}{}": a.first}*""}"");
System.out.println();
System.out.println(""#{d.map{|a|a.length>1? "[#{a.map{|b|"'#{b}'"}*""}]#{a.length}rand=" : "'#{a.first}'"}*""}"");
System.out.println(""\\\\\\\\bye"");
}
}");
}
}
]==]);
'''
DATA
__END__
[Thank you/Wow/Great], this is [awesome/wonderful].

```

# Ruby

```
$ ruby a.rb
Great, this is awesome.
from random import choice
import sys
sys.stdout.write(choice(["Thank you", "Wow", "Great"]))
sys.stdout.write(choice([", this is "]))
sys.stdout.write(choice(["awesome", "wonderful"]))
sys.stdout.write(choice(["."]))
print
print '''math.randomseed(os.time())
a={"Thank you", "Wow", "Great"};io.write(a[math.random(1,3)]);
a={", this is "};io.write(a[math.random(1,1)]);
a={"awesome", "wonderful"};io.write(a[math.random(1,2)]);
a={"."};io.write(a[math.random(1,1)]);
print()
print([==[
public class a {
public static void Main() {
System.Random r=new System.Random();
if (r.NextDouble()<0.5){System.Console.Write("Thank you");}else{if (r.NextDouble()<0.5){System.Console.Write("Wow");}else{System.Console.Write("Great");};};
System.Console.Write(", this is ");
if (r.NextDouble()<0.5){System.Console.Write("awesome");}else{System.Console.Write("wonderful");};
System.Console.Write(".");
System.Console.WriteLine();
System.Console.WriteLine(@"class a {
public static void main(String[] args) {
java.util.Random r=new java.util.Random();
if (r.nextFloat()<0.5){System.out.print(""Thank you"");}else{if (r.nextFloat()<0.5){System.out.print(""Wow"");}else{System.out.print(""Great"");};};
System.out.print("", this is "");
if (r.nextFloat()<0.5){System.out.print(""awesome"");}else{System.out.print(""wonderful"");};
System.out.print(""."");
System.out.println();
System.out.println(""\\\\def \\\\optb {\\\\ifnum500>\\\\pdfuniformdeviate1000 Thank you\\\\else \\\\ifnum500>\\\\pdfuniformdeviate1000 Wow\\\\else Great\\\\fi\\\\fi}%"");

System.out.println(""\\\\def \\\\optd {\\\\ifnum500>\\\\pdfuniformdeviate1000 awesome\\\\else wonderful\\\\fi}%"");

System.out.println(""\\\\optb{}, this is \\\\optd{}."");
System.out.println();
System.out.println(""['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'"");
System.out.println(""\\\\bye"");
}
}");
}
}
]==]);
'''

```

# Python

```
$ python a.py
Great, this is wonderful.
math.randomseed(os.time())
a={"Thank you", "Wow", "Great"};io.write(a[math.random(1,3)]);
a={", this is "};io.write(a[math.random(1,1)]);
a={"awesome", "wonderful"};io.write(a[math.random(1,2)]);
a={"."};io.write(a[math.random(1,1)]);
print()
print([==[
public class a {
public static void Main() {
System.Random r=new System.Random();
if (r.NextDouble()<0.5){System.Console.Write("Thank you");}else{if (r.NextDouble()<0.5){System.Console.Write("Wow");}else{System.Console.Write("Great");};};
System.Console.Write(", this is ");
if (r.NextDouble()<0.5){System.Console.Write("awesome");}else{System.Console.Write("wonderful");};
System.Console.Write(".");
System.Console.WriteLine();
System.Console.WriteLine(@"class a {
public static void main(String[] args) {
java.util.Random r=new java.util.Random();
if (r.nextFloat()<0.5){System.out.print(""Thank you"");}else{if (r.nextFloat()<0.5){System.out.print(""Wow"");}else{System.out.print(""Great"");};};
System.out.print("", this is "");
if (r.nextFloat()<0.5){System.out.print(""awesome"");}else{System.out.print(""wonderful"");};
System.out.print(""."");
System.out.println();
System.out.println(""\\def \\optb {\\ifnum500>\\pdfuniformdeviate1000 Thank you\\else \\ifnum500>\\pdfuniformdeviate1000 Wow\\else Great\\fi\\fi}%"");

System.out.println(""\\def \\optd {\\ifnum500>\\pdfuniformdeviate1000 awesome\\else wonderful\\fi}%"");

System.out.println(""\\optb{}, this is \\optd{}."");
System.out.println();
System.out.println(""['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'"");
System.out.println(""\\bye"");
}
}");
}
}
]==]);

```

# Lua

```
$ lua a.lua
Great, this is wonderful.
public class a {
public static void Main() {
System.Random r=new System.Random();
if (r.NextDouble()<0.5){System.Console.Write("Thank you");}else{if (r.NextDouble()<0.5){System.Console.Write("Wow");}else{System.Console.Write("Great");};};
System.Console.Write(", this is ");
if (r.NextDouble()<0.5){System.Console.Write("awesome");}else{System.Console.Write("wonderful");};
System.Console.Write(".");
System.Console.WriteLine();
System.Console.WriteLine(@"class a {
public static void main(String[] args) {
java.util.Random r=new java.util.Random();
if (r.nextFloat()<0.5){System.out.print(""Thank you"");}else{if (r.nextFloat()<0.5){System.out.print(""Wow"");}else{System.out.print(""Great"");};};
System.out.print("", this is "");
if (r.nextFloat()<0.5){System.out.print(""awesome"");}else{System.out.print(""wonderful"");};
System.out.print(""."");
System.out.println();
System.out.println(""\\def \\optb {\\ifnum500>\\pdfuniformdeviate1000 Thank you\\else \\ifnum500>\\pdfuniformdeviate1000 Wow\\else Great\\fi\\fi}%"");

System.out.println(""\\def \\optd {\\ifnum500>\\pdfuniformdeviate1000 awesome\\else wonderful\\fi}%"");

System.out.println(""\\optb{}, this is \\optd{}."");
System.out.println();
System.out.println(""['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'"");
System.out.println(""\\bye"");
}
}");
}
}

```

# C#

```
$ mcs a.cs
$ mono a.exe
Thank you, this is wonderful.
class a {
public static void main(String[] args) {
java.util.Random r=new java.util.Random();
if (r.nextFloat()<0.5){System.out.print("Thank you");}else{if (r.nextFloat()<0.5){System.out.print("Wow");}else{System.out.print("Great");};};
System.out.print(", this is ");
if (r.nextFloat()<0.5){System.out.print("awesome");}else{System.out.print("wonderful");};
System.out.print(".");
System.out.println();
System.out.println("\\def \\optb {\\ifnum500>\\pdfuniformdeviate1000 Thank you\\else \\ifnum500>\\pdfuniformdeviate1000 Wow\\else Great\\fi\\fi}%");

System.out.println("\\def \\optd {\\ifnum500>\\pdfuniformdeviate1000 awesome\\else wonderful\\fi}%");

System.out.println("\\optb{}, this is \\optd{}.");
System.out.println();
System.out.println("['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'");
System.out.println("\\bye");
}
}

```

# Java

```
$ javac a.java
$ java a
Wow, this is wonderful.
\def \optb {\ifnum500>\pdfuniformdeviate1000 Thank you\else \ifnum500>\pdfuniformdeviate1000 Wow\else Great\fi\fi}%
\def \optd {\ifnum500>\pdfuniformdeviate1000 awesome\else wonderful\fi}%
\optb{}, this is \optd{}.

['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'
\bye

```

# PdfTeX

(the code will be inside a.pdf instead of the stdout. I hope this is still okay)

```
$ pdftex a.tex
This is pdfTeX, Version 3.1415926-2.4-1.40.13 (TeX Live 2012)
 restricted \write18 enabled.
entering extended mode
(./a.tex [1{/usr/local/texlive/2012/texmf-var/fonts/map/pdftex/updmap/pdftex.ma
p}] )</usr/local/texlive/2012/texmf-dist/fonts/type1/public/amsfonts/cm/cmr10.p
fb>
Output written on a.pdf (1 page, 15967 bytes).
Transcript written on a.log.
$ open a.pdf

```

Result:

In text:

```
Great, this is wonderful.
['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'

```

# Golfscript

```
$ ruby golfscript.rb a.gs
Wow, this is awesome.

```

# Notes

1. It seems PHP is quite forgiving with binary data in string literals, except for hex codes AF and 96. Don't ask why.
2. I could've probably added perl and C++11 code as well easily (as they both support raw string literals), but 8 is a more round number than 10 :)
3. The distribution of values is not uniform, as the first element comes more often than later ones. According to comments this should be okay.
4. The initial code was actually generated using the following PHP 5.5 code. `orig.rb` is actually the same as the Ruby code without the footer (`__END__` and the appended data afterwards)

`generator.php`:

```
<?php
$d=file_get_contents('orig.rb');
$dc = gzcompress($d,9);
echo '<?php $x=file_get_contents("php://stdin");echo preg_replace_callback("/\\[(.*?)\\]/",function($m){$r=explode("/",$m[1]);return $r[array_rand($r)];},$x)';
?><?php
echo ".gzuncompress(\"";
for ($i=0;$i<strlen($dc);$i++) {
  switch($dc[$i]) {
  case '"':
    echo "\\\"";break;
  case "\n":
    echo "\\n";break;
  case '\\':
    echo "\\\\";break;
  case "\x00":case "\xaf":case "\x96":
    echo sprintf("\\x%02x",ord($dc[$i]));
    break;
  default:
    echo $dc[$i];
  }
}
echo "\").\"__END__\\n\".\$x;";

```

(you can potentially use this code to zLib encompress PHP solutions for other challenges)
> 5 votes

# Answer
# Ruby 1.9 -\> Perl 5 -\> Python 2, 227/9 = 25.22222...

```
$><<(g=gets).gsub(/\[(.*?)\]/){$1.split(?/).sample}+"say'#{g.chop}'=~s|\\[(.*?)\\]|@a=split'/',$1;$a[rand@a]|reg;say'import re,random;print re.sub(\"\\[(.*?)\\]\",lambda m:random.choice(m.group(1).split(\"/\")),\"#{g.chop}\")'"

```

Output for `[Please/Kindly] [visit/see] my [site/blog].`:

```
Please see my site.
say'[Please/Kindly] [visit/see] my [site/blog].'=~s|\[(.*?)\]|@a=split'/',$1;$a[rand@a]|reg;say'import re,random;print re.sub("\[(.*?)\]",lambda m:random.choice(m.group(1).split("/")),"[Please/Kindly] [visit/see] my [site/blog].")'

```

The Perl program (my first ever! :-P) outputs:

```
Kindly see my blog.
import re,random;print re.sub("\[(.*?)\]",lambda m:random.choice(m.group(1).split("/")),"[Please/Kindly] [visit/see] my [site/blog].")

```

The Python program outputs:

```
Kindly visit my site.

```
> 4 votes

---
Tags: code-golf, rosetta-stone
---