share
Stack OverflowCode Bowling on "Hello World"?
[+53] [18] Jonathan Sampson
[2010-01-12 20:30:52]
[ anti-golf code-bowling ]
[ http://stackoverflow.com/questions/2052137/code-bowling-on-hello-world ] [DELETED]

Contrary to the popular code-golf challenges which demonstrate the genius of many regulars here, I'd like to see that genius illustrated in an antithetical fashion.

The challenge is to successfully perform "Hello World" with special focus on over-complicating matters. Not verbosity, not obscurity, just pure sloppiness/over-complication.

Think of The Daily WTF [1] as inspiration.

function mb2($o){return (int)($o*2);}
$alphabet = str_split("abcdefghijklmnopqrstuvwxyz");
$alphabet[] = " ";
$output = "";
for ($i = 0; $i <= 10; $i++)
  switch (mb2($i*.5)) {
    case  0: $output = $output . $alphabet[07]; break;
    case  1: $output = $output . $alphabet[04]; break;
    case  2: $output = $output . $alphabet[11]; break;
    case  3: $output = $output . $alphabet[11]; break;
    case  4: $output = $output . $alphabet[14]; break;
    case  5: $output = $output . array_pop($alphabet); break;
    case  6: $output = $output . $alphabet[22]; break;
    case  7: $output = $output . $alphabet[14]; break;
    case  8: $output = $output . $alphabet[17]; break;
    case  9: $output = $output . $alphabet[11]; break;
    case 10: $output = $output . $alphabet[03]; break;
  }

print $output; // hello world
Are you competing against the IOCC? - SLaks
I suspect the BF implementation is a good starting point. - Anon.
(2) Apparently my request wasn't properly understood. - Jonathan Sampson
(23) This is not a duplicate. He's asking for evil code in normal languages, not normal code in evil languages. Please reopen. - SLaks
Perhaps my new question makes more sense. - Jonathan Sampson
(6) I don't think this should have been closed. He wasn't asking for the same thing. This is a fun question, the other was not. - dicroce
GNU has a very long Hello World (which, of course, can read mail) in c as an exemplar of their coding standards: gnu.org/software/hello/hello.html . But this is not a good question for SO... - dmckee
(10) This question makes no sense. If you were asking for the longest or most obfuscated, it would make more sense. But you specifically don't want verbose or obscure code, just messy code. What's the point of that? - gnovice
(2) Does code.google.com/p/hello--world count? I don't really get the requirements here. - Michael Myers
gnovice, sit down and try to come up with a messy solution. You'll see it's not as easy as you would initially think. - Jonathan Sampson
(8) -1: I don't see what people would learn from this question, that isn't covered (deeply) in "Obfuscated X Code" competitions. - Chip Uni
mmyers, do you not recall ever seeing something that just had ignorance oozing off of it? That's what I'm seeking, but an ignorance constructed by pure genius. - Jonathan Sampson
Oh yeah... I think I once saw a website devoted to that very subject... if I could only remember the name. - Michael Myers
The Daily WTF illustrates what I was interested in to a degree. - Jonathan Sampson
(1) I think part of the problem here is that "messy" and "sloppy" are subjective terms that mean different things to different people. For example, I would categorize the sample code you added to the question as "verbose" or "obfuscated", not "sloppy". It actually looks fairly neat and well-organized, just overly-complicated. - gnovice
@gnovice "Overly-complicated" was what I was aiming for. Nice choice of words. - Jonathan Sampson
(2) I think this may be a first ... I voted to reopen. Knowing full well that this one's an open/close war, but it is (a) programming-related, (b) a sincere challenge (akin to code golf) and (c) actually can provide education, albeit in subtle ways, if answerers actually meet the challenge. Finally, it being CW clinched my reopen vote. - John Rudy
(1) I don't see the relevance to TDWTF. You want to use those programs to inspire "genius"? - Roger Pate
I voted to reopen out of curiosity. But I do agree that unlike code-golf (which has a definite metric [characters of source]), this cannot (you cannot possibly write "the longest possible program that does X") - Jimmy
@Roger Inspire genius? No. This is for fun. I'm curious how difficult it can be to follow somebody's operation. Something so messed up it would have taken a genius to write :) - Jonathan Sampson
(3) I think this isn't too bad, and there might be even something to learn here, so I'm casting the fifth reopen vote. - balpha
@balpha: Thanks. (I already voted to reopen the first time, so I couldn't) - SLaks
[+118] [2010-01-13 14:43:18] balpha [ACCEPTED]

You asked for it. Python:

# Copyright (c) 1999 - 2010
# Large Company, Inc. ("THE COMPANY")
# 
# Redistribution and use in source and binary forms, with or without 
# modification, are permitted provided that the following conditions are 
# met: 
# 
# 1. Redistributions of source code must retain the above copyright 
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright 
#    notice, this list of conditions and the following disclaimer in the 
#    documentation and/or other materials provided with the distribution. 
# 
# THIS SOFTWARE IS PROVIDED BY THE COMPANY AND CONTRIBUTORS "AS IS" AND 
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COMPANY OR CONTRIBUTORS BE 
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 
# THE POSSIBILITY OF SUCH DAMAGE. 

"""This program outputs an enthusiastic "Hello World" in english.
"""

# FIXME: Where are the unit tests for this? QA called and says we
# can't ship this without tests. Also, while writing documentation
# may be boring, you can't expect everyone to understand all this!
# Go ahead and write some docstrings! -- O.D. 2004/7/22

class Expression(object):
    def get_value(self, **kwargs):
        """get_value returns the value of this Expression.

        Any keyword arguments that the method receives should
        be passed on to the get_value methods of possibly called
        subexpressions, even if this method does not handle
        them.

        This method must be reimplemented by the subclass."""

        raise NotImplementedError

class Word(Expression):
    def __init__(self, value):
        self.value = value

    def get_value(self, **kwargs):
        return self.value

class Sentence(Expression):
    def __init__(self, expressions, punctuation = "."):
        self.expressions = list(expressions)
        self.punctuation = punctuation

    def get_value(self, separator = " ", **kwargs):
         mainpart = separator.join(
                    subexpression.get_value(separator = separator, **kwargs)
                    for subexpression in self.expressions
                    )

         if len(mainpart) > 0:
             capitalized = mainpart[0].upper() + mainpart[1:]
         else:
             capitalized = ""

         # FIXME: We're hardcoding "" here. Should we be prepared for
         # languages that require a separator before the punctuation mark?
         # NB: A workaround for now would be adding an empty word
         return "".join((capitalized, self.punctuation))

class Hello(Word):

    # FIXME: We should be prepared for languages where "hello" is
    # represented by more than one word.
    hello_by_language = {"en": "hello", "de": "hallo"}

    def __init__(self, language = "en"):
        super(Hello, self).__init__(self.hello_by_language[language])

class World(Word):

    # FIXME: We should be prepared for languages where "world" is
    # represented by more than one word.
    world_by_language = {"en": "world", "de": "Welt"}

    def __init__(self, language = "en"):
        super(World, self).__init__(self.world_by_language[language])

class HelloWorld(Sentence):
    def __init__(self, punctuation, language):
        hello = Hello(language)
        world = World(language)
        super(HelloWorld, self).__init__([hello, world], punctuation)

class EnthusiasticHelloWorld(HelloWorld):
    def __init__(self, language):

        # FIXME: We should be prepared for languages where enthusiasm
        # is not expressed with an exclamation mark.
        super(EnthusiasticHelloWorld, self).__init__("!", language)

def main():
    english_enthusiastic_hello_world = EnthusiasticHelloWorld("en")
    print english_enthusiastic_hello_world.get_value()

if __name__ == "__main__":
    main()

(35) "We should be prepared for languages where enthusiasm is not expressed with an exclamation mark." As well as those like Spanish, where there is double-punctuation (pre- and post-expression). +1, love it. - John Rudy
@John Rudy: Yeah, I was thinking about the spanish punctuation, but the code had enough FIXMEs already :-) - balpha
(1) You win for the day. - Scott
And what about languages with a different word order? When I ask Google to translate it to Chinese it's clearly doing World hello. - Loren Pechtel
(4) +1 for a good laugh. Love the comments especially... - Thorsten79
So where's the plugin API? I need to support different hello phrases based on gender. - Martin
(10) @Martin: The open source version doesn't include a plugin system. I can connect you to our sales team if you're interested in learning about the commercial version. In that case, hurry up; we're in the process of being bought by Oracle, and rumor has it that they want to kill off "Hello World" because it competes with their RDBMS. - balpha
This reminds me of the hello package in debian repostory. - FUZxxl
(2) You're kidding right? You can write obfuscated code in Python? - Joe Zitzelberger
1
[+63] [2010-01-13 23:23:54] gnibbler

Can someone help me speed up my program. Python is so slow even to run just one line!

python -c '[__import__("os").write(1,__import__("urllib2").urlopen("http://stackoverflow.com/questions/2052137").read()[x+__import__("urllib2").urlopen("http://stackoverflow.com/questions/2052137").read().find("Hello World")]) for x,_ in enumerate("Hello World")]'

(8) +1 Creative. Nice thinking. :) - Jonathan Sampson
(2) Impressive! (15 characters later ...) - Sean Vieira
(4) and boosts stackoverflow.com's traffic stats at the same time - mob
Wait, what? You're loading the entire OS to your Python script? :o - nyuszika7h
AH I just coded this up now but can't add my answer: pastebin.com/TvNsZCDw - robert king
2
[+35] [2010-01-17 04:55:12] chris

I think it's pretty hard to beat the GNU "Hello World" [1] (view the tar to enjoy it in its full glory, including tests, makefile(s!), man, etc.):

/* hello.c -- print a greeting message and exit.

   Copyright 1992, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2005,
   2006, 2007, 2008 Free Software Foundation, Inc.

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

#include <config.h>
#include "system.h"

/* String containing name the program is called with.  */
const char *program_name;

static const struct option longopts[] =
{
  { "greeting", required_argument, NULL, 'g' },
  { "help", no_argument, NULL, 'h' },
  { "next-generation", no_argument, NULL, 'n' },
  { "traditional", no_argument, NULL, 't' },
  { "version", no_argument, NULL, 'v' },
  { NULL, 0, NULL, 0 }
};

/* Different types of greetings; only one per invocation.  */
typedef enum {
  greet_gnu, greet_new, greet_traditional, greet_user
} greeting_type;

/* Forward declarations.  */
static void print_help (void);
static void print_version (void);

int
main (int argc, char *argv[])
{
  int optc;
  int lose = 0;
  const char *greeting_msg = NULL;
  greeting_type g = greet_gnu;

  program_name = argv[0];

  /* Set locale via LC_ALL.  */
  setlocale (LC_ALL, "");

#if ENABLE_NLS
  /* Set the text message domain.  */
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);
#endif

  /* Even exiting has subtleties.  On exit, if any writes failed, change
     the exit status.  The /dev/full device on GNU/Linux can be used for
     testing; for instance, hello >/dev/full should exit unsuccessfully.
     This is implemented in the Gnulib module "closeout".  */
  atexit (close_stdout);

  while ((optc = getopt_long (argc, argv, "g:hntv", longopts, NULL)) != -1)
    switch (optc)
      {
      /* --help and --version exit immediately, per GNU coding standards.  */
      case 'v':
        print_version ();
        exit (EXIT_SUCCESS);
        break;
      case 'g':
        greeting_msg = optarg;
        g = greet_user;
        break;
      case 'h':
        print_help ();
        exit (EXIT_SUCCESS);
        break;
      case 'n':
        g = greet_new;
        break;
      case 't':
        g = greet_traditional;
        break;
      default:
        lose = 1;
        break;
      }

  if (lose || optind < argc)
    {
      /* Print error message and exit.  */
      if (optind < argc)
        fprintf (stderr, _("%s: extra operand: %s\n"),
   program_name, argv[optind]);
      fprintf (stderr, _("Try `%s --help' for more information.\n"),
               program_name);
      exit (EXIT_FAILURE);
    }

  /* Print greeting message and exit. */
  if (g == greet_traditional)
    printf (_("hello, world\n"));

  else if (g == greet_new)
    /* TRANSLATORS: Use box drawing characters or other fancy stuff
       if your encoding (e.g., UTF-8) allows it.  If done so add the
       following note, please:

       [Note: For best viewing results use a UTF-8 locale, please.]
    */
 printf (_("\
+---------------+\n\
| Hello, world! |\n\
+---------------+\n\
"));

  else if (g == greet_user)
    puts (greeting_msg);

  else if (g == greet_gnu)
    puts (_("Hello, world!"));

  else {
    /* No need for this impossible message to be translated.  */
    fprintf (stderr, "Impossible hello value %d\n", g);
    exit (EXIT_FAILURE);
  }

  exit (EXIT_SUCCESS);
}



/* Print help info.  This long message is split into
   several pieces to help translators be able to align different
   blocks and identify the various pieces.  */

static void
print_help (void)
{
  /* TRANSLATORS: --help output 1 (synopsis)
     no-wrap */
        printf (_("\
Usage: %s [OPTION]...\n"), program_name);

  /* TRANSLATORS: --help output 2 (brief description)
     no-wrap */
  fputs (_("\
Print a friendly, customizable greeting.\n"), stdout);

  puts ("");
  /* TRANSLATORS: --help output 3: options 1/2
     no-wrap */
  fputs (_("\
  -h, --help          display this help and exit\n\
  -v, --version       display version information and exit\n"), stdout);

  puts ("");
  /* TRANSLATORS: --help output 4: options 2/2
     no-wrap */
  fputs (_("\
  -t, --traditional       use traditional greeting format\n\
  -n, --next-generation   use next-generation greeting format\n\
  -g, --greeting=TEXT     use TEXT as the greeting message\n"), stdout);

  printf ("\n");
  /* TRANSLATORS: --help output 5 (end)
     TRANSLATORS: the placeholder indicates the bug-reporting address
     for this application.  Please add _another line_ with the
     address for translation bugs.
     no-wrap */
  printf (_("\
Report bugs to <%s>.\n"), PACKAGE_BUGREPORT);
}



/* Print version and copyright information.  */

static void
print_version (void)
{
  printf ("hello (GNU %s) %s\n", PACKAGE, VERSION);
  /* xgettext: no-wrap */
  puts ("");

  /* It is important to separate the year from the rest of the message,
     as done here, to avoid having to retranslate the message when a new
     year comes around.  */
  printf (_("\
Copyright (C) %s Free Software Foundation, Inc.\n\
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n\
This is free software: you are free to change and redistribute it.\n\
There is NO WARRANTY, to the extent permitted by law.\n"),
              "2008");
}
[1] http://ftp.gnu.org/gnu/hello/

(4) Just downloaded it and looked at it. whaaattt.... - Charlie Somerville
(6) Oh, my. But it's missing the GNU rant about how man pages are obsolete, I guess it needs to get even bigger! (I love man pages, and my MacBook came with them preinstalled, way cool. Take that, FSF!) - DigitalRoss
(2) Just posted the c file, but I recommend that you check out the entire 225 file tarball :) - fatcat1111
@fatcat1111, it's really the fact that there are over 200 files that make it "special". - chris
(13) What's scary is .. that sample actually serves as a coding guideline. - Tim Post
3
[+23] [2010-01-14 08:00:43] cfern

I'm paranoid. I don't trust the compiler. I have to tell it how to do its job (C#):

using System;
using System.Reflection;

.

static void Main()
{
    Type ConsoleType = Type.GetType("System.Console");
    Type StringType = Type.GetType("System.String");
    Type CharArrayType = Type.GetType("System.Char[]");
    MethodInfo WriteLineMethod = ConsoleType.GetMethod("WriteLine", new Type[] { StringType });
    MethodInfo ReadLineMethod = ConsoleType.GetMethod("ReadLine");
    ConstructorInfo StringConstructorInfo = StringType.GetConstructor(new Type[] { CharArrayType });
    object HelloWorldStringObject = StringConstructorInfo.Invoke(new object[] { 
        new char[] { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' } });
    WriteLineMethod.Invoke(null, new object[] { HelloWorldStringObject });
    ReadLineMethod.Invoke(null, new object[] { });
}

4
[+20] [2010-02-10 15:18:16] marcgg

It's always a matter of finding the good language for the job. How about brainfuck ?

+++++ +++++             
[                       
    > +++++ ++              
    > +++++ +++++            
    > +++                   
    > +                     
    <<<< -                  
]                   
> ++ .                  
> + .                   
+++++ ++ .              
.                       
+++ .                   
>++ .                   
<< +++++ +++++ +++++ .  
> .                     
+++ .                   
----- - .               
----- --- .             
> + .                   
> .                     

(5) Hahaha, hilarious. Someone care to post the whitespace version? - Steve Tjoa
(24) Believe it or not, the idea of using indentation in BrainFuck never crossed my mind. For some irrational reason I thought every BrainFuck program had to be a one-liner... You know, like Perl. - R. Martinho Fernandes
5
[+15] [2010-02-03 21:24:14] Matteo Italia

C++ template abuse.

#include <iostream>
#include <string>
#include <new>

namespace HelloLand
{
    template<int Ordinal=1> class Hello
    {
        private:
            Hello<Ordinal<<1> * next;

            //We don't want no damned copies
            Hello(const Hello<Ordinal> & Other) {}
            Hello<Ordinal>& operator=(const Hello<Ordinal>& Other) {}
        public:

            Hello()
            {
                next=new Hello<Ordinal<<1>;
            }

            ~Hello()
            {
                delete next;
            }


            std::string GetString()
            {
                return next->GetString() + GetChar();
            }

            char GetChar();
    };

    template <> char Hello<1<<0>::GetChar() { return '!'; }
    template <> char Hello<1<<1>::GetChar() { return 'd'; }
    template <> char Hello<1<<2>::GetChar() { return 'l'; }
    template <> char Hello<1<<3>::GetChar() { return 'r'; }
    template <> char Hello<1<<4>::GetChar() { return 'o'; }
    template <> char Hello<1<<5>::GetChar() { return 'w'; }
    template <> char Hello<1<<6>::GetChar() { return ' '; }
    template <> char Hello<1<<7>::GetChar() { return 'o'; }
    template <> char Hello<1<<8>::GetChar() { return 'l'; }
    template <> char Hello<1<<9>::GetChar() { return 'l'; }
    template <> char Hello<1<<10>::GetChar() { return 'e'; }
    template <> char Hello<1<<11>::GetChar() { return 'H'; }

    template<> class Hello<1<<12>
    {
        public:
        std::string GetString()
        {
            return "";
        }
    };
}

int main()
{
    HelloLand::Hello<> hello;
    std::cout<<hello.GetString()<<std::endl;
    return 0;
}

What I like most of this thing:

  • no preprocessor-obfuscation (heck, this is C++, we don't need no preprocessor!);
  • the left shifts make the template brackets look mispaired, unbearable view for a programmer;
  • abuse-resistance; just try to insert an invalid Ordinal and the compiler will blow up;
  • it forced me to restudy some template functionalities I never used. :D

6
[+12] [2010-01-13 23:41:31] dsimcha
class Letter {

    void print();

    static Letter factory(char character) {
         Class cl = Class.forName(new String(character));
         java.lang.reflect.Constructor co = cl.getConstructor(null);
         return (Letter) co.newInstance(null);
    }

}

// We don't want to hard code any strings in case the value of 
// "H" changes and we want to override it.
class H extends Letter {
    void print() {
        System.out.println(this.getName());
    }
}

class E extends Letter {
    void print() {
        System.out.println(this.getName());
    }
}

class L extends Letter {
    void print() {
        System.out.println(this.getName());
    }
}

class O extends Letter {
    void print() {
        System.out.println(this.getName());
    }
}


class W extends Letter {
    void print() {
        System.out.println(this.getName());
    }
}

class R extends Letter {
    void print() {
        System.out.println(this.getName());
    }
}

class D extends Letter {
    void print() {
        System.out.println(this.getName());
    }
}

public class Main {
    public static void main() {
        Letter.factory('H').print();
        Letter.factory('E').print();
        Letter.factory('L').print();
        Letter.factory('L').print();
        Letter.factory('O').print();
        Letter.factory('W').print();
        Letter.factory('O').print();
        Letter.factory('R').print();
        Letter.factory('L').print();
        Letter.factory('D').print();
    }
}

(4) You probably want to use print() instead of println(), since this will print each letter out on its own line. Also, what about the space character? - Chinmay Kanchi
7
[+11] [2010-02-03 20:12:09] BalusC

Not really worth a "Daily WTF", but I couldn't resist in creating a multi-language Hello World using Java :)

package mypackage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HelloWorldInAllLanguages {

    private static final String HELLO_WORLD = "Hello World";
    private static final String DEFAULT_LANGUAGE = "en";
    private static final String DEFAULT_ENCODING = "UTF-8";
    private static final String TRANSLATOR_URL = "http://ajax.googleapis.com"
        + "/ajax/services/language/translate?v=1.0&q=%s&langpair=%2s%%7C%2s";
    private static final String REGEX = ".*\\{\"translatedText\":\"(.*)\"\\}";
    private static final int MATCH_GROUP = 1;

    public static void main(String[] args) throws IOException {
        Set<String> processedLanguages = new HashSet<String>();
        for (Locale locale : Locale.getAvailableLocales()) {
            String language = locale.getLanguage();
            if (processedLanguages.add(language)) {
                String url = String.format(TRANSLATOR_URL, 
                    URLEncoder.encode(HELLO_WORLD, DEFAULT_ENCODING), 
                    DEFAULT_LANGUAGE, language);
                BufferedReader reader = null;
                String json = null;
                try {
                    reader = new BufferedReader(new InputStreamReader(
                        new URL(url).openStream(), DEFAULT_ENCODING));
                    json = reader.readLine();
                } finally {
                    if (reader != null) {
                        reader.close();
                    }
                }
                Matcher matcher = Pattern.compile(REGEX).matcher(json);
                matcher.find();
                String text = matcher.group(MATCH_GROUP);
                System.out.println(locale.getDisplayLanguage() + ": " + text);
            }
        }
    }

}

To save the Google Translate service from being stackoverflowed by fellow sopedians, here's right the output so that you don't need to try yourself ;)

Japanese: ハローワールド
Spanish: Hola Mundo
English: Hello World
Serbian: Хелло Свет
Macedonian: Hello World
Arabic: مرحبا العالمي
Norwegian: Hello World
Albanian: Hello World
Bulgarian: Здравей, Свят
Hebrew: שלום עולם
Hungarian: Hello World
Portuguese: Olá Mundo
Greek: Hello World
Swedish: Hello World
German: Hallo Welt
Finnish: Hello World
Icelandic: Hello World
Czech: Hello World
Slovenian: Hello World
Slovak: Hello World
Italian: Ciao a tutti!
Turkish: Merhaba Dünya
Chinese: 世界您好
Thai: Hello World
Lithuanian: Hello World
Romanian: Hello World
Nederlands: Hello World
Irish: Hello World
French: Bonjour tout le monde
Korean: 안녕하세요
Estonian: Hello World
Indonesian: Hello World
Russian: Привет мир
Latvian: Hello World
Hebrew: שלום העולם
Croatian: Hello World
Hindi: नमस्ते विश्व
Belarusian: Прывітанне свет
Catalan: Hola món
Ukrainian: Привіт світ
Polish: Hello World
Vietnamese: Xin chào thế giới
Maltese: Hello dinja
Malay: Hello World
Danish: Hello World

(2) Bravo !!! To be perfect, you should refactor actual working part into separate class(es). - zendar
(2) It would then quicky grow to 500 lines, including neat javadocs. Do you want to have that? :) - BalusC
He! The Dutch translation is wrong. It says "Nederlands: Hello World" but I recon this should be "Nederlands: Hallo Wereld" - Niels Basjes
8
[+10] [2010-01-12 20:33:22] KennyTM
9
[+6] [2010-01-17 04:50:06] DigitalRoss

Ruby


class String

  def tack p
    self << p
  end

  def hello
    tack 'hello'
  end

  def comma
    tack ','
  end

  def blank
    tack ' '
  end

  def world
    tack 'world'
  end
end

puts String.new.hello.comma.blank.world.capitalize

10
[+3] [2010-01-12 20:56:28] Novelocrat

The Malbolge version might be of interest:

(=<`$9]7<5YXz7wT.3,+O/o'K%$H"'~D|#z@b=`{^Lx8%$Xmrkpohm-kNi;gsedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543s+O<oLm

11
[+3] [2010-01-14 00:31:37] Chinmay Kanchi

Here's an extreme case of taking abstraction to the limit in Python. This is inspired by dsimcha's solution:

class Character(object):
 """Abstract class to store character objects"""
 def __init__(self, character):
  self._character = character

 def getCharacter(self):
  raise NotImplementedError('Use AlphaCharacter, SymbolCharacter, DigitCharacter, WhiteSpaceCharacter or ControlCharacter instead') 

 def __add__(self, character):
  return String(self._character, character.getCharacter())

 def __repr__(self):
  return self._character

 def __str__(self):
  return String(character)

class VisibleCharacter(Character):
 def __init__(self, character):
  if(len(character) != 1): 
   raise ValueError('Only single characters are allowed')
  super(VisibleCharacter, self).__init__(character)

 def getCharacter(self):
  return self._character


class AlphaCharacter(VisibleCharacter):
 def __init__(self, character):
  if character not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ':
   raise ValueError('character must be alphabetical')

  super(AlphaCharacter, self).__init__(character)


class DigitCharacter(VisibleCharacter):
 def __init__(self, character):
  if character not in '1234567890':
   raise ValueError('character must be a digit')

  super(DigitCharacter, self).__init__(character)

 def getNumericalValue(self):
  return int(_character, 10)

class SymbolCharacter(VisibleCharacter):
 def __init__(self, character):
  if character not in r"""~`!@#$%^&*()-_+=[]{};:"'\|/?<>,.""": 
   raise ValueError('character must be a symbol')

  super(SymbolCharacter, self).__init__(character)

class InvisibleCharacter(Character):
 def __init__(self, character):
  super(InvisibleCharacter, self).__init__(character)

 def getCharacter(self):
  return self._character

class WhiteSpaceCharacter(InvisibleCharacter):
 def __init__(self, character):
  if character not in ' \t':
   raise ValueError('character must be whitespace')

  super(WhiteSpaceCharacter, self).__init__(character)

class ControlCharacter(InvisibleCharacter):
 def __init__(self, character):
  if character not in '\n\v\r':
   raise ValueError('character must be a control character')

  super(ControlCharacter, self).__init__(character)

class String(object):
 def __init__(self, *args):
  self._string = ""
  for character in args:
   self._string+=character.getCharacter()
 def __str__(self):
  return self._string

if __name__=='__main__':
 H = AlphaCharacter('H')
 e = AlphaCharacter('e')
 l = AlphaCharacter('l')
 o = AlphaCharacter('o')
 space = WhiteSpaceCharacter(' ')
 w = AlphaCharacter('w')
 r = AlphaCharacter('r')
 d = AlphaCharacter('d')
 exclamationMark = SymbolCharacter('!')
 newLine = ControlCharacter('\n')


 print(String(H,e,l,l,o,space,w,o,r,l,d,newLine))

(3) Err... looks like I inadvertently stumbled upon a bug in SO's string parsing for code... The code itself is perfectly valid and works on my machine certified. - Chinmay Kanchi
(1) Looks like Prettify doesn't handle a " inside """'s. - Michael Myers
(2) Not too bad. I've crashed SO's code parser! - slebetman
12
[+3] [2010-01-14 15:38:56] Dave Webb

Perl, avoiding the temptation to misuse classes:

use strict;
use warnings;
# Make sure we don't ruin regexp performance
use English qw(-no_match_vars);
use Carp qw(cluck);
use vars qw($stdout $words @words $exclamation_mark);

# Make sure we can see all error information
$Carp::MaxArgLen = 0;

# Route all output through single routine - DRY!
sub outputValues {
  my ($filehandle,@values) = @_;

  # Validate arguments
  if (ref($filehandle) !~ /^GLOB$/) {
    cluck("Invalid argument.  Please supply a filehandle");
  }

  unless (scalar(@values) > 0) {
    cluck("No values to print");
  }

  # Separate words with a space and lines with a newline
  local($OUTPUT_RECORD_SEPARATOR) = "\n";
  local($OUTPUT_FIELD_SEPARATOR) = " ";

  print $filehandle @values;
}

# Get the filehandle of STDOUT
sub getStandardOut {
  my $filehandle;

  unless (open($filehandle,">-")) {
    cluck("Cannot open STDOUT\n");
  }

  return $filehandle;
}

# Always encode ASCII data as a here document to avoid quoting
# problems etc.
$words = <<END_OF_DATA;
Hello World
END_OF_DATA
$exclamation_mark = <<END_OF_DATA;
!
END_OF_DATA

# Trim trailing newlines
chomp($words);
chomp($exclamation_mark);

# Split words in to array to pass to outputValues
@words = ($words =~ /\b\w+\b/g);

# Append exclamation mark to final word
$words[$#words] .= $exclamation_mark;

# Output to STDOUT
$stdout = getStandardOut();

# Output words
outputValues($stdout,@words);

13
[+3] [2010-02-03 20:19:48] Joachim Sauer

In the spirit of code-reuse, I present the sh version (requires sh, wget, zcat, tar, make and a C compiler).

#!/bin/sh

VERSION=2.4
wget -q -O - http://ftp.gnu.org/gnu/hello/hello-$VERSION.tar.gz | zcat - | tar xf -
cd hello-$VERSION
./configure > /dev/null
make > /dev/null
src/hello
cd ..
rm -Rf hello-$VERSION

14
[+2] [2010-01-12 20:36:23] Tyler McHenry

Not exactly "Hello World", but along the same lines is Enterprise FizzBuzz [1] (written in C#).

[1] http://code.google.com/p/fizzbuzz/source/browse/#svn/trunk/trunk

15
[+2] [2011-03-09 16:55:46] nyuszika7h

PHP, 1812 chars

<?php
    # DISCLAIMER
    #
    # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED
    # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
    # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
    # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
    # SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
    # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    # DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    #
    # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
    # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

    class Letter {
        public function factory($letter, $is_lowercase = false) {
            echo ($is_lowercase) ? strtolower($letter) : $letter;
        }
    }
    class H extends Letter {
        public function send() {
            return 'H';
        }
    }
    class E extends Letter {
        public function send() {
            return 'E';
        }
    }
    class L extends Letter {
        public function send() {
            return 'L';
        }
    }
    class O extends Letter {
        public function send() {
            return 'O';
        }
    }
    class W extends Letter {
        public function send() {
            return 'W';
        }
    }
    class R extends Letter {
        public function send() {
            return 'R';
        }
    }
    class D extends Letter {
        public function send() {
            return 'D';
        }
    }
    Letter::factory(H::send());
    Letter::factory(E::send(), true);
    Letter::factory(L::send(), true);
    Letter::factory(L::send(), true);
    Letter::factory(O::send(), true);
    // insert a space
    echo chr(32);
    Letter::factory(W::send());
    Letter::factory(O::send(), true);
    Letter::factory(R::send(), true);
    Letter::factory(L::send(), true);
    Letter::factory(D::send(), true);
?>

you forgot a flag for toupper. which means you probably need to define a new classtype so you can encapsulate the logic for that. - jcolebrand
@dranchestern Nope, letters are uppercase by default. If you pass true or a truthy value as the second parameter to Letter::factory, it will be lowercase. - nyuszika7h
16
[+2] [2012-02-05 04:59:14] phatskat

wait, no HQ9+?

      ++                      +             ++  +              +  +
    ++   +++                  +             ++  +              +  +
  ++     +  +  +++++    ++++  +                 +       ++++   +  +   ++++
++        +   +     +  +      ++++    ++++      ++++   +    +  +  +  +    +
  ++      +   +++++++  +      +   +  +    +     +   +  ++++++  +  +  +    +
    ++        +        +      +   +  +    +     +   +  +       +  +  +    +
      ++  +    +++++    ++++  +   +   ++++      +   +   +++++  +  +   ++++


+           +                   +      + ++            ++
+           +                   +      + ++   +  +++     ++
 +         +    ++++   + +++    +      +         +  +      ++
 +    +    +   +    +  ++   +   +   ++++      +   +          ++
  +  + +  +    +    +  +        +  +   +      +   +        ++
  +  + +  +    +    +  +        +  +   +      +          ++
   ++   ++      ++++   +        +   ++++     +    +    ++

H

17
[0] [2012-01-31 17:12:24] Alex Coplan

Objective-C

This isn't necessary a lot of code, but it's pretty darn in-efficient :)

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
    @autoreleasepool {
        int chars[53];

        for (int i = 0; i<26; i++) {
            chars[i] = i+65;
        }

        for (int i = 0; i<26; i++) {
            chars[i+26] = i+97;
        }

        chars[52] = 32;

        int rnum=0, iterations=0;
        NSString *target = @"Hello World";
        NSMutableString *buffer = [NSMutableString string];
        NSUInteger length = [target length];

        for (int i = 0; i < length; i++) {
            char getme = [target characterAtIndex:i];
            while (rnum != getme) {
                iterations++;
                rnum = chars[arc4random() % 53];
            }
            [buffer appendFormat:@"%c",rnum];
        }
        NSLog(@"We've got your string... it took %i pointless iterations!",iterations);
        NSLog(@"%@",buffer);
    }
    return 0;
}

18