text:
Try and make a completely fake reboot!
This challenge is simple.  Write code that shows what looks exactly like a complete reboot of the computer. It must not show anything on-screen that shows it is not a full reboot and should end at the log-in screen you would get after rebooting.
Rules

You can choose any OS you like to imitate. For example you can reboot into Linux from Windows, Mac from Linux, or any other combination you choose.
The code should display the full reboot full-screen with no signs that it isn't real.
This is a popularity contest so the cooler it looks, the better it is.
The code must be completely harmless, perform no actual rebooting, and be easy to quit at any point.
If you need to use external images to make the reboot look more realistic, then your code should automatically grab them from the web.
Your code should be self-contained, only relying on standard freely available libraries or tools, and must be easily executable by reading the instructions you provide.

As it is a popularity contest, I will award the win to the answer with the highest number of votes on June 1, 2014.

Following a request to narrow the question, here is an additional rule,
the system should imitate any version of Windows or the Mint, Ubuntu, Debian, Fedora, Archlinux or Mageia distributions of Linux or OS X. For extra coolness, you should shut down in one and open in the other.
Interested people may want to look at Pitch dark (Earth Hour remembrance) where a number of ways are suggested for using the full screen even when starting in an xterm.

As it stands, this question is too broad. By not restricting the system which should be faked it runs into (at least - this list may not be exhaustive) problems:  a) with old ROM-based systems which reboot instantly, and can be faked by displaying one image; b) with determining whether or not a fake meets the acceptance criteria when e.g. the computer I'm running it on is multi-head and the faked OS didn't support multi-head (or any heads at all).

@PeterTaylor I was hoping that answers of type a) would just get low votes and as it is a popularity contest that would be OK. If you could help me refine it to handle point b) I would be very grateful.

The obvious solution to problem b) is to narrow the question by saying that your solution only needs to work under the system it imitates, and by restricting the systems which can be imitated. But even then many attempts are doomed to failure by the variety of BIOSes available for IBM-compatible machines.

@PeterTaylor Thanks. I have greatly narrowed the scope. How is it now?

Gah, I almost had a perfect solution for pure ArchLinux (no boot splash, just kernel messages and BIOS). I must say, I never understood the point of wasting CPU cycles at boot just to display some pretty graphics.

@semi-extrinsic Added archlinux. I look forward to seeing it!

Could the rules be modified to also include OSX as a potential OS candidate?

@SztupY Of course. Added.

crap... windows with grabbing bootscreen and similar  from system files is goin to be a pain in the butt (to catch those with switched bootscreen)

zsh + coreutils + unclutter + amixer + xterm (Arch Linux)
I took the answer by @TheDoctor and ran with it. This version has many improvements, and is 99% convincing to an experienced user (me) on my Arch Linux system. I use Zsh since it has good array and floating-point number support.
Dependencies: feh, unclutter, amixer, zsh, xterm
Improvements:
1) Use the number printed in the first column by dmesg, which is the time since boot, (e.g. [    0.000000] ) to determine the time to sleep. Without this it looks very unrealistic on my machine. These times are parsed before the loop (in an early call to sleep) since parsing inside the loop is too slow.
2) Don't print lines where time since boot is larger than 16 seconds. This specific number is machine-dependent, but the point is to avoid printing later dmesg-stuff that comes from inserting/removing usb sticks, etc. and is unrelated to booting.
3) Do all this in a fullscreen terminal window with black background and white text. Kudos to Mechanical Snail for this trick used in: Make a PNG image with "Hello World!" with programming APIs, in the shortest code possible
4) Mute the audio on shutdown, restore volume when script finishes.
5) Hide the mouse cursor, restore when script finishes.
6) Show BIOS and Syslinux splash screens.
Run with: xterm -fu -fg white -bg black -e '/usr/bin/zsh fake-reboot.sh'
Code:
#!/usr/bin/zsh
# Remove (undisplay) the mouse pointer
unclutter -idle 0 -jitter 255 &
# Since there is no easily-accessible (i.e. without being root) shutdown log, we
# fake these messages.
echo "The system is going down for maintenance NOW."
sleep 2.0
echo "[21656.404742] systemd[1]: Shutting down."
echo "[21656.404742] systemd[1]: Stopping Session 1 of user `id -u -n`."
echo "[21656.404742] systemd[1]: Stopped Session 1 of user `id -u -n`."
echo "[21656.404742] systemd[1]: Stopping Sound Card."
# For added effect, store volume and then mute sound
volume=`amixer -- sget Master | awk -F'[][]' 'END{print $2}'`
amixer -- sset Master 0% &> /dev/null
echo "[21656.404742] systemd[1]: Stopped target Sound Card."
sleep 0.5
echo "[21656.919792] systemd[1]: Stopping system-systemd\x2dfsck.slice."
echo "[21656.919792] systemd[1]: Removed slice system-systemd\x2dfsck.slice."
echo "[21656.919792] systemd[1]: Stopping system-netctl\x2difplugd.slice."
echo "[21656.919793] systemd[1]: Removed slice system-netctl\x2difplugd.slice."
echo "[21656.919793] systemd[1]: Stopping User Manager for UID `id -u`..."
sleep 0.7
echo "[21657.624741] systemd[1]: Stopping Graphical Interface."
echo "[21657.624742] systemd[1]: Stopped target Graphical Interface."
echo "[21657.624745] systemd[1]: Stopping Multi-User System."
sleep 0.9
echo "[21658.606561] systemd[1]: Stopped target Multi-User System."
echo "[21658.606562] systemd[1]: Stopping Paths."
echo "[21658.606562] systemd[1]: Stopped D-Bus System Message Bus."
echo "[21658.606562] systemd[1]: Stopped target Paths."
echo "[21658.606568] systemd[1]: Stopping Timers."
echo "[21658.606568] systemd[1]: Stopped target Timers."
echo "[21658.606568] systemd[1]: Stopping Sockets."
echo "[21658.606568] systemd[1]: Stopped target Sockets."
echo "[21658.606568] systemd[1]: Starting Shutdown."
echo "[21658.606571] systemd[1]: Reached target Shutdown."
echo "[21658.606571] systemd[1]: Starting Exit the Session..."
echo "[21658.606571] systemd[1]: Received SIGRTMIN+26 from PID 10988 (kill)."
echo "[21658.606571] systemd[1]: Deactivated swap."
sleep 0.4
echo "[21659.001741] systemd[1]: Starting Unmount All Filesystems."
echo "[21659.001742] systemd[1]: Unmounted /home."
echo "[21659.001742] systemd[1]: Reached target Unmount All Filesystems."
echo "[21659.001742] systemd[1]: Stopping Remount Root and Kernel File Systems..."
echo "[21659.001742] systemd[1]: Stopped Remount Root and Kernel File Systems."
echo "[21659.001743] systemd[1]: Reached target Shutdown."
echo "[21659.001743] systemd[1]: Starting Final Step."
echo "[21659.001743] systemd[1]: Reached target Final Step."
echo "[21659.001754] systemd[1]: Shutting down."
sleep 0.3
echo "[21659.304341] systemd-journal[250]: Journal stopped"
sleep 0.2
echo "System halted."
sleep 2
clear
sleep 1
# Get the BIOS splash screen and display it
wget http://pvv.ntnu.no/~asmunder/bios.jpg  &> /dev/null
feh -Z -x -F -N --force-aliasing bios.jpg &
pid=$! # Store PID of Feh, so we can kill it later
# While showing the BIOS splash, use the time to parse dmesg output into arrays
tim=`dmesg | awk '{print $2}' | sed 's/]//' | grep "[0-9][0-9][0-9][0-9][0-9]"`
tim=($=tim)
dmsg=("${(@f)$(dmesg)}")
sleep 2.5
kill $pid
sleep 0.5
# Get the Syslinux splash and display it
wget http://pvv.ntnu.no/~asmunder/syslinux.png  &> /dev/null
feh -Z -x -F -N --force-aliasing syslinux.png &
pid=$!
sleep 1.3
kill $pid
# Loop through the arrays we created. Calculate the time we have to wait before
# displaying this line. If the wait time is less than 0.1 sec, we skip waiting.
T1=0.0
T2=0.0
n=0
for d in $dmsg; do
  T1=$T2
  T2=${tim[$n]}
  ((dT = $T2-$T1))
  if (( $dT > 0.1));then
    sleep $dT
  fi
  echo $d
  if (( $T2 > 16.0 )); then
    break
  fi
  ((n=$n+1))
done
sleep 1
clear
# It's normally agetty that parses /etc/issue and handles escape codes in a
# special way. Thus we skip the first line of /etc/issue and do that manually.
echo "Arch Linux "`uname -r`" (tty1)"
tail -n +2 /etc/issue
echo `hostname`" login:"
sleep 10
# Reset the mouse pointer so it is visible again
unclutter -idle 5 -jitter 0 &
# Reset the audio volume
amixer -- sset Master $volume &> /dev/null

This is really good and by far the most impressive one I have been able to test so far.

very nice, much boot screen

Haha, you linked my own question! But that is very good code there. I'm going to try it.

cat /etc/issue | tail -n +2 : useless use of cat.  tail -n +2 /etc/issue is simpler, especially when there's no pipeline.

Good point. Fixed it, and fixed the broken links.

Commodore 64
1?CHR$(147)
2?"    **** COMMODORE 64 BASIC V2 ****"
3?
4?" 64K RAM SYSTEM  38911 BASIC BYTES FREE"

The BASIC intepreter will display the READY. prompt automatically.

I'd suggest changing line 1 to:
1 POKE 53280,6:POKE 53281,14:?CHR$(159):?CHR$(147)
...to make sure the colors are correct.

+1 for bringing a tear to my eye, even though it doesn't meet the rules.

You can save some bytes by excluding the closing quotation mark on the print statements - i.e., 4?"  64K RAM SYSTEM   38911 BASIC BYTES FREE - this is also very slightly more performant but you'll only notice over much bigger and more complex BASIC programs

You may save further bytes by using the character control symbols, like ?"{CLEAR}" which appears as a reversed heart symbol. You can also reduce the number of lines, this could be done in two lines, possibly one if you use CBM PRG Studio, or write this onto a C128 and then load it into C64 mode.

TI-Basic
AxesOff
GridOff
LabelOff
CoordOff
ClrDraw
DispGraph
ClrHome

On my Ti-83 Plus it shows "Done", dunno if this breaks the rules...

To avoid the "Done" you should add an extra line with a single quote.

This does not simulate a reboot. If you just press 2ND+ON and then ON again, you only put the device into standby and waking it up shows (in most cases) the screen that you had when you put it into a standby. A real reboot is harder to do. There are ways to do it without removing the battery, but that's the easiest one. So what you see after changing the batteries is what the program should simulate. That's harder, but also possible in TI-Basic.

Bash + Coreutils (Linux)
echo "The system is going down for maintenance NOW."
clear
sleep 5
dmesg|while read i; do echo "$i"; sleep 0.1; done
cat /etc/issue
login

This is good if run from a virtual terminal. Is there some way to make it full screen if it is started in an xterm? I suppose at that point you are basically implementing a screensaver.

@Lembik xterm -fullscreen?

@professorfish As in http://codegolf.stackexchange.com/questions/26697/pitch-dark-earth-hour-remembrance

Tried it on Mac; doesn't work.

@Jwosty On OS X (Mavericks, 10.9) you need to have super user privileges, so replace dmesg with sudo dmesg. Futhermore /etc/issue does not exist on OS X.

Windows 8
Shoddy attempt, I can't figure out how to auto full screen. I tried.
<!DOCTYPE html>
<html>
<body>

<iframe width="1600" height="900" src="http://www.youtube.com/embed/VgQ87b7muWs?start=510&end=524&autoplay=1" frameborder="0" allowfullscreen></iframe>

</body>
</html>

You can try to look for the HTML5 API Element.RequestFullScreen() (https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Using_full_screen_mode)

Python / Pygame OSX
import pygame, time, os, urllib # Import Modules
pygame.init() # Initalise Pygame
pygame.mouse.set_visible(0) # Hide the Cursor
stdscr = pygame.display.set_mode((1280,800),pygame.FULLSCREEN) # Set up the display
stdscr.fill((255,255,255)) # Fill the screen white
urllib.urlretrieve("http://harrybeadle.github.io/FakeRestart/apple.bmp", "apple.bmp") # Get Apple Logo
urllib.urlretrieve("http://harrybeadle.github.io/FakeRestart/startup.wav", "startup.wav") # Get Startup Sound
time.sleep(1) # Wait for 1 second, screen still black
applelogo = pygame.image.load('apple.bmp').convert() # Load the Logo
pygame.mixer.music.load('startup.wav') # Load the Bung
stdscr.blit(applelogo,(580, 340)) # Blit the logo
pygame.mixer.music.play(1) # Play the sound
pygame.display.flip() # Flip the buffers
time.sleep(5) # Wait 5 seconds
pygame.quit() # Quit the pygame window
os.remove('apple.bmp') # Delete logo
os.remove('startup.wav') # Delete bung
os.system('/System/Library/CoreServices/"Menu Extras"/User.menu/Contents/Resources/CGSession -suspend') # Lock the Mac

Now Updated!
Features:

Blank Screen
White Screen w/ Apple Logo and Bung Sound
Assets downloaded from GitHub using urlib
Locks the user's Mac preserving any work using a terminal command and os.system()

Nice. Minor nitpick - the rules say: "If you need to use external images to make the reboot look more realistic then your code should grab those automatically from the web."

@semi-extrinsic Looked into it, it's more bother than it's worth, I had to edit the image anyway and Pygame is not friendly with any filetype that isn't a Windows Bitmap, so I think I leave it as it is for now.

@semi-extrinsic Scrap my previous comment, functionality added.

This only shows the apple logo full screen for a few seconds. It definitely needs the "Bung" :)

@Lembik I've added that now, along with moving the assets to GitHub for reliability :)

British Colour coding style: x=1 # set x to 1

@ace I would get a mark for this commenting in F452 :)

This one does linux with parameters "quiet" and "init=/bin/sh"
#!/bin/sh
echo shutting down
sleep 1
clear
echo Press F12 to enter setup. #everyone forgets the BIOS
sleep 1
clear

usually systems either show a image or console output. and not everyone's bios is on f12 :P

@masterX244 - the image is a configurable build option in linux.  with quiet there is no kernel ouput and with init=/bin/sh there is no startup output because the init is to simply start a shell.  You should try it sometime and see exactly what is needed to start X.  with devtmfs+automount enabled I can get to X in < 0.2sec with a 1-liner.

ahh, not a common config thats why i commented

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


text:
Guess the word (aka Lingo)
The goal of this challenge is to write a program able to guess a word in the smallest possible number of attempts.
It is based on the concept of the Lingo TV show (http://en.wikipedia.org/wiki/Lingo_(U.S._game_show)).
Rules
Given a word length passed as the first argument on its command line, the player program disposes of five attempts to guess the word by writing a guess on its standard output followed by a single \n character.
After a guess is made, the program receives a string on its standard input, also followed by a single \n character.
The string has the same length as the word to guess and is comprised of a sequence of the following characters:

X: which means that the given letter is not present in the word to guess
?: which means that the given letter is present in the word to guess, but at another location
O: which means that the letter at this location has been correctly guessed

For example, if the word to guess is dents, and the program sends the word dozes, it will receive OXX?O because d and s are correct, e is misplaced, and o and z are not present.
Be careful that if a letter is present more times in the guessing attempt than in the word to guess, it will not be marked as ? and O more times than the number of occurences of the letter in the word to guess.
For example, if the word to guess is cozies and the program sends tosses, it will receive XOXXOO because there is only one s to locate.
Words are chosen from an english word list. If the word sent by the program is not a valid word of the correct length, the attempt is considered as an automatic failure and only X's are returned.
The player program should assume that a file named wordlist.txt and containing one word per line is present in the current working directory, and can be read as necessary.
Guesses should only be comprised of alphabetic low-case characters ([a-z]).
No other network or file operations are allowed for the program.
The game ends when a string only comprised of O is returned or after the program has made 5 attempts and was not able to guess the word.
Scoring
The score of a game is given by the given formula:
score = 100 * (6 - number_of_attempts)

So if the word is correctly guessed on the first try, 500 points are given. The last try is worth 100 points.
Failure to guess the word grants zero points.
The pit
Player programs will be evaluated by trying to have them guess 100 random words for each word length between 4 and 13 characters inclusively.
Random word selection will be done by advance so all entries will have to guess the same words.
The winning program, and accepted answer, will be the one to reach the highest score.
Programs will be run in an Ubuntu virtual machine, using the code at https://github.com/noirotm/lingo. Implementations in any language are accepted as long as reasonable instructions to compile and/or run them are provided.
I'm providing a few test implementations in ruby in the git repository, feel free to take inspiration from them.
This question will be periodically updated with rankings for published answers so challengers can improve their entries.
The official final evaluation will take place on the 1st of July.
Update
Entries can now assume the presence of wordlistN.txt files to speed up reading the word list for the current word length for N between 4 and 13 inclusively.
For example, there is a wordlist4.txt file containing all four letter words, and wordlist10.txt containing all ten letter words, and so on.
First round results
At the date of 2014-07-01, three entries have been submitted, with the following results:
                        4       5       6       7       8       9       10      11      12      13      Total
./chinese-perl-goth.pl  8100    12400   15700   19100   22100   25800   27900   30600   31300   33600   226600
java Lingo              10600   14600   19500   22200   25500   28100   29000   31600   32700   33500   247300
./edc65                 10900   15800   22300   24300   27200   29600   31300   33900   33400   33900   262600

** Rankings **
1: ./edc65 (262600)
2: java Lingo (247300)
3: ./chinese-perl-goth.pl (226600)

All entries performed consistently, with a clear winner, being @edc65's C++'s entry.
All contestants are pretty awesome. I have been unable so far to even beat @chinese-perl-goth.
If more entries are submitted, another evaluation will take place. Current entries can also be improved if you feel like you can do better.

So basicly you have to make 2 programs/functions? 1 that knows the word and the other one that tries to guess it?

@TeunPronk no, only one program, the word guesser. The game engine exists and can be compiled from the github repository mentioned in the question.

Just to clarify: if the program takes more than 6 tries to guess the word, does it get negative points or just zero? In other words, do we need logic to quit the program after 6 tries to avoid negative points? (Rules say zero points if the program fails to guess the word)

@ZoveGames: OP states the player program disposes of five attempts to guess the word by writing a guess on its standard output....

Sorry I didn't read completely...

@ZoveGames after five attempts, your program should exit, but the game engine will forcibly terminate it if it refuses to do so :)

@SirDarius Is the program allowed to make you guess a new word?

@RichardA no, the player program is run only for one word.

@SirDarius Could you please explain what you mean with "Implementations in any language are accepted as long as reasonable instructions to compile and/or run them are provided."? I didn't quite understand what you meant with that.

@RichardA There is no language restriction for this challenge, however, if you choose an exotic language not readily available on Ubuntu, please give explanations how to have your program running.

@SirDarius Ubuntu ships with Python right?

@RichardA yes right, don't worry about Python, it is a first-class citizen, so I will have no problem running some python code :)

Seems like Python is unable to pick up from stdin. Not sure why. pit.rb hangs when trying to read from stdin

The output of the program should be a valid word? Or can it be any sequence of character? I want to clarify the rule "If the word sent by the program is not a valid word of the correct length" whether it only wants to specify the length of the guess. Because I see this really similar to Mastermind, where you can guess any sequence of colored pegs.

@justhalf you must give a word that belongs to the wordlist, AND has the same length as the word to guess.

@RichardA what do you mean by pit.rb hangs? It takes quite a long time to finish pit.rb, for your information. And ensure that you do sys.stdout.flush() after each print in Python.

@justhalf Well, after 10 minutes NOTHING happens. I do flush my output, but it seems either the lingo application waits for input indefinitely or my python script waits for output indefinitely. Send: print(words[index], end="", flush=True, file=sys.stdout) Receive: response = sys.stdin.readline()

@RichardA if you don't feel like publishing a non-working entry, you can always use a temporary Gist as a sandbox, so I can test things on my side.

@SirDarius http://pastebin.com/Rfx1D8Xc My entry so far.

@RichardA using python 2 here, replaced the print line by print words[index] followed by sys.stdout.flush() and it works fine

@SirDarius I'm using Python 3, is that okay or do I HAVE to use Python 2?

You should not use end="", the game engine specifically waits for \n

@RichardA Either will do, as long as it works ;)

Anyway, for testing you should use ./lingo instead of pit.rb, right? You can run just single word there.

@justhalf Does it really? I might have found my bug then!

@justhalf Thanks so much for that! I can finally continue!

What are the runtime constraints? My first guess is pretty slow (52 hours in my first try, but I can do better...)

@edc65 I haven't enforced constraints yet, given that all posted entries are quite fast so far. 52 hours is not acceptable though ;) The challenge is not that hard, unless you are using an extremely complex algorithm, I don't see why a guess would take more than a second (not including the time needed to read the word list). Don't let this discourage you though, I'm eager to see more challengers !

@SirDarius, is there any possibility to count the number of correct guesses beside the score? I feel my answer tends to give the correct answers albeit in more guesses.

@justhalf good idea indeed, i'll try to implement that

C++ 267700 Points
A porting from an old MasterMind engine.
Differences from MasterMind:

More slots
More symbols
Bigger solution space (but non so much, because not all symbols combination allowed)
The response is much informative, so we have more information after each guess
The response is slower to generate and that's a pity because my algorithm have to do it a lot.

The basic idea is choosing the word that minimize the solution space. The algorithm is really slow for the first guess (I mean 'days'), but the best first guess depends only on the word len, so it's hardcoded in the source. The other guesses are done in matter of seconds.
The Code
(Compile with g++ -O3)
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <ctime>
#include <cstdlib>

using namespace std;

class LRTimer
{
private:
    time_t start;
public:
    void startTimer(void)
    {
        time(&start);
    }

    double stopTimer(void)
    {
        return difftime(time(NULL),start);
    }

};

#define MAX_WORD_LEN 15
#define BIT_QM 0x8000

LRTimer timer;
int size, valid, wordLen;

string firstGuess[] = { "", "a", "as", "iao", "ares",
    "raise", "sailer", "saltier", "costlier", "clarities",
    "anthelices", "petulancies", "incarcerates", "allergenicity" };

class Pattern
{
public:
    char letters[MAX_WORD_LEN];
    char flag;
    int mask;

    Pattern()
        : letters(), mask(), flag()
    {
    }

    Pattern(string word)
        : letters(), mask(), flag()
    {
        init(word);
    }

    void init(string word)
    {
        const char *wdata = word.data();
        for(int i = 0; i < wordLen; i++) {
            letters[i] = wdata[i];
            mask |= 1 << (wdata[i]-'a');
        }
    }

    string dump()
    {
        return string(letters);
    }

    int check(Pattern &secret)
    {
        if ((mask & secret.mask) == 0)
            return 0;

        char g[MAX_WORD_LEN], s[MAX_WORD_LEN];
        int r = 0, q = 0, i, j, k=99;
        for (i = 0; i < wordLen; i++)
        {
            g[i] = (letters[i] ^ secret.letters[i]);
            if (g[i])
            {
                r += r;
                k = 0;
                g[i] ^= s[i] = secret.letters[i];
            }
            else
            {
                r += r + 1;
                s[i] = 0;
            }
        }
        for (; k < wordLen; k++)
        {
            q += q;
            if (g[k])
            {
                for (j = 0; j < wordLen; j++)
                    if (g[k] == s[j])
                    {
                        q |= BIT_QM;
                        s[j] = 0;
                        break;
                    }
            }
        }
        return r|q;
    }

    int count(int ck, int limit);

    int propcheck(int limit);

    void filter(int ck);
};

string dumpScore(int ck)
{
    string result(wordLen, 'X');
    for (int i = wordLen; i--;)
    {
        result[i] = ck & 1 ? 'O' : ck & BIT_QM ? '?' : 'X';
        ck >>= 1;
    }
    return result;
}

int parseScore(string ck)
{
    int result = 0;
    for (int i = 0; i < wordLen; i++)
    {
        result += result + (
            ck[i] == 'O' ? 1 : ck[i] == '?' ? BIT_QM: 0
        );
    }
    return result;
}

Pattern space[100000];

void Pattern::filter(int ck)
{
    int limit = valid, i = limit;
//  cerr << "Filter IN Valid " << setbase(10) << valid << " This " << dump() << "\n";

    while (i--)
    {
        int cck = check(space[i]);
//      cerr << setbase(10) << setw(8) << i << ' ' << space[i].dump()
//          << setbase(16) << setw(8) << cck << " (" << Pattern::dumpScore(cck) << ") ";

        if ( ck != cck )
        {
//          cerr << " FAIL\r" ;
            --limit;
            if (i != limit)
            {
                Pattern t = space[i];
                space[i] = space[limit];
                space[limit] = t;
            }
        }
        else
        {
//          cerr << " PASS\n" ;
        }
    }
    valid = limit;
//  cerr << "\nFilter EX Valid " << setbase(10) << valid << "\n";
};

int Pattern::count(int ck, int limit)
{
    int i, num=0;
    for (i = 0; i < valid; ++i)
    {
        if (ck == check(space[i]))
            if (++num >= limit) return num;
    }
    return num;
}

int Pattern::propcheck(int limit)
{
    int k, mv, nv;

    for (k = mv = 0; k < valid; ++k)
    {
        int ck = check(space[k]);
        nv = count(ck, limit);
        if (nv >= limit)
        {
            return 99999;
        }
        if (nv > mv) mv = nv;
    }
    return mv;
}

int proposal(bool last)
{
    int i, minnv = 999999, mv, result;

    for (i = 0; i < valid; i++)
    {
        Pattern& guess = space[i];
//      cerr << '\r' << setw(6) << i << ' ' << guess.dump();
        if ((mv = guess.propcheck(minnv)) < minnv)
        {
//          cerr << setw(6) << mv << ' ' << setw(7) << setiosflags(ios::fixed) << setprecision(0) << timer.stopTimer() << " s\n";
            minnv = mv;
            result = i;
        }
    }
    if (last)
        return result;
    minnv *= 0.75;
    for (; i<size; i++)
    {
        Pattern& guess = space[i];
//      cerr << '\r' << setw(6) << i << ' ' << guess.dump();
        if ((mv = guess.propcheck(minnv)) < minnv)
        {
//          cerr << setw(6) << mv << ' ' << setw(7) << setiosflags(ios::fixed) << setprecision(0) << timer.stopTimer() << " s\n";
            minnv = mv;
            result = i;
        }
    }
    return result;
}

void setup(string wordfile)
{
    int i = 0;
    string word;
    ifstream infile(wordfile.data());
    while(infile >> word)
    {
        if (word.length() == wordLen) {
            space[i++].init(word);
        }
    }
    infile.close();
    size = valid = i;
}

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        cerr << "Specify word length";
        return 1;
    }

    wordLen = atoi(argv[1]);

    timer.startTimer();
    setup("wordlist.txt");
    //cerr << "Words " << size
    //  << setiosflags(ios::fixed) << setprecision(2)
    //  << " " << timer.stopTimer() << " s\n";

    valid = size;
    Pattern Guess = firstGuess[wordLen];
    for (int t = 0; t < 5; t++)
    {
        cout << Guess.dump() << '\n' << flush;
        string score;
        cin >> score;
        int ck = parseScore(score);
        //cerr << "\nV" << setw(8) << valid << " #"
        //  << setw(3) << t << " : " << Guess.dump()
        //  << " : " << score << "\n";
        if (ck == ~(-1 << wordLen))
        {
            break;
        }
        Guess.filter(ck);
        Guess = space[proposal(t == 3)];
    }
    // cerr << "\n";

    double time = timer.stopTimer();
    //cerr << setiosflags(ios::fixed) << setprecision(2)
    //   << timer.stopTimer() << " s\n";

    return 0;
}

My scores
Evaluation with lingo, 100 rounds:
4   9000
5   17700
6   22000
7   25900
8   28600
9   29700
10  31000
11  32800
12  33500
13  34900

Total   265'100
Self evalueted scores
Here are my average points, scored on the whole wordlist. Not completely relyable because some detail of algorithm has changed during the tests.
 4 # words  6728 PT AVG   100.98 87170.41 s
 5 # words 14847 PT AVG   164.44 42295.38 s
 6 # words 28127 PT AVG   212.27 46550.00 s
 7 # words 39694 PT AVG   246.16 61505.54 s
 8 # words 49004 PT AVG   273.23 63567.45 s
 9 # words 50655 PT AVG   289.00 45438.70 s
10 # words 43420 PT AVG   302.13 2952.23 s
11 # words 35612 PT AVG   323.62 3835.00 s
12 # words 27669 PT AVG   330.19 5882.98 s
13 # words 19971 PT AVG   339.60 2712.98 s

According to these numbers, my average score should be near 257'800
PIT SCORE
At last I installed Ruby, so now I have an 'official' score:
    4       5       6       7       8       9      10      11      12      13   TOTAL
10700   16300   22000   25700   27400   30300   32000   33800   34700   34800   267700

My intention was to create something like this. Alas I couldn't find how to truly minimize the solution space, so I approximated it. And mine is in Python, so it's even slower, haha. I also hardcoded the first guess. Yours is definitely better than mine for the shorter strings. Can you test with my implementation also on the same set of input to compare? Also we have quite a different set of first guesses.

@justhalf I tried some rounds with lingo.go. I didn't check with the pit (I don't have Ruby installed). Our scores are close, it's a matter of luck I think.

Yours is better I think, since your reported average is better than the score that I reported. Although you seem to take substantially more time.

This seems to be the strongest player so far. I am going to run the official result later today, stay tuned !

Oops, correction for my comment above, I forgot that my submission is in Java.

Java, 249700 points (beats Chinese Perl Goth in my test)
Updated ranklist:

                        4       5       6       7       8       9       10      11      12      13      Total
perl chinese_perl_goth.pl 6700  12300   16900   19200   23000   26100   28500   29600   32100   33900   228300
java Lingo              9400    14700   18900   21000   26300   28700   30300   32400   33800   34200   249700

Here is the old ranklist using pit.rb:

                        4       5       6       7       8       9       10      11      12      13      Total
ruby player-example.rb  200     400     400     500     1800    1400    1700    1600    3200    4400    15600
ruby player-example2.rb 2700    3200    2500    4300    7300    6300    8200    10400   13300   15000   73200
ruby player-example3.rb 4500    7400    9900    13700   15400   19000   19600   22300   24600   27300   163700
perl chinese_perl_goth.pl 6400  14600   16500   21000   22500   26000   27200   30600   32500   33800   231100
java Lingo              4800    13100   16500   21400   27200   29200   30600   32400   33700   36100   245000

** Rankings **
1: java Lingo (245000)
2: perl chinese_perl_goth.pl (231100)
3: ruby player-example3.rb (163700)
4: ruby player-example2.rb (73200)
5: ruby player-example.rb (15600)

Compared to @chineseperlgoth, I lose in shorter words (< 6 chars) but I win in longer words (>= 6 chars).
The idea is similar to @chineseperlgoth, it's just that my main idea is about finding the guess (can be any word of the same length, not necessarily one of the remaining possibilities) which gives the most information for the next guess.

Currently I'm still playing with the formula, but for the scoreboard above, I choose the word which will yield the minimum for:

-num_confusion * entropy

The latest version uses different scoring to find next best guess, which is maximizing the number of "single possibility" after the current guess. This is done by trying all words in pruned wordlist (to save time) on all possible candidates, and see which guess is more probable to produce "single possibility" (that is, after this guess there will only be one possible answer) for the next guess.
So for example this run:

Starting new round, word is boons
Got:   seora
Sent:  ?XOXX
Got:   topsl
Sent:  XOX?X
Got:   monks
Sent:  XO?XO
Got:   bewig
Sent:  OXXXX
Got:   boons
Sent:  OOOOO
Round won with score 100

From the first three guesses, we already got "*oo*s" with an "n" somewhere and we still need to figure out one more letter. Now the beauty of this algorithm is that instead of guessing words which are similar to that form, it instead guesses the word which has no relation to previous guesses at all, trying to give more letters, hopefully revealing the missing letter. In this case it happens to also get the position for the missing "b" correctly, and concludes with the correct final guess "boons".
Here is the code:
import java.util.*;
import java.io.*;

class Lingo{
    public static String[] guessBestList = new String[]{
                                "",
                                "a",
                                "sa",
                                "tea",
                                "orae",
                                "seora", // 5
                                "ariose",
                                "erasion",
                                "serotina",
                                "tensorial",
                                "psalterion", // 10
                                "ulcerations",
                                "culteranismo",
                                "persecutional"};
    public static HashMap<Integer, ArrayList<String>> wordlist = new HashMap<Integer, ArrayList<String>>();

    public static void main(String[] args){
        readWordlist("wordlist.txt");
        Scanner scanner = new Scanner(System.in);
        int wordlen = Integer.parseInt(args[0]);
        int roundNum = 5;
        ArrayList<String> candidates = new ArrayList<String>();
        candidates.addAll(wordlist.get(wordlen));
        String guess = "";
        while(roundNum-- > 0){
            guess = guessBest(candidates, roundNum==4, roundNum==0);
            System.out.println(guess);
            String response = scanner.nextLine();
            if(isAllO(response)){
                break;
            }
            updateCandidates(candidates, guess, response);
            //print(candidates);
        }
    }

    public static void print(ArrayList<String> candidates){
        for(String str: candidates){
            System.err.println(str);
        }
        System.err.println();
    }

    public static void readWordlist(String path){
        try{
            BufferedReader reader = new BufferedReader(new FileReader(path));
            while(reader.ready()){
                String word = reader.readLine();
                if(!wordlist.containsKey(word.length())){
                    wordlist.put(word.length(), new ArrayList<String>());
                }
                wordlist.get(word.length()).add(word);
            }
        } catch (Exception e){
            System.exit(1);
        }
    }

    public static boolean isAllO(String response){
        for(int i=0; i<response.length(); i++){
            if(response.charAt(i) != 'O') return false;
        }
        return true;
    }

    public static String getResponse(String word, String guess){
        char[] wordChar = word.toCharArray();
        char[] result = new char[word.length()];
        Arrays.fill(result, 'X');
        for(int i=0; i<guess.length(); i++){
            if(guess.charAt(i) == wordChar[i]){
                result[i] = 'O';
                wordChar[i] = '_';
            }
        }
        for(int i=0; i<guess.length(); i++){
            if(result[i] == 'O') continue;
            for(int j=0; j<wordChar.length; j++){
                if(result[j] == 'O') continue;
                if(wordChar[j] == guess.charAt(i)){
                    result[i] = '?';
                    wordChar[j] = '_';
                    break;
                }
            }
        }
        return String.valueOf(result);
    }

    public static void updateCandidates(ArrayList<String> candidates, String guess, String response){
        for(int i=candidates.size()-1; i>=0; i--){
            String candidate = candidates.get(i);
            if(!response.equals(getResponse(candidate, guess))){
                candidates.remove(i);
            }
        }
    }

    public static int countMatchingCandidates(ArrayList<String> candidates, String guess, String response){
        int result = 0;
        for(String candidate: candidates){
            if(response.equals(getResponse(candidate, guess))){
                result++;
            }
        }
        return result;
    }

    public static String[] getSample(ArrayList<String> words, int size){
        String[] result = new String[size];
        int[] indices = new int[words.size()];
        for(int i=0; i<words.size(); i++){
            indices[i] = i;
        }
        Random rand = new Random(System.currentTimeMillis());
        for(int i=0; i<size; i++){
            int take = rand.nextInt(indices.length-i);
            result[i] = words.get(indices[take]);
            indices[take] = indices[indices.length-i-1];
        }
        return result;
    }

    public static String guessBest(ArrayList<String> candidates, boolean firstGuess, boolean lastGuess){
        if(candidates.size() == 1){
            return candidates.get(0);
        }
        String minGuess = candidates.get(0);
        int wordlen = minGuess.length();
        if(firstGuess && guessBestList[wordlen].length()==wordlen){
            return guessBestList[wordlen];
        }
        int minMatches = Integer.MAX_VALUE;
        String[] words;
        if(lastGuess){
            words = candidates.toArray(new String[0]);
        } else if (candidates.size()>10){
            words = bestWords(wordlist.get(wordlen), candidates, 25);
        } else {
            words = wordlist.get(wordlen).toArray(new String[0]);
        }
        for(String guess: words){
            double sumMatches = 0;
            for(String word: candidates){
                int matches = countMatchingCandidates(candidates, guess, getResponse(word, guess));
                if(matches == 0) matches = candidates.size();
                sumMatches += (matches-1)*(matches-1);
            }
            if(sumMatches < minMatches){
                minGuess = guess;
                minMatches = sumMatches;
            }
        }
        return minGuess;
    }

    public static String[] bestWords(ArrayList<String> words, ArrayList<String> candidates, int size){
        int[] charCount = new int[123];
        for(String candidate: candidates){
            for(int i=0; i<candidate.length(); i++){
                charCount[(int)candidate.charAt(i)]++;
            }
        }
        String[] tmp = (String[])words.toArray(new String[0]);
        Arrays.sort(tmp, new WordComparator(charCount));
        String[] result = new String[size+Math.min(size, candidates.size())];
        String[] sampled = getSample(candidates, Math.min(size, candidates.size()));
        for(int i=0; i<size; i++){
            result[i] = tmp[tmp.length-i-1];
            if(i < sampled.length){
                result[size+i] = sampled[i];
            }
        }
        return result;
    }

    static class WordComparator implements Comparator<String>{
        int[] charCount = null;

        public WordComparator(int[] charCount){
            this.charCount = charCount;
        }

        public Integer count(String word){
            int result = 0;
            int[] multiplier = new int[charCount.length];
            Arrays.fill(multiplier, 1);
            for(char chr: word.toCharArray()){
                result += multiplier[(int)chr]*this.charCount[(int)chr];
                multiplier[(int)chr] = 0;
            }
            return Integer.valueOf(result);
        }

        public int compare(String s1, String s2){
            return count(s1).compareTo(count(s2));
        }
    }
}

Awesome, this entry is seriously strong ! I remember seeing human players in the TV show using a similar strategy when they were unable to guess a word from the current clues.

Perl
There's still some room for improvement but at least it beats the included example players :)
Assumes write access to current directory for caching wordlists (to make it run a bit faster); will create wordlist.lenN.stor files using Storable.  If this is an issue, remove read_cached_wordlist and change the code to use just read_wordlist.
Explanation
First, I build a histogram of letter frequencies in all the words in the current wordlist (build_histogram).  Then I need to choose my next guess - which is done by find_best_word.  The scoring algorithm is just adding the histogram values together, skipping letters already seen.  This gives me a word containing the most frequent letters in the wordlist.  If there is more than one word with a given score, I choose one randomly.
Having found a word, I send it to the game engine, read the reply then try and do something useful with it :)
I maintain a set of conditions, that is, letters that can occur at a given position in a word. On start, this is just simple (['a'..'z'] x $len), but it is updated basing on the hints given in reply (see update_conds).  I build a regex out of those conditions then and filter the wordlist through it.
During tests I have found out then that the aforementioned filtering doesn't handle ?s too well, hence the second filter (filter_wordlist_by_reply).  This takes advantage of the fact that a letter marked as ? occurs in the word on a different position, and filters the wordlist accordingly.
These steps are repeated for every iteration of the main loop, unless the solution is found (or it is not possible to read from stdin anymore, which means a failure).
Code
#!perl
use strict;
use warnings;
use v5.10;
use Storable;

$|=1;

sub read_wordlist ($) {
    my ($len) = @_;
    open my $w, '<', 'wordlist.txt' or die $!;
    my @wordlist = grep { chomp; length $_ == $len } <$w>;
    close $w;
    \@wordlist
}

sub read_cached_wordlist ($) {
    my ($len) = @_;
    my $stor = "./wordlist.len$len.stor";
    if (-e $stor) {
        retrieve $stor
    } else {
        my $wl = read_wordlist $len;
        store $wl, $stor;
        $wl
    }
}

sub build_histogram ($) {
    my ($wl) = @_;
    my %histo = ();
    for my $word (@$wl) {
        $histo{$_}++ for ($word =~ /./g);
    }
    \%histo
}

sub score_word ($$) {
    my ($word, $histo) = @_;
    my $score = 0;
    my %seen = ();
    for my $l ($word =~ /./g) {
        if (not exists $seen{$l}) {
            $score += $histo->{$l};
            $seen{$l} = 1;
        }
    }
    $score
}

sub find_best_word ($$) {
    my ($wl, $histo) = @_;
    my @found = (sort { $b->[0] <=> $a->[0] }
                 map [ score_word($_, $histo), $_ ], @$wl);
    return undef unless @found;
    my $maxscore = $found[0]->[0];
    my @max;
    for (@found) {
        last if $_->[0] < $maxscore;
        push @max, $_->[1];
    }
    $max[rand @max]
}

sub build_conds ($) {
    my ($len) = @_;
    my @c;
    push @c, ['a'..'z'] for 1..$len;
    \@c
}

sub get_regex ($) {
    my ($cond) = @_;
    local $" = '';
    my $r = join "", map { "[@$_]" } @$cond;
    qr/^$r$/
}

sub remove_cond ($$$) {
    my ($conds, $pos, $ch) = @_;
    return if (scalar @{$conds->[$pos]} == 1);
    return unless grep { $_ eq $ch } @{$conds->[$pos]};
    $conds->[$pos] = [ grep { $_ ne $ch } @{$conds->[$pos]} ]
}

sub add_cond ($$$) {
    my ($conds, $pos, $ch) = @_;
    return if (scalar @{$conds->[$pos]} == 1);
    return if grep { $_ eq $ch } @{$conds->[$pos]};
    push @{$conds->[$pos]}, $ch
}

sub update_conds ($$$$) {
    my ($word, $reply, $conds, $len) = @_;
    my %Xes;
    %Xes = ();
    for my $pos (reverse 0..$len-1) {
        my $r = substr $reply, $pos, 1;
        my $ch = substr $word, $pos, 1;

        if ($r eq 'O') {
            $conds->[$pos] = [$ch]
        }

        elsif ($r eq '?') {
            for my $a (0..$len-1) {
                if ($a == $pos) {
                    remove_cond $conds, $a, $ch
                } else {
                    unless (exists $Xes{$a} and $Xes{$a} eq $ch) {
                        add_cond($conds, $a, $ch);
                    }
                }
            }
        }

        elsif ($r eq 'X') {
            $Xes{$pos} = $ch;
            for my $a (0..$len-1) {
                remove_cond $conds, $a, $ch
            }
        }
    }
}

sub uniq ($) {
    my ($data) = @_;
    my %seen;
    [ grep { !$seen{$_}++ } @$data ]
}

sub filter_wordlist_by_reply ($$$) {
    my ($wl, $word, $reply) = @_;
    return $wl unless $reply =~ /\?/;
    my $newwl = [];
    my $len = length $reply;
    for my $pos (0..$len-1) {
        my $r = substr $reply, $pos, 1;
        my $ch = substr $word, $pos, 1;
        next unless $r eq '?';
        for my $a (0..$len-1) {
            if ($a != $pos) {
                if ('O' ne substr $reply, $a, 1) {
                    push @$newwl, grep { $ch eq substr $_, $a, 1 } @$wl
                }
            }
        }
    }
    uniq $newwl
}

my $len = $ARGV[0] or die "no length";
my $wl = read_cached_wordlist $len;
my $conds = build_conds $len;

my $c=0;
do {
    my $histo = build_histogram $wl;
    my $word = find_best_word $wl, $histo;
    die "no candidates" unless defined $word;
    say $word;
    my $reply = <STDIN>;
    chomp $reply;
    exit 1 unless length $reply;
    exit 0 if $reply =~ /^O+$/;
    update_conds $word, $reply, $conds, $len;
    $wl = filter_wordlist_by_reply $wl, $word, $reply;
    $wl = [ grep { $_ =~ get_regex $conds } @$wl ]
} while 1

My rules originally forbade writing to disk, but I make it an exception to allow caching of the word list, because the big one I found makes the whole thing annoyingly slow to test :)

This entry works better than my own (unpublished yet) attempts. Could you explain your algorithm a bit ?

I've added a short explanation; fixed the code formatting a bit as well.

@SirDarius: I don't think there would be any loss if any particular test uses a word list that contains only entries of the proper length.  While it shouldn't be overly difficult for a program to ignore words within the file whose length is other than specified, the existence of such words would at minimum slow down testing.  Also, I wonder if there would be value in allowing submissions to specify an optional program which, given a word list and N, would send to standard output a word list formatted in whatever fashion is most helpful...

...and allow the main program to use that rather than a raw word list (so if some pre-analysis is needed, it will only have to be done once for each word length, rather than once per game).

@supercat i'll update the challenge so that files like wordlistNN.txt are available. Also you can do like the perl entry and cache word list data as you want.

source: Stack Exchange

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

sort: votes


text:
Duct tape can fix Mother's Day
Based on the Duct tape can fix anything question, that was too broad, with very similar rules. Only this time the objective is very specific:
The challenge
Your mission is to make a program that displays hello mom -- without ever writing a single line of code.
You can only use code which is already written for you, both in questions and answers from StackOverflow. All you can do is duct tape it all together the best you can. And of course, it's very important that we provide appropriate attribution so that we don't get our rights terminated.

Rules

You must include links to the questions/answers you used in your answer.

You may not modify the code you find, with the following exceptions:
a. You may rename variables, functions, and methods.  (This doesn't mean you can change a method invocation, by changing, say scanner.nextInt() to scanner.nextLine() and claiming that you're changing a method name.  The change must be in the definition or reference to the same entity.). The solution should still work if variables, functions or methods would be renamed again, so renaming code to contain hello mom as a variable name does not count.
b. You may adjust indentation appropriately.
c. You can assume that the proper modules are loaded for the code snippets to work.  (e.g., import statements for Java and Python, using statements for C# and C++, and their equivalents in all languages)  If the code snippet includes the imports for you, you can move them to the top of the code.
d. If the language requires the code to be in some kind of method body to execute (e.g., public static void main(String[] args) for Java, static int Main(string[] args) for C#, and so on), you can wrap your code in the appropriate method.  But the contents of that main method must remain unmodified.

You must supply an explicit list of any variable/method/function/class rename-ings performed.

You can't take snippets of snippets (meaning if you take a code block from a post, you take the whole thing)

Provide a brief description of what the code does for people who aren't intimate with the language you're using.

You must use snippets posted before this challenge was started.

Popularity contest, so the most upvotes wins!

Deadline
I will accept the the submission that has the most votes around the end of mothersday (midnight of the UTC-11 timezone), but later submissions can still get votes.

Changing strings in the code allowed?

@iamkrillin That would make it fairly trivial to transfer any hello world example into a hello mom code. Also note the last line in the rule about renaming variables.

You must use snippets posted before this challenge was. (I could go answer a bunch of string-related questions with code that would do this)

@Geobits I thought it would be implied by rule2, but indeed it seems prudent to state it specifically. Have included it now.

Mother's day was on the 30th of March. Should I create a time machine with duct tape too? :-)

This is kind of a bad challenge because it requires the answerer to find a code snippet which explicitly contains the word "mom" as a String literal.  That narrows down the available code dramatically and doesn't allow much flexibility or encourage creativity.

Can you insert code inside another snippet?

@Gareth you know, there are other countries...

@JeffGohlke or an m or an o as a literal. Or a snippet that converts code points to characters and snippets that let you calculate the right code point. The restriction is exactly what encourages creativity here. This is what I mentioned on your own challenge, and why I suggested to limit the scope (and subsequently why it was closed).

@m.buettner Yes, but the point I was making in my own roundabout way was that the deadline is on some mother's day, but it's not obvious to me which one. I assume, since the OP is from the Netherlands, that it's the second sunday in May - but it really should be made clear.

@Gareth ah I didn't see the deadline, so I was wondering what your point was :D. In that case my comment should rather be targeted at the OP I suppose ^^

It would be quite the challenge to do this in BrainFuck...

what's with snippets that don't put stuff into variable like baos.toString() ?

@m.buettner Looks like you were right.  Some good answers coming. :)

Wait, Mother’s Day is in two weeks!

I just did find this question, so too late to enter, but the first thing that occurs to me on reading the challenge is that it does not specify what programming language to use. Writing the program in Whitespace, it would be fairly trivial to find a source to quote for each of a space, a tab, and a linefeed. Then just snag a standard Whitespace "hello world" program, and replace "world" with "mom". Rule 4 complicates this, but since Whitespace ignores all characters but those 3, just look for very short snippets to quote that only contain 1 Whitespace character per snippet.

@MatthewNajmon Note that you would not be able to replace anything inside the code of the hello world problem, but perhaps that is not a problem. Also, I have accepted an answer but you can still participate for votes.

@DennisJaheruddin I didn't mean use an existing "hello world" program as one of the quoted code blocks. I meant go anywhere online to find a Whitespace "hello world" program. Modify it to replace "world" with "mom". Then find-replace every space in that program with a quotable block containing one space and no tabs or linefeeds, find-replace the tabs with a quotable block containing one tab and no space or linefeed, and find-replace all the linefeeds with a block containing one of those with no spaces or tabs.

@MatthewNajmon, bear in mind that this is a popularity contest. Whilst you could do this, it may not lead to an interesting or popular solution. My BF solution plays on a similar language quirk, but I explicitly avoided using single-symbol snippets for exactly this reason.

Brainfuck
Oh god why did I do this to myself?
It is actually possible to find each BF symbol by itself as a code snippet in some answer somewhere. The interesting bit was piecing together bits of other people's code, each representing a block of BF instructions. Unfortunately there are basically no unmatched [ and ] symbols out there, so I had to cheat a bit for those, and I had to get an awful lot of mileage out of a funky Haskell snippet which had a bunch of pluses in it. There are probably others out there. Beyond that, here's some Frankensteined code:
byte x = 1;
byte y = 2;
byte z = x + y;   // ERROR: Cannot implicitly convert type 'int' to 'byte'
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
[
int a = (b > 10) ? some_value
                 : another_value;
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
int a = (b > 10) ? c : d;
byte x = 1;
byte y = 2;
byte z = x + y;   // ERROR: Cannot implicitly convert type 'int' to 'byte'
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
?"<<-"
]
exec >{space}> (command)
byte z = (int) x + (int) y;
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
find . -type f -print -exec cat {} \;
git reset .
byte x = 1;
byte y = 2;
byte z = x + y;   // ERROR: Cannot implicitly convert type 'int' to 'byte'
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
System.out.print("B");
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
fatal: Failed to resolve 'HEAD' as a valid ref.
while read p; do
echo $p
done < $filename
static HMODULE hMod = NULL;
  static bool once = false;
  if (!once++)
    hMod = LoadLibrary("xxx");
 if (originalValue.length > size) {
static HMODULE hMod = NULL;
  static bool once = true;
  if (once--)
    hMod = LoadLibrary("xxx");
$ cd /usr/local/wherever
$ grep timmy accounts.txt
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
ls -ld $(find .)
git commit --amend -m "New commit message"
wget -q -O - $line
git rebase --interactive $parent_of_flawed_commit
find . -type f -user 'user1' -maxdepth 1

And, since my mother is British, the output is quite simply hello mum
Bibliography:
https://stackoverflow.com/questions/17845014/what-does-the-regex-mean
[ and ], with apologies
https://stackoverflow.com/a/21460161/2581168
find . -type f -print -exec cat {} \;

https://stackoverflow.com/questions/6161328/what-exactly-does-this-do-exec-command
exec >{space}> (command)

https://stackoverflow.com/questions/20130538/what-is-in-haskell
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}

https://stackoverflow.com/questions/21947452/why-is-printing-b-dramatically-slower-than-printing
System.out.print("B");

https://stackoverflow.com/questions/941584/byte-byte-int-why
byte x = 1;
byte y = 2;
byte z = x + y;   // ERROR: Cannot implicitly convert type 'int' to 'byte'

https://stackoverflow.com/a/160295/2581168
int a = (b > 10) ? c : d;

And
int a = (b > 10) ? some_value
                 : another_value;

https://stackoverflow.com/questions/13273002/what-does-mean-in-r
?"<<-"

https://stackoverflow.com/questions/3450420/bool-operator-and
static HMODULE hMod = NULL;
static bool once = false;
if (!once++)
    hMod = LoadLibrary("xxx");

And
static HMODULE hMod = NULL;
static bool once = false;
if (!once--)
    hMod = LoadLibrary("xxx");

https://stackoverflow.com/questions/22776085/in-which-case-will-size-originalvalue-length-in-string-constructor-string
if (originalValue.length > size) {

https://stackoverflow.com/questions/3797795/does-mean-stdout-in-bash
wget -q -O - $line

https://stackoverflow.com/questions/179123/how-do-i-edit-an-incorrect-commit-message-in-git/179147#179147
git commit --amend -m "New commit message"

And
git rebase --interactive $parent_of_flawed_commit

https://stackoverflow.com/questions/14763413/grep-ls-output-across-tabs/14763499#14763499
find . -type f -user 'user1' -maxdepth 1

https://stackoverflow.com/questions/945288/saving-current-directory-to-bash-history
$ cd /usr/local/wherever
$ grep timmy accounts.txt

https://stackoverflow.com/questions/348170/undo-git-add-before-commit/682343#682343
fatal: Failed to resolve 'HEAD' as a valid ref.

Error messages are not code. Though that one should be easy to fix

Also there should probably be a ruling on whether the code snippet needs to be in the language of the answer. But well done, regardless

@durron597, true, but I kind of like having the error message in there. There's a git add . in the same post if OP has a problem with it.

There might be some J answers out there that have unmatched []s, but those often come with .s included. http://stackoverflow.com/questions/21898628/how-to-create-a-gerund-from-an-array-in-j

This is awesome.  +1000

I'm pretty sure you can find an unmatched [ by exploiting the Java toString output for arrays. I'm not sure what you need, but this might work: http://stackoverflow.com/questions/3442090/java-what-is-this-ljava-lang-object/3442100#3442100

Java
Start with these:
https://stackoverflow.com/a/19509316/1768232
String myStr = "hello";
String myStr1 = "hello";

https://stackoverflow.com/a/8341513/1768232
String[] history = new String[] { "hey", "you", "Mom" };

https://stackoverflow.com/a/23300004/1768232
String editednames = titleCase(name);

https://stackoverflow.com/a/20698093/1768232
myString = myString.toLowerCase();

https://stackoverflow.com/a/19393222/1768232
System.out.println(Name + " " + Income);

https://stackoverflow.com/a/1181979/1768232
public static <T> T last(T[] array) {
   return array[array.length - 1];
}

Add the required class and public static void main(String[] args){ } as allowed in Rule #2d (not around the static method), and change some variable / method names in exactly 3 of 6 snippets:

Change name -> history in the third snippet
Change editednames -> myString in the third snippet
Change Name -> myStr in the fifth snippet
Change Income -> myString in the fifth snippet
Change last -> titleCase in the sixth snippet

Resulting program:
public class DuctTape {
  public static void main(String[] args) {
    // https://stackoverflow.com/a/19509316/1768232
    String myStr = "hello";
    String myStr1 = "hello";

    // https://stackoverflow.com/a/8341513/1768232
    String[] history = new String[] { "hey", "you", "Mom" };

    // https://stackoverflow.com/a/23300004/1768232
    String myString = titleCase(history);

    // https://stackoverflow.com/a/20698093/1768232
    myString = myString.toLowerCase();

    // https://stackoverflow.com/a/19393222/1768232
    System.out.println(myStr + " " + myString);
  }

  // https://stackoverflow.com/a/1181979/1768232
  public static <T> T titleCase(T[] array) {
    return array[array.length - 1];
  }
}

Output:
hello mom

This appears to break the rules; 2a indicates you can't change which method is invoked by a method call, which you did in changing titleCase() to last().

@BillyMailman if your interpretation is correct then you can NEVER use a method definition unless the q/a also provides a call to that method somewhere. I will try to edit if there's a ruling from OP

Actually, @BillyMailman is right.  But the way you do this is by renaming the method to titleCase() rather than renaming the external reference.  That's how you'd tie it together.  Rule 2a dictates that changing method/function names is legal.

@JeffGohlke Fixed

C#
Possibly crazy, roundabout, and convoluted way to get to the (exact) result - with only variable renames and without any literal "mom" in any of the code.
Reading the "if you take a code block from a post, you take the whole thing" rule very literally probably didn't help - but made it more fun.
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

public class Program
{
    void Main()
    {
        // Step 1
        var n = 3;
        var helloAndGoodbye = "12345678900"
                    .Select((c, i) => new { letter = c, group = i / n })
                    .GroupBy(l => l.group, l => l.letter)
                    .Select(g => string.Join("", g))
                    .ToList();

        // Step 2
        string place = "world";
        string greet = String.Format("Hello {0}!", place);

        // Step 3
        byte[] b1 = System.Text.Encoding.UTF8.GetBytes (greet);
        byte[] b2 = System.Text.Encoding.ASCII.GetBytes (greet);

        // Step 4
        string encryptionKey = "test";
        var md5 = MD5.Create();
        var keyBytes = Encoding.UTF8.GetBytes(encryptionKey);
        byte[] encryptionKeyBytes = md5.ComputeHash(keyBytes);

        // Step 5
        string strName = md5.GetType().Name;
        if(strName == "Person")
        {
            //My Code
        }

        // Step 6
        string HashAlgorithm = new string(strName.Take(n).ToArray());

        // Step 7
        int previousYear = DateTime.Now.AddYears(-1).Year;

        // Step 8
        string myString = previousYear.ToString();

        // Step 9
        string totallyRandomString = new string(myString.Take(n).ToArray());

        // Step 10
        int myInt = System.Convert.ToInt32(totallyRandomString);

        // Step 11
        int x = myInt << 1 + 1;

        // Step 12
        PasswordDeriveBytes DerivedPassword =
                    new PasswordDeriveBytes(place, b1, HashAlgorithm, x);
        byte[] KeyBytes = DerivedPassword.GetBytes(32);

        // Step 13
        string base64 = Convert.ToBase64String(KeyBytes);
        byte[] bytes = Convert.FromBase64String(base64);

        // Step 14
        var split = base64.Split('/');
        var last = split[split.Length -1];
        var prev = split[split.Length -2];

        // Step 15
        string truncatedToNLength = new string(last.Take(n).ToArray());

        // Step 16
        Regex rgx = new Regex("[^a-zA-Z0-9 -]");
        greet = rgx.Replace(greet, "");

        // Step 17
        var newString = greet.Replace(place.ToString(), truncatedToNLength);

        // Step 18
        var searchStr = newString.ToLower();
            searchStr = searchStr.Trim();

        // Step 19
        Console.WriteLine(searchStr);
    }
}

.NET Fiddle
http://dotnetfiddle.net/PbjhPn
http://dotnetfiddle.net/bg20wb (with redundant lines in code blocks removed)
Short explanation
Basically, we get "Hello world!" from a simple string format. Now we need "mom" to replace it. For that, we use the Base64 encoded result of running 804 iterations of PBKDF1 using MD5 with "world" as password and "Hello world!" as salt. That yields a string "ciSf5cCls1l/MoM...". We extract that "MoM" and use it as a replacement for "world". Then we clean up the string.
How do we get to 804? The previous year clipped to three characters (= "201"), and then multiplied by 4.
Long explanation and attributions
1: We start with a bit of rule-following overkill.
The integer 3 is a very very important constant in this program.
Here we assign that integer to n. We must include the entire block from the source. It may be redundant, but it will compile just fine, as long as we rename the split variable that we'll be needing later. Source
Replaced variable names:
split              > helloAndGoodbye

2: Set up starting string ("Hello world!"). Source
This is a very personal message to our mom. So we obviously need some cryptography to deal with those NSA types. For that, we'll need some parameters, which we prepare now.
3: Convert greet ("Hello world!") to byte array for salting. Source
myString           > greet

4: Although we're using cryptography, we don't actually need to instantiate the MD5 class. We do, however, need the string "MD5" assigned for one of our parameters to be used further down - and that's not easy to find in usable code. So we'll take another... "shortcut"... Once again, entire code block included as per rules, although we only need the second line. Source
5: Now we need the name of the type of the md5 variable (MD5CryptoServiceProvider). The if is yet another redundancy. Source
entity             > md5

6: Get the first 3 (ooh, there's our constant!) characters of the type name. Source
s                  > strName
truncatedToNLength > HashAlgorithm

7: Code-trolling: Using DateTime.Now would mean this would only work until 2019. To make it a bit more future proof, we use the previous year. Then it will work until 2020 ;-)Source
8: Convert our previousYear to string. Source
myInt              > previousYear

9: Hey, code reuse! ;-) Get the first 3 (our constant!) characters of our year. Source
s                  > myString
truncatedToNLength > totallyRandomString

10: Aaaaaaaand... convert the result back to integer. Source
myString           > totallyRandomString

11: Eric Lippert makes every answer better. Multiply by 4 in a roundabout way. Source
y                  > myInt

12: Send place (password) and greet (salt) through PBKDF1 using MD5 with x (which is now 201*4 = 804) iterations. Source
Password           > place
SaltValueBytes     > b1
PasswordIterations > x

13: Jon Skeet also makes every answer better. Convert our derived password to base 64. We throw out the bytes array. Source
bytes (first occurrence) > KeyBytes

14: What a crazy random happenstance! We now have a base64 with "MoM" in it. Conveniently, right before "MoM" is a single '/'. So split the string with that character as delimiter: Source
filePath          > base64

15: Hey, our favorite piece of code reuse tape! Get the first 3 (constant!) letters of last. Source
s                 > last

16: Remove "!". Source
str               > greet

17: MoM is our world - so make the string reflect that (replace "world" with "MoM"). Source
someTestString   > greet
someID           > place
sessionID        > truncatedToNLength

18: Finally, convert to lower case. Trim for good measure (or possibly because it's part of the duct tape block). Source
wordToSearchReplacemntsFor > newString

19: Output to console. Source
_surface         > searchStr

A bit of "bonus material"/commentary

At first I tried every combination of built-in cryptographic hashes (each combined with HMAC) and inputs ("world", "Hello world!", "Hello world", "hello world" etc.) to see if something would miraculously give a usable output to derive "mom" from - before taking the easy route of just looking for a number of iterations of PDKDB1 (or 2) that would be useful.
Wasn't quite happy with the use of the year as input for the 201*4 = 804 iterations. At first I tried to find some useful code for HttpStatusCode.Created (201) to use as input - with a "troll excuse" along the lines of "we've created our 'Hello world!' string, so a good practice would be to use a 'Created' status code" here. Unfortunately, I never found a usage of the HttpStatusCode enumeration that didn't introduce a dependency on most of the ASP.NET WebAPI framework.
The start of the code (the "Hello world!" string format) was never looked at again after I first added it. If I had, yeah, I might have realized that the assignment of place was actually in a different block in the source - so I could have simply assigned my derived "mom" to place rather than using "world" and later replacing it. Ah well.

+1 for "mom is our world", and "Lippert and Skeet make every answer better".

"Trim for good measure..." gave me a good chuckle.

Befunge 98

var abc = function(){};
display: table-*
+
, new {area = ""}
byte z = x + y;
"1,23,4"
String[] temp = data.split("\\s+\\^,?\"'\\|+");
List<Set<Integer>> foo;
: base(name)
10001.10010110011
[5326, 4223, 1204]
https://stackoverflow.com/q/23044400/1896169
Runnable prs = new Runnable() {
    public void run() {
        Document doc = null;
        try {
            doc = Jsoup.connect("http://play.radio.com/").get();

        } catch (IOException e) {

            e.printStackTrace();
        }
        parser.postDelayed(prs, 10000);
    }
};

$selector.append("somestuff");
-new Date().getTimezoneOffset()/60;
https://stackoverflow.com/a/8928476/1896169
 [0000] push        ebp
 [0001] mov         ebp,esp
 [0003] push        edi
 [0004] push        esi
 [0005] push        ebx
 [0006] sub         esp,1Ch
 [0009] xor         eax,eax
 [000b] mov         dword ptr [ebp-20h],eax
 [000e] mov         dword ptr [ebp-1Ch],eax
 [0011] mov         dword ptr [ebp-18h],eax
 [0014] mov         dword ptr [ebp-14h],eax
 [0017] xor         eax,eax
 [0019] mov         dword ptr [ebp-18h],eax
*[001c] mov         esi,1
 [0021] xor         edi,edi
 [0023] mov         dword ptr [ebp-28h],1
 [002a] mov         dword ptr [ebp-24h],0
 [0031] inc         ecx
 [0032] mov         ebx,2
 [0037] cmp         ecx,2
 [003a] jle         00000024
 [003c] mov         eax,esi
 [003e] mov         edx,edi
 [0040] mov         esi,dword ptr [ebp-28h]
 [0043] mov         edi,dword ptr [ebp-24h]
 [0046] add         eax,dword ptr [ebp-28h]
 [0049] adc         edx,dword ptr [ebp-24h]
 [004c] mov         dword ptr [ebp-28h],eax
 [004f] mov         dword ptr [ebp-24h],edx
 [0052] inc         ebx
 [0053] cmp         ebx,ecx
 [0055] jl          FFFFFFE7
 [0057] jmp         00000007
 [0059] call        64571ACB
 [005e] mov         eax,dword ptr [ebp-28h]
 [0061] mov         edx,dword ptr [ebp-24h]
 [0064] lea         esp,[ebp-0Ch]
 [0067] pop         ebx
 [0068] pop         esi
 [0069] pop         edi
 [006a] pop         ebp
 [006b] ret

https://stackoverflow.com/q/23569160/1896169
def logme(func):
    def wrapped(*args):
        for arg in args: print str(arg)
        func(*args)
    return wrapped

@logme
def my_func(*args):
    res = 1
    for arg in args :
        print "Multiplying %s by %s" % (arg, res)
        res*=arg
    print res
    return res

My code:
var abc = function(){};
display: table-*
display: table-*
display: table-*
display: table-*
display: table-*
display: table-*
display: table-*
display: table-*
+
+
+
+
+
+
+
, new {area = ""}
byte z = x + y;
byte z = x + y;
byte z = x + y;
byte z = x + y;
byte z = x + y;
byte z = x + y;
byte z = x + y;
byte z = x + y;
display: table-*
+
+
+
+
+
+
+
+
, new {area = ""}
"1,23,4"
  String[] temp = data.split("\\s+\\^,?\"'\\|+");
List<Set<Integer>> foo;
"1,23,4"
+
: base(name)
: base(name)
, new {area = ""}
, new {area = ""}
10001.10010110011
10001.10010110011
10001.10010110011
+
+
+
, new {area = ""}
"1,23,4"
  String[] temp = data.split("\\s+\\^,?\"'\\|+");
"1,23,4"
, new {area = ""}
"1,23,4"
[5326, 4223, 1204]
Runnable prs = new Runnable() {
    public void run() {
        Document doc = null;
        try {
            doc = Jsoup.connect("http://play.radio.com/").get();

        } catch (IOException e) {

            e.printStackTrace();
        }
        parser.postDelayed(prs, 10000);
    }
};
"1,23,4"
$selector.append("somestuff");
$selector.append("somestuff");
-new Date().getTimezoneOffset()/60;
: base(name)
10001.10010110011
10001.10010110011
10001.10010110011
+
+
+
 [0000] push        ebp
 [0001] mov         ebp,esp
 [0003] push        edi
 [0004] push        esi
 [0005] push        ebx
 [0006] sub         esp,1Ch
 [0009] xor         eax,eax
 [000b] mov         dword ptr [ebp-20h],eax
 [000e] mov         dword ptr [ebp-1Ch],eax
 [0011] mov         dword ptr [ebp-18h],eax
 [0014] mov         dword ptr [ebp-14h],eax
 [0017] xor         eax,eax
 [0019] mov         dword ptr [ebp-18h],eax
*[001c] mov         esi,1
 [0021] xor         edi,edi
 [0023] mov         dword ptr [ebp-28h],1
 [002a] mov         dword ptr [ebp-24h],0
 [0031] inc         ecx
 [0032] mov         ebx,2
 [0037] cmp         ecx,2
 [003a] jle         00000024
 [003c] mov         eax,esi
 [003e] mov         edx,edi
 [0040] mov         esi,dword ptr [ebp-28h]
 [0043] mov         edi,dword ptr [ebp-24h]
 [0046] add         eax,dword ptr [ebp-28h]
 [0049] adc         edx,dword ptr [ebp-24h]
 [004c] mov         dword ptr [ebp-28h],eax
 [004f] mov         dword ptr [ebp-24h],edx
 [0052] inc         ebx
 [0053] cmp         ebx,ecx
 [0055] jl          FFFFFFE7
 [0057] jmp         00000007
 [0059] call        64571ACB
 [005e] mov         eax,dword ptr [ebp-28h]
 [0061] mov         edx,dword ptr [ebp-24h]
 [0064] lea         esp,[ebp-0Ch]
 [0067] pop         ebx
 [0068] pop         esi
 [0069] pop         edi
 [006a] pop         ebp
 [006b] ret
10001.10010110011
+
: base(name)
, new {area = ""}
"1,23,4"
List<Set<Integer>> foo;

"1,23,4"
+
10001.10010110011
10001.10010110011
10001.10010110011
+
+
+
, new {area = ""}
, new {area = ""}
def logme(func):
    def wrapped(*args):
        for arg in args: print str(arg)
        func(*args)
    return wrapped

@logme
def my_func(*args):
    res = 1
    for arg in args :
        print "Multiplying %s by %s" % (arg, res)
        res*=arg
    print res
    return res

This works because the first v (in the first line) sends the IP downward. So we are basically executing this program:
dddddddd+++++++,bbbbbbbbd++++++++," L"+::,,111+++," ","[R           }"$$-:111+++             *                            1+:,"L "+111+++,,d     @

Which does this:

dddddddd+++++++, pushes 104 and prints
bbbbbbbbd++++++++, pushes 101 and prints
" L"+, pushes 32 and the ascii value of L, then adds them, duplicates twice, and prints twice
To the one that was duplicated, 111+++, adds 3 and prints
" ", prints a space. "[R           }"$$-:111+++ pushes a 9 and duplicates it, then adds 3 to the top value
* multiplies the top two values
1+:, increments that number, duplicates, and prints
"L "+111+++, prints o. , prints the m from earlier, and d     @ pushes 13 (which does nothing) and ends the program.

And yes. I actually did run this and it outputs hello mom

Java
import java.util.*;

public class HelloMom {

     public static void main(String[] args) {
         Hashtable<String, String> ht = new Hashtable<String, String>();

        ht.put("Answer", "42");
        ht.put("Hello", "World");    // First value association for "Hello" key.
        ht.put("Hello", "Mom");      // Second value association for "Hello" key.

        for (Map.Entry<String, String> e : ht.entrySet()) {
          System.out.println(e);
        }
    }
}

Output
Answer=42
Hello=Mom

There is a pesky = in there, but this is the best I could do
https://stackoverflow.com/a/1050075/573421

Remarkable find!

Actually I searched a bit before starting the challenge and did not expect to find complete solutions like this in one post. Nice that you found one anyway!

C
Most of this code comes from an answer to Find the beginning of the first word that is a palindrom [sic] posted by BLUEPIXY, which outputs the word mom. At lines 21 and 22, the hello is printed by a code snippet at the end of an answer to printf(“%%%s”,“hello”) by user142019 (who fortunately added a semicolon at the end), and the space between the words comes from an answer to How to print space with padding in c by M Oehm.
Output:
%hello        mom

I wasn't able to eliminate the extra spaces or the percent character, unfortunately :(
Source code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int isPalindrome(const char *str){
    const char *front, *back;
    front=str;
    back =str + strlen(str)-1;
    for(;front<back;++front,--back){
        while(!isalpha(*front))++front;//isalnum?
        while(!isalpha(*back))--back;
        if(front > back || tolower(*front)!=tolower(*back))
            return 0;
    }
    return 1;
}

int main(){
    const char *data="Hello mom and dad, how is it going?";
    char *p, *src;
    printf("%%%s", "hello");
    printf("        ");
    p=src=strdup(data);
    for(;NULL!=(p=strtok(p, " \t\n,.!?"));p=NULL){
        if(isPalindrome(p)){
            printf("%s\n", p);
            break;
        }
    }
    free(src);
    return 0;
}

Java
import java.io.ByteArrayOutputStream;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Random;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author LH
 */
public class Kopierpaste
{

    //https://stackoverflow.com/questions/15182496/why-does-this-code-using-random-strings-print-hello-world
    //randomizer code for the first String
    public static String randomString(int i)
    {
        Random ran = new Random(i);
        StringBuilder sb = new StringBuilder();
        for (int n = 0;; n++)
        {
            int k = ran.nextInt(27);
            if (k == 0)
            {
                break;
            }

            sb.append((char) ('`' + k));
        }

        return sb.toString();
    }

    public static void main(String[] nope)
    {
        //catching a System.out() based code snippet
        //https://stackoverflow.com/questions/4183408/redirect-stdout-to-a-string-in-java
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        System.setOut(new PrintStream(baos));
        //same as randomizer
        //getting hello, world inside a ByteArray
        System.out.println(randomString(-229985452) + " " + randomString(-147909649));

        //undo the redirecct of System.out()
        //https://stackoverflow.com/questions/4183408/redirect-stdout-to-a-string-in-java && https://stackoverflow.com/a/14716148/1405227
        System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));

        //stringify the out of first part
        //https://stackoverflow.com/questions/4183408/redirect-stdout-to-a-string-in-java
        String text = baos.toString();

        //getting rid of the world part
        //https://stackoverflow.com/a/17008136/1405227
        String firstWord = text.substring(0, text.indexOf(' '));

        //needing the word Mom
        //https://stackoverflow.com/a/8341513/1405227
        //history -> a
        String[] a = new String[]
        {
            "hey", "you", "Mom"
        };

        //stitching the array together in a certain fashion ([elem1, elem2, elem3]
        //https://stackoverflow.com/a/2822736/1405227
        //myarray->a
        String b = Arrays.toString(a);

        //getting rid of the ,s
        //https://stackoverflow.com/a/7552284/1405227 stripping annoying bullcrap out
        //result ->c
        //yourString ->b
        String c = b.replaceAll("[-+.^:,]", "");

        //getting the Mom] part
        //https://stackoverflow.com/a/15317037/1405227
        //sentence -> c
        String lastToken = c.replaceAll(".* ", "");

        //getting rid of more crap
        //https://stackoverflow.com/a/18599016/1405227
        //message -> lastToken
        lastToken = lastToken.replaceAll("\\W", "");

        //finally out
        //https://stackoverflow.com/a/19393222/1405227
        //name -> firstWord
        //income -> lastToken
        System.out.println(firstWord + " " + lastToken);
    }
}

Documentation  and source links are in the comments ( starting with // )
clean list of sources used

https://stackoverflow.com/questions/15182496/why-does-this-code-using-random-strings-print-hello-world
https://stackoverflow.com/questions/4183408/redirect-stdout-to-a-string-in-java
https://stackoverflow.com/a/14716148/1405227
https://stackoverflow.com/a/17008136/1405227
https://stackoverflow.com/a/2822736/1405227
https://stackoverflow.com/a/7552284/1405227
https://stackoverflow.com/a/15317037/1405227
https://stackoverflow.com/a/18599016/1405227
https://stackoverflow.com/a/19393222/1405227

+1. I wanted to go for the random hello world approach but got bored and did it more straightforwardly. nicely done

yeah, remembered that, and to get it out i had to abuse the system.out redirect hax. took me a while to get the Mom with my approach and some nasty regexes. but luckily we got google to dig around SO

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


text:
Cheap, Fast, Good - Common Factor (Greatest)
Inspired by Cheap, Fast, Good, we're going to implement an algorithm which has exactly two of them.
The Math
Given two nonzero integers a and b, the GCF d is the largest integer that divides both a and b without remainder. Bézout coefficients are pairs of integers (x, y) such that ax + by = d. Bézout coefficients are not unique. For example, given:
a = 15, b = 9

We have
d =  3
x =  2
y = -3

Since 15*2 + 9*(-3) = 30 - 27 = 3.
A common way to calculate the GCF and a pair of Bézout coefficients is using Euclid's Algorithm, but it's by no means the only way.
The Code
Your program should take two integers as inputs. It should output/return the greatest common factor and one pair of Bézout coefficients.
Example input:
15 9

example output
3 (2, -3)

The output can be in any order and format, but it should be clear which is the GCF and which are the coefficients.
The Underhanded
Your program has the potential to be cheap, fast, and good. Unfortunately, it can only be two of those at once.

When it's not cheap, the program should use an excessive amount of system resources.
When it's not fast, the program should take an excessive amount of time.
When it's not good, the program output should be wrong.

The program should be able to do (well, not do) all three. Which is does when is up to you- it could be based on the time, the compiler, which input is larger, etc. Some additional notes:

Your program should not be obviously underhanded and should pass a cursory inspection. I'd be a little suspicious if you implemented three separate algorithms.
In the cheap case, "excessive amount of system resources" is anything that would slow down other programs. It could be memory, bandwidth, etc.
In the fast case, "excessive time" means relative to how it runs in the cheap and good cases. The program should still finish. The closer you can to "incredibly frustrating but not frustrating enough to stop the program" the (funnier and) better.
In the good case, the output shouldn't be obviously wrong  and should pass a cursory inspection. I'd be very suspicious if it gave me a GCF of "2 anna half".

This is a popularity contest, so most upvotes wins!
EDIT
To clarify, I'm looking for programs that can be "fast and cheap" and "cheap and good" and "fast and good" in different cases, not ones that just do one of them.

It's nice to have an original challenge like this. :)

Does the program have to be exactly two at once or is it OK if it's only good in some cases and cheap and fast (but not good) in others?

I'm looking for three cases, with exactly two in each.

If the program is not good it's output should be incorrect? Then what is the point of calculating anything correctly?

@RicardoA Because that's only one of the three cases, and this is an underhanded contest, so you're trying to hide the fact that in one of the three cases, it's incorrect.

@Hovercouch I understand the rules but by looking at some of the answers the fact that the output is wrong is not hidden which makes it not underhanded.

I'm voting to close this question as off-topic because it's an [underhanded] challenge, which was on-topic a year ago, but is now off-topic by community consensus.

C
It's cheap and fast. You get gcd in the blink of an eye. However the guy who did it had no clue about that "Bézier co-something" so he simply divided a and b by gcd.
(to make things worse, at that point a and b are pretty far from their initial value because of the algorithm he wisely chose)
int main(int argc, char **argv){
    unsigned int a, b, tmp;
    a = (unsigned int)atoi(argv[1]);
    b = (unsigned int)atoi(argv[2]);
    for (tmp = 0; ((a | b) & 1) == 0; ++tmp){
        a >>= 1;
        b >>= 1;
    }
    while ((a & 1) == 0)
        a >>= 1;
    do {
        while ((b & 1) == 0)
            b >>= 1;
        if (a > b){
            unsigned int t = b;
            b = a;
            a = t;
        }
        b = b - a;
    } while (b != 0);
    tmp = a << tmp;
    printf("%u, (%u,%u)", tmp, a/tmp, b/tmp);
    return 0;
}

C#
This calculates the Bézout coefficients. I used the Extended Euclidean algorithm.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter your first number.");
            int firstNumber = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter your second number.");
            int secondNumber = Convert.ToInt32(Console.ReadLine());

            double max = Math.Max(firstNumber, secondNumber);
            double min = Math.Min(firstNumber, secondNumber);
            double s1 = 1;
            double s2 = 0;
            double t1 = 0;
            double t2 = 1;
            double quotient = 0;
            double remainder = 0;
            double[] remainders = new double[0];

            int i = 0;
            do
            {
                quotient = (int)(max / min);
                remainder = max - quotient * min;
                if (remainder > 0)
                {
                    Array.Resize(ref remainders, remainders.Length + 1);
                    remainders[i] = remainder;

                }
                if (i % 2 == 0)
                {
                    s1 = s1 - quotient * s2;
                    t1 = t1 - quotient * t2;
                }
                else
                {
                    s2 = s2 - quotient * s1;
                    t2 = t2 - quotient * t1;
                }

                if (i == 0)
                {
                    max = min;

                }
                else if (i >= 1)
                {
                    max = remainders[i - 1];
                }

                min = remainder;
                i++;
            } while (remainder > 0);

            Console.WriteLine((remainders[remainders.Length - 1]).ToString() + " " + (i % 2 == 0 ? "(" + s1 + "," + t1 + ")" : "(" + s2 + "," + t2 + ")"));
        }

    }
}

When is this expensive, when is it slow, and when is it bad?

@undergroundmonorail I will put those values when I have the chance.

Javascript
Not cheap
Uses a lot of system resources.
function gcf(a, b) {
    var result = 1;
    for (var i = 1; i < 100000000 * a && i < 100000000/* Do it a few extra times, just to make sure */ * b; i++) {
        if (a % i == 0 && b % i == 0) {
            result = i;
        }
    }
    return [result, a / result, b / result];
}

Not fast
Use a callback, just as an extra failsafe.
function gcf(a, b) {
    setTimeout(function() {
        var result = 1;
        for (var i = 1; i < 2 * a && i < 2 * b; i++) {
            if (a % i == 0 && b % i == 0) {
                result = i;
            }
        }
        alert(result.toString() + " (" + (a / result).toString() + ", " + (b/result).toString() + ")");
    }, 10000);
}

Not good
Strict limit of gcf(10, 10), just to safe disk space.
function gcf(a, b) {
    var gcfTable = [[1,1,1,1,1,1,1,1,1,1],[1,2,1,2,1,2,1,2,1,2],[1,1,3,1,1,3,1,1,3,1],[1,2,1,4,1,2,1,4,1,2],[1,1,1,1,5,1,1,1,1,5],[1,2,3,2,1,6,1,2,3,2],[1,1,1,1,1,1,7,1,1,1],[1,2,1,4,1,2,1,8,1,2],[1,1,3,1,1,3,1,1,9,1],[1,2,1,2,5,2,1,2,1,10]];
    return [gcfTable[a - 1][b - 1], a / gcfTable[a - 1][b - 1], b / gcfTable[a - 1][b - 1]];
}

When is it cheap and fast but not good?

This answer is cheap, good, but not fast.

the challenge is to write a program that is each of "not cheap", " not fast ", and " not good " in different circumstances.

Answer fixed...

Perl 5
#!/usr/bin/perl
use strict;
use warnings;

$SIG{__WARN__} = sub { exit };

print(<<INTRO);
Greatest Common Factor

    goodbye           -- exit the application
    [number] [number] -- compute gcf of both numbers

INTRO

main();
sub main {
    print "> ";
    chomp(local $_ = <STDIN>);

    print "Have a good one.\n" and exit if /goodbye/;

    my @nums = /(-?\d+)/g;
    print "invalid input\n" and return main() if @nums != 2;

    my ($gcf, @coeff) = gcf(@nums);
    unless (grep abs($_) > 99, $gcf, @coeff) {
        select $\,$\,$\, rand for 1..10;
    }

    local $" = ", "; #"
    print "gcf(@nums) = $gcf\n";
    print "bezout coefficients: @coeff\n";
    main();
}

sub gcf {
    my ($x, $y) = @_;

    my @r = ($x, $y);
    my @s = (1, 0);
    my @t = (0, 1);

    my $i = 1;
    while ($r[$i] != 0) {
        my $q = int($r[$i-1] / $r[$i]);
        for (\@r, \@s, \@t) {
            $_->[$i+1] = $_->[$i-1] - $q * $_->[$i];
        }
        $i++;
    }

    return map int(1.01 * $_->[$i-1]), \@r, \@s, \@t;
}

__END__

Not cheap: main() is called recursively (filling up the stack) until a "deep recursion" warning is fired by perl which will quit the application due to the __WARN__ handler.
Not fast: When the gcf() algorithms returns correct results, the code just hangs on for a few seconds (select() in main()).
Not good: All results above 99 (or below -99) are incorrect.
All in all not so creative; looking forward to more elegant answers.

Python
#!/usr/bin/python
def gcd(x, y):
    l = 0
    if x < y:
        l = x
    else:
        l = y
    for g in reversed(range(l + 1)):
        if x%g == 0 and y%g == 0 and g > 1:
            return g
        else:
            if g == 1:
                return 1

def bezout(x,y,g):
    c1 = 0
    c2 = 0
    k = 0
    if x < y:
        k = y
    else:
        k = x
    for _k in range(k):
        tc = (gcd(x,y) - x*_k)%y
        if tc == 0:
            c1 = _k
            c2 = (gcd(x,y) - y*_k)/x
            return (c1, c2)

gc = gcd(15,9)
be, bf = bezout(9,15,gc)
print("%d (%d, %d)" % (gc, be, bf))

This is cheap and fast but it is bad in the fact that the range is capped at the largest input so it may not find a pair of coefficients.
Good puzzle.


text:
Ordering an integer array - Lowest to Highest - No Tools Challenge
Here's the challenge:
Order an Array from the Lowest to the Highest digit from a number, which is conveniently represented in an array. The trick here is that you cannot use any array methods, nor other sorts of loopholes. You have to stick to the basics (Arrays, Mathematical Operators /not Math Class/, no recursion. You can use any variable type of your chosing (eg: String, int), and evidently repetitive cicles, you can't however use "advanced" expressions, such as ArrayList or ParseInt for Java)
For an user input of 2014, the output should be 0124 Yes, the 0 must be represented
Scoring Method
Simply a codegolf challenge, shortest code wins.
Origin of the challenge:
I've been reading quite a bit of codegolf for a while, and decided to create a challenge based on an issue that I had with java to order the digits of a number. I did manage to get a solution, but I wasn't quite pleased with it (it took a significant ammount of bytes which I wanted to avoid), I am interested in creative, short awnsers to counter my own =)

Just to clarify, the program must be valid for any integer, 2014 was an example.

And evidently, any downvote without a plight explanation is the same as flipping me the finger, which I find rude.

How is the array defined?  Is it user input or defined in the program, and if so, how do you want to count the bytes in int[] array = {INSERT AN UNKNOWN NUMBER OF BYTES HERE}?

Can't speak for anyone else, but in my opinion, as code-golf sorting challenges go this is really boring. And thinking that recursion is not "basic" suggests that you may be just beginning to program; believe me, it is on the same level of the basic tool box as looping. Moreover, the limitations and scoring modifiers make it look like you are trying to use CodeGolf SE as a mechanical turk willing to do your homework. And people can react badly to that impression no matter the truth or falsity of it.

Scoring item 1 and 2 are unnecessary. For 3 and 4, I highly doubt any golfed submission will reach over 500 bytes. 5 seems strange and put in there for no reason, and 6 makes very little sense at all - why does Java get priority over, say, C++? 7 just begs for someone to answer "foobarbaz in Perl, it doesn't work but I still get the first submission bonus" or something. Furthermore, typically challenges here do not have deadlines.

I'm not a professsional programmer, but I'm not either a begginer (I do know how to work with, and prefer to use recursion). This was however an issue I had when starting out. Regarding kitcar2000's comment, I made it that way so it would be a four digit example, with a number that contained a 0 (to explain should it occur). As per "asking others to do my homework", they are partially correct, this was once part of my homework, and that's why I'm interested in looking at solutions different from mine (And mine was in java, hence why that scoring bonus)

@Doorknob What would you recommend as a scoring method?

A more ideal method would be plain code-golf: shortest code wins. You may also want to clarify what "the basics" are - that's extremely underspecified at the moment.

I've edited the Question, what do you think of it?

I don't understand what you're asking for. You say it's about sorting an integer array, and then give an example where you sort the digits of a single decimal integer. You prohibit the use of "array methods" but allow the use of arrays. Also, how could the use of string variables possibly help with the task of sorting an array of integers? And what is an "evidently repetitive cicle"?

Oh screw this, I was about to hit the submit button with a SleepSort and it was closed.

The original proposition was a sole number, which was then turned into an array composed of the digits (2014 -> 2,0,1,4)

In Racket, without explicit recursion :-P
(define Y (lambda (f) ((lambda (x) (x x)) (lambda (x) (lambda (y) ((f (x x)) y))))))
(define a (Y (lambda (f) (lambda (c) (cond ((null? c) c)
                                           ((null? (cdr c)) c)
                                           ((> (car c) (cadr c))
                                            (f (cons (cadr c) (cons (car c) (cddr c)))))
                                           (#t (cons (car c) (f (cdr c)))))))))
(define b (Y (lambda (f) (lambda (c) (let ((s (a c))) (if (equal? s c) c (f s)))))))

Call:
(b '(2 0 1 4))

where

Y is the Y-Combinator
a is one iteration of Bubble Sort
b is the bubble sort algorithm

Guess I can't really accept other awnsers