41
votes
\$\begingroup\$

Your boss asks you to write a "hello world" program. Since you get paid for lines of code, you want to make it as complex as possible. However if you just add nonsense lines, or obviously useless or obfuscating stuff, you will never get it through code review. Therefore the challenge is:

Write a "hello world" program which is as complex as possible under the condition that you can give a "justification" for every complexity in the code.

The required behavior of the program is to just output a single line "Hello world" (without the quotes, but with a newline at the end) and then exit successfully.

"Justifications" include:

  • buzzword compatibility ("Modern software is object oriented!")
  • generally accepted good programming practices ("Everyone knows that you should separate model and view")
  • maintainability ("If we do it this way, we can more easily do XXX later")
  • and of course any other justification you can imagine using (in other situations) for real code.

Obviously silly justifications will not be accepted.

Also, you have to "justify" your choice of language (so if you choose an inherently verbose language, you'll have to justify why it is the "right" choice). Fun languages like Unlambda or Intercal are not acceptable (unless you can give a very good justification for using them).

The score of qualifying entries is computed as follows:

  • 1 point for each statement (or whatever the equivalent to a statement is in your language of choice).
  • 1 point for each definition of a function, type, variable etc (with the exception of the main function, where applicable).
  • 1 point for each module use statement, file include directive, namespace using statement or similar.
  • 1 point for each source file.
  • 1 point for each necessary forward declaration (if you could get rid of it by rearranging code, you have to "justify" why the arrangement you've chosen is the "right" one).
  • 1 point for each control structure (if, while, for, etc.)

Remember that you have to "justify" each single line.

If the chosen language is different enough that this scheme cannot be applied (and you can give a good "justification" for its use), please suggest a scoring method which most closely resembles the above for your language of choice.

Contestants are asked to calculate the score of their entry and write it in the answer.

\$\endgroup\$
  • 3
    \$\begingroup\$ I've seen this before: stackoverflow.com/questions/2052137/code-bowling-on-hello-world \$\endgroup\$ – ChristopheD Feb 5 '12 at 0:51
  • 7
    \$\begingroup\$ Somehow, these 'gimme more, more, more' - challenges only look interesting for 5 minutes. Let's do a ProxyPoolFactoryPoolFacadePoolProxyFactory (Pool)! You need a restriction like: Finish in 20 minutes from now! Another problem is 'silly justifications will not be accepted'. It's not only subjective, it is void from the beginning, since we know, that the whole thing is silly. Okay - instead of a ProxyPoolPool, let's use something less silly, a PoolProxyProxy probably? \$\endgroup\$ – user unknown Feb 5 '12 at 7:05
  • 1
    \$\begingroup\$ @ChristopheD: While I didn't know that SO question, there's a twist in mine which is not in that one: You have to "justify" your choices (i.e. just making it more complex doesn't suffice, you'll have to give a good reason for the complexity). \$\endgroup\$ – celtschk Feb 5 '12 at 8:34
  • 3
    \$\begingroup\$ I'm not sure that the "not obviously silly" restriction on the justification can be made to agree with the FAQ where it says "All questions on this site [...] should have [... an] objective primary winning criterion". \$\endgroup\$ – dmckee Feb 5 '12 at 17:15
  • 21
    \$\begingroup\$ It seems hard to beat GNU Hello World (gnu.org/software/hello) - the source code for version 2.7 is a 586 kB download as a compressed archive, complete with automatic tests, internationalization, documentation etc. \$\endgroup\$ – han Feb 6 '12 at 16:04

23 Answers 23

48
votes
\$\begingroup\$

C++, trollpost

Most complex “Hello world” program you can justify

#include <iostream>

using namespace std;

int main(int argc, char * argv[])
{
    cout << "Hello, world!" << endl;
    return 0;
}

My brain cannot justify writing a longer one :)

\$\endgroup\$
  • 6
    \$\begingroup\$ The best answer here. \$\endgroup\$ – Joe Z. Feb 15 '13 at 20:45
  • 12
    \$\begingroup\$ "using namespace std" cannot be justified! Plus your main takes arguments it doesn't use. Wasteful! ;) \$\endgroup\$ – Riot Feb 20 '14 at 20:09
  • 3
    \$\begingroup\$ Too complex for me. What's it meant to do? Is there the possibility of adding some unit tests? \$\endgroup\$ – Nathan Cooper Jun 16 '14 at 14:25
20
votes
\$\begingroup\$

I will here demonstrate the power and usability of the scripting language called Python by solving a rather complex task in a graceful and efficient manner through the aforementioned scripting language's operators on – and generators of – data structures such as lists and dictionaries.

However, I'm afraid I don't fully comprehend the use of the phrases "complex as possible" and "justification". Nevertheless, here is a rundown of my usual, quite self-explanatory and straight-forward strategy, followed by the actual implementation in Python which you will find, is quite true to the playful, high-order nature of the language:

  1. Define the alphabet – obvious first step. For expandability, we choose the entire ascii range. Note the use of the built-in list-generator that can save us for hours of tedious list initialization.

  2. tell how many of each letter in the alphabet we will be using. This is simply represented as another list!

  3. Merge these two lists into one handy dictionary, where the keys are ascii points and the values are the desired amount.

  4. We are now ready to start making characters! Start by creating a string of character out of the dictionary. This will contain all the characters we need in our final output, and the right amount of each one!

  5. Declare the desired order of the characters and initiate a new list that will hold our final output. With simple iteration we will put the generated characters into their final position and print the result!

Here is the actual implementation

# 1: Define alphabet:
a = range(255)

# 2: Letter count:
n = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
     1, 1, 0, 0, 0, 0, 0, 0, 3, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0)

# 3: Merge to dictionary:
d = { x: y for x, y in zip(a,n) }

# 4: 'Initialize' characters
l = ''.join([chr(c) *n for c,n in d.items()])

# 5: Define the order of the characters, initialize final string
#    and sort before outputting:
z = [6,5,0,7,11,1,2,3,4,8,9]
o = [0] * 13

for c in l:
    i = z.pop(0)
    o[i] = c

print ''.join(o)

Ok, Just went for a short but stupid one and added a bunch of text rather than a TL;DR code solution

\$\endgroup\$
  • \$\begingroup\$ Does the definition of n here count as 1 line or 11? \$\endgroup\$ – Draco18s Jan 22 '16 at 19:32
17
votes
\$\begingroup\$

Dart's Hello World compiled to JS (2 936 012)

http://code.google.com/p/dart/issues/detail?id=14686

(I'll let Google justify it, though)

\$\endgroup\$
16
votes
\$\begingroup\$

Scala, score: 62

Okay, I throw my hat into the ring.

ContentProvider.scala:

/*  
    As we all know, the future is functional programming. 

    And one of the mantras of pure functional programming is, to avoid mutable data 
    as hell. Using case classes and case objects allows us to create very small,
    immutable Flight-Weight-Pattern like objects (Singletons, if you like).

    I'm choosing scala, because its compiled to bytecode for the JVM and therefore very 
    portable. I could of course have implemented it in Java, but as we all know,
    Javacode is boilerplaty, while scala is a concise language.     

    S: for easy grepping of scoring hints. 
    Scoring summary: 

        1 import 
        3 control structures
        8 function calls
       22 function definitions
       14 type definitions
       14 files: Seperate files speed up the compilation process, 
          if you only happen to make a local change. 
*/

/**
   To change the content and replace it with something else later, we generate 
   a generic Content trait, which will be 'Char' in the beginning, but could be Int or
   something. 

S:   1 type definition. 
S:   1 function 
*/
trait ContentProvider [T] {
  // ce is the content-element, but we like to stay short and lean. 
  def ce () : T 
}

HWCChain.scala:

//S:  1 import, for the tailcall annotation later. 
import annotation._

/**
   HWCChain is a Chain of HelloWordCharacters, but as a lean, concise language, 
   we do some abbrev. here. 
   We need hasNext () and next (), which is the iterator Pattern.

S: 1 type 
S: 2 functions definitions 
S: 4 function calls
S: 1 if 
*/
trait HWCChain[T] extends Iterator [HWCChain[T]] with ContentProvider[T] {
  // tailrec is just an instruction for the compiler, to warn us, if this code 
  // can't be tail call optimized. 
  @tailrec 
  final def go () : Unit = {
    // ce is our ContentProvider.ce 
    System.out.print (ce);
    // and here is our iterator at work, hasNext and next:  
    if (hasNext ()) next ().go ()
  }
  // per default, we have a next element (except our TermHWWChain, see close to bottom) 
  // this follows the DRY-principle, and reduces the code drastically.
  override def hasNext (): Boolean = true 
}

HHWCChain.scala:

/**
  This is a 'H'-element, followed by the 'e'-Element. 
S: 1 type 
S: 2 functions
*/
case object HHWCChain extends HWCChain[Char] with ContentProvider[Char] {
  override def ce = 'H'
  override def next = eHWCChain
}

eHWCChain.scala:

/*
  and here is the 'e'-Element, followed by l-Element 1, which is a new Type

S: 1 type 
S: 2 functions
*/
case object eHWCChain extends HWCChain[Char] {
  override def ce = 'e'
  override def next = new indexedLHWCChain (1) 
}

theLThing.scala:

/**
  we have to distinguish the first, second and third 'l'-thing. 
  But of course, since all of them provide a l-character, 
    we extract the l for convenient reuse. That saves a lotta code, boy! 

S: 1 type
S: 1 function
*/
trait theLThing extends HWCChain[Char] {
  override def ce = 'l'
}

indexedLHWCChain.scala:

/**
  depending on the l-number, we either have another l as next, or an o, or the d. 
S: 1 type 
S: 1 function definition
S: 2 function calls
S: 1 control structure (match/case) 
*/
case class indexedLHWCChain (i: Int) extends theLThing {
  override def next = i match { 
    case 1 => new indexedLHWCChain (2) 
    case 2 => new indexedOHWCChain (1) 
    case _ => dHWCChain
  }
}

theOThing.scala:

// see theLTHing ...
//S: 1 type
//S: 1 function
trait theOThing extends HWCChain[Char] {
  override def ce = 'o'
}

indexedOHWCChain.scala:

// and indexedOHWCCHain ...
//S: 1 type 
//S: 1 function definition
//S: 1 function call 
//S: 1 control structure 
case class indexedOHWCChain (i: Int) extends theOThing {
  override def next = i match { 
    case 1 => BlankHWCChain
    case _ => rHWCChain
  }
}

BlankHWCChain.scala:

// and indexedOHWCCHain ...
//S: 1 type
//S: 2 function definitions
case object BlankHWCChain extends HWCChain[Char] {
  override def ce = ' '
  override def next = WHWCChain
}

WHWCChain.scala:

//S: 1 type
//S: 2 function definitions
case object WHWCChain extends HWCChain[Char] {
  override def ce = 'W'
  override def next = new indexedOHWCChain (2) 
}

rHWCChain.scala:

//S: 1 type 
//S: 2 function definitions
case object rHWCChain extends HWCChain[Char] {
  override def ce = 'r'
  override def next = new indexedLHWCChain (3) 
}

dHWCChain.scala:

//S: 1 type
//S: 2 function definitions
case object dHWCChain extends HWCChain[Char] {
  override def ce = 'd'
  override def next = TermHWCChain
}

TermHWCChain.scala:

/*
   Here is the only case, where hasNext returns false. 
   For scientists: If you're interested in terminating programs, this type is 
   for you!

S: 1 type 
S: 3 function definitions
*/ 
case object TermHWCChain extends HWCChain[Char] {
  override def ce = '\n'
  override def hasNext (): Boolean = false 
  override def next = TermHWCChain // dummy - has next is always false
}

HelloWorldCharChainChecker.scala:

/* 
S: 1 type
S: 1 function call
*/ 
object HelloWorldCharChainChecker extends App {
  HHWCChain.go ()
}

Of course, for a pure functional approach, 0 stinky variables. Everything is layed out in the type system and straight forward. A clever compiler can optimize it down to the bare nothing.

The program is clear, simple and easy to understand. It is easy testable and generic and avoids the trap of overengineering (my team wanted to recode the indexedOHWCChain and indexedLHWCChain to a common secondary trait, which has an array of targets and a length field, but that would have been just silly!).

\$\endgroup\$
  • \$\begingroup\$ Where are the 14 files? \$\endgroup\$ – celtschk Feb 6 '12 at 11:44
  • 1
    \$\begingroup\$ After every closing brace in column 0, a new file is made. One file per object, class and trait. That speeds up the build process, if you only modify a single object. \$\endgroup\$ – user unknown Feb 6 '12 at 17:21
  • \$\begingroup\$ Then please make that clear in the answer itself. \$\endgroup\$ – celtschk Feb 7 '12 at 20:16
  • 1
    \$\begingroup\$ This is not complex as the original question requests. It is just very verbose. There is a difference. \$\endgroup\$ – monokrome Dec 30 '13 at 19:42
  • 5
    \$\begingroup\$ +1 for "Javacode is boilerplaty, while scala is a concise language." followed by the most boilerplaty code I've seen. \$\endgroup\$ – Tim S. Aug 7 '14 at 19:37
8
votes
\$\begingroup\$

Pure Bash no fork (some count, seem to be approx 85...)

  • 6 function initRotString 2 variables, 3 statments
  • 14 function binToChar 2 variables, 7 statements + sub define: 1 func, 1 var, 2 stat
  • 34 function rotIO 9 variables, 25 statments
  • 9 function rle 4 variables, 5 statments
  • 22 MAIN 13 variables, 9 statments

Features:

  • Two level RLE: first binary encode each chars and second for repeated chars
  • Key based modified rot13: The rotIO function perform rotation like Rot13, but on 96 values instead of 26 (*rot47), but shifted by submited key.
  • Second version use gzip and uuencode via perl (more commonly installed than uudecode)

Complete rewrite (bugs corrections, ascii-art drawing and two level rle):

#!/bin/bash

BUNCHS="114 11122 112111 11311 1213 15 21112 11311 1123 2121 12112 21211"
MKey="V922/G/,2:"

export RotString=""
function initRotString() {
    local _i _char
    RotString=""
    for _i in {1..94} ;do
        printf -v _char "\\%03o" $((_i+32))
        printf -v RotString "%s%b" "$RotString" $_char
    done
}

 

function rotIO() {
    local _line _i _idx _key _cidx _ckey _o _cchar _kcnt=0
    while read -r _line ;do
        _o=""
        for (( _i=0 ; _i < ${#_line} ; _i++)) ;do
            ((_kcnt++ ))
            _cchar="${_line:_i:1}"
            [ "${_cchar//\(}" ] || _cchar="\("
            [ "${_cchar//\*}" ] || _cchar="\*"
            [ "${_cchar//\?}" ] || _cchar="\?"
            [ "${_cchar//\[}" ] || _cchar="\["
            [ "${_cchar//\\}" ] || _cchar='\\'
            if [ "${RotString//${_cchar}*}" == "$RotString" ] ;then
                _o+="${_line:_i:1}"
            else
                _kchar="${1:_kcnt%${#1}:1}"
                [ "${_kchar//\(}" ] || _kchar="\("
                [ "${_kchar//\*}" ] || _kchar="\*"
                [ "${_kchar//\?}" ] || _kchar="\?"
                [ "${_kchar//\[}" ] || _kchar="\["
                [ "${_kchar//\\}" ] || _kchar='\\'
                _key="${RotString//${_kchar}*}"
                _ckey=${#_key}
                _idx="${RotString//${_cchar}*}"
                _cidx=$(((1+_ckey+${#_idx})%94))
                _o+=${RotString:_cidx:1}
            fi; done
        if [ "$_o" ] ; then
            echo "$_o"
    fi ; done ; }

 

function rle() {
    local _out="" _c=1 _l _a=$1
    while [ "${_a}" ] ; do
        printf -v _l "%${_a:0:1}s" ""
        _out+="${_l// /$_c}"
        _a=${_a:1} _c=$((1-_c))
        done
    printf ${2+-v} $2 "%s" $_out
}
function binToChar() {
    local _i _func="local _c;printf -v _c \"\\%o\" \$(("
    for _i in {0..7} ;do
        _func+="(\${1:$_i:1}<<$((7-_i)))+"
        done
    _func="${_func%+}));printf \${2+-v} \$2 \"%b\" \$_c;"

    eval "function ${FUNCNAME}() { $_func }"
    $FUNCNAME $@
}

initRotString

 

for bunch in "${BUNCHS[@]}" ; do
    out=""
    bunchArray=($bunch)
    for ((k=0;k<${#bunchArray[@]};k++)) ; do
        enum=1
        if [ "${bunchArray[$k]:0:1}" == "-" ];then
            enum=${bunchArray[$k]:1}
            ((k++))
        fi
        ltr=${bunchArray[$k]}
        rle $ltr binltr
        printf -v bin8ltr "%08d" $binltr
        binToChar $bin8ltr outltr
        printf -v mult "%${enum}s" ""
        out+="${mult// /$outltr}"
    done
    rotIO "$MKey" <<< "$out"
done

(The key used V922/G/,2: is based on HelloWorld too, but that's no matter;)

Result (as requested):

Hello world!

There is another version:

#!/bin/bash

eval "BUNCHS=(" $(perl <<EOF | gunzip
my\$u="";sub d{my\$l=pack("c",32+.75*length(\$_[0]));print unpack("u",\$l.\$
_[0]);"";}while(<DATA>){tr#A-Za-z0-9+/##cd;tr#A-Za-z0-9+/# -_#;\$u.=\$_;while
(\$u=~s/(.{80})/d(\$1)/egx){};};d(\$u);__DATA__
H4sIAETywVICA8VZyZLcMAi9z1e4+q6qAHIr+f8fi7UgyQYs3DOp5JBxywKxPDZr27bthRFgA4B9C0Db
8YdoC+UB6Fjewrs8A8TyFzGv4e+2iLh9HVy2sI+3lQdk4pk55hdIdQNS/Qll2/FUuAD035V3Y1gEAUI4
0yBg3xxnaZqURYvAXLoi2Hj1N4U84HQsy1MPLiRC4qpj3CgKxc6qVwMB8+/0sR0/k8a+LZ4M2o6tUu1V
/oMM5SZWBLslsdqtsMaTvbG9gqpbU/d4iDgrmtXXtD3+0bBVleJ4o+hpYAGH1dkBhRfN7mjeapbpPu8P
1QzsKRLmCsNvk2Hq6ntYJjOirGaks58ZK2x7nDHKj7H8Fe5sK21btwKDvZtCxcKZuPxgL0xY5/fEWmVx
OxEfHAdptnqcIVI4F15v2CYKRkXsMVBDsOzPNqsuOBjXh8mBjA+Om/mkwruFSTwZDlC30is/vYiaRkWG
otG0QDVsz2uHQwP+6usNpwYHDgbJgvPiWOfsQAbBW6wjFHSdzoPmwtNyckiF1980cwrYXyyFqCbS1dN3
L60+yE727rSTeFDgc+fWor5kltEnJLsKkqSRWICZ2WWTEAmve5JmK/yHnNxYj26oX+0nTyXViwaMlwh2
CJW1ugBEargbGtJFhigVFCs6Tn36GFjThTIUukPIQqSyMcgso6stk8xnxp8K9Cr2HDhhFR3glpa6ZiKO
HfIkFSt+PoO7wB7hjaEc7tJEk8w8CNcB5uB1ySaWJVsZRHzqLoPTMvaSp1wocFezmxI/M5SfptDkyO3f
gJNeUUNaNweooE6xkaNe3TUxAW+taR+jGoo0cCtHJC3e+xGXLKq1CKumAbW0kDxtldGLLfLLDeWicIkg
1jOEFtadl9D9scGSm9ESfTR/WngEIu3Eaqv0lEzbsm7aPfJVvTyBmBY/jZZIslEDaNnH+Ojs4KwTYZ/+
Lx8D1ulL7YmUOPkhNur0piXlMH2QkcWFvMs36crIqVrSv3p7TKjhzwMba3axh6WP2SwwQKvBc2ind7E/
wUhLlLujdK3KL67HVG2Wf8pj7T1zBjBOGT22VUPcY9NdNRXOWNUcw4dqSvJ3V8+lMptHtQ+696DdiPo9
z/ks2lI9C5aBkJ9gpNaG/fkk0UYmTyHViWWDYTShrq9OeoZJvi7zBm3rLhRpOR0BqpUmo2T/BKLTZ/HV
vLfsa40wdlDezKUBP5PNF8RP1nx2WuPkCGeV1YNQ0aDuJL5c5OBN72m1Oo7PVpWZ7+uIb6BMzwuWVnb0
2cYxyciKaRneNRi5eQWfwYKvCLr5uScSh67/k1HS0MrotsPwHCbl+up00Y712mtvd33j4g/4UnNvyahe
hLabuPm+71jmG+l6v5qv2na+OtwHL2jfROv/+daOYLr9LZdur6+/stxCnQsgAAA=
EOF
) ")"

MKey="V922/G/,2:"
export RotString=""

function initRotString() {
    local _i _char
    RotString=""
    for _i in {1..94} ;do
        printf -v _char "\\%03o" $((_i+32))
        printf -v RotString "%s%b" "$RotString" $_char
    done
}
function rotIO() {
    local _line _i _idx _key _cidx _ckey _o _cchar _kcnt=0
    while read -r _line ;do
        _o=""
        for (( _i=0 ; _i < ${#_line} ; _i++)) ;do
            ((_kcnt++ ))
            _cchar="${_line:_i:1}"
            [ "${_cchar//\(}" ] || _cchar="\("
            [ "${_cchar//\*}" ] || _cchar="\*"
            [ "${_cchar//\?}" ] || _cchar="\?"
            [ "${_cchar//\[}" ] || _cchar="\["
            [ "${_cchar//\\}" ] || _cchar='\\'
            if [ "${RotString//${_cchar}*}" == "$RotString" ] ;then
                _o+="${_line:_i:1}"
            else
                _kchar="${1:_kcnt%${#1}:1}"
                [ "${_kchar//\(}" ] || _kchar="\("
                [ "${_kchar//\*}" ] || _kchar="\*"
                [ "${_kchar//\?}" ] || _kchar="\?"
                [ "${_kchar//\[}" ] || _kchar="\["
                [ "${_kchar//\\}" ] || _kchar='\\'
                _key="${RotString//${_kchar}*}"
                _ckey=${#_key}
                _idx="${RotString//${_cchar}*}"
                _cidx=$(((1+_ckey+${#_idx})%94))
                _o+=${RotString:_cidx:1}
            fi; done
        if [ "$_o" ] ; then
            echo "$_o"
        fi; done
}
function rle() {
    local _out="" _c=1 _l _a=$1
    while [ "${_a}" ] ; do
        printf -v _l "%${_a:0:1}s" ""
        _out+="${_l// /$_c}"
        _a=${_a:1} _c=$((1-_c))
        done
    printf ${2+-v} $2 "%s" $_out
}
function binToChar() {
    local _i _func="local _c;printf -v _c \"\\%o\" \$(("
    for _i in {0..7} ;do
        _func+="(\${1:$_i:1}<<$((7-_i)))+"
        done
    _func="${_func%+}));printf \${2+-v} \$2 \"%b\" \$_c;"

    eval "function ${FUNCNAME}() { $_func }"
    $FUNCNAME $@
}

initRotString

for bunch in "${BUNCHS[@]}" ; do
    out=""
    bunchArray=($bunch)
    for ((k=0;k<${#bunchArray[@]};k++)) ; do
        enum=1
        if [ "${bunchArray[$k]:0:1}" == "-" ];then
            enum=${bunchArray[$k]:1}
            ((k++))
        fi
        ltr=${bunchArray[$k]}
        rle $ltr binltr
        printf -v bin8ltr "%08d" $binltr
        binToChar $bin8ltr outltr
        printf -v mult "%${enum}s" ""
        out+="${mult// /$outltr}"
    done
    rotIO "$MKey" <<< "$out"
done

Using same key and may render something like:

              _   _      _ _                            _     _ _
             | | | | ___| | | ___   __      _____  _ __| | __| | |
             | |_| |/ _ \ | |/ _ \  \ \ /\ / / _ \| '__| |/ _` | |
             |  _  |  __/ | | (_) |  \ V  V / (_) | |  | | (_| |_|
             |_| |_|\___|_|_|\___/    \_/\_/ \___/|_|  |_|\__,_(_)
 
▐▌ █                    ▐▙ █             █ █                ▗▛▀▙ ▟▜▖ ▗█  ▗█▌ ▗█▖
▐▙▄█ ▀▜▖▝▙▀▙▝▙▀▙▐▌ █    ▐▛▙█▗▛▀▙▐▌▖█     ▜▄▛▗▛▀▙ ▀▜▖▝▙▛▙      ▄▛▐▌▖█  █ ▗▛▐▌ ▝█▘
▐▌ █▗▛▜▌ █▄▛ █▄▛▝▙▄█    ▐▌▝█▐▛▀▀▐▙▙█      █ ▐▛▀▀▗▛▜▌ █       ▟▘▄▝▙▗▛  █ ▝▀▜▛  ▀
▝▘ ▀ ▀▘▀▗█▖ ▗█▖ ▗▄▄▛    ▝▘ ▀ ▀▀▘ ▀▝▘     ▝▀▘ ▀▀▘ ▀▘▀▝▀▘     ▝▀▀▀ ▝▀  ▀▀▀  ▀▀  ▀
 
  ▟▙█▖▟▙█▖                ▜▌           █   █   ▝▘  █       ▝█         ▟▙█▖▟▙█▖
  ███▌███▌    ▟▀▟▘▟▀▜▖▟▀▜▖▐▌▟▘    ▝▀▙ ▀█▀ ▀█▀  ▜▌ ▀█▀ █ █ ▟▀█ ▟▀▜▖    ███▌███▌
  ▝█▛ ▝█▛     ▜▄█ █▀▀▘█▀▀▘▐▛▙     ▟▀█  █▗▖ █▗▖ ▐▌  █▗▖█ █ █ █ █▀▀▘    ▝█▛ ▝█▛
   ▝   ▝      ▄▄▛ ▝▀▀ ▝▀▀ ▀▘▝▘    ▝▀▝▘ ▝▀  ▝▀  ▀▀  ▝▀ ▝▀▝▘▝▀▝▘▝▀▀      ▝   ▝
 
... And thank you for reading!!

Hello world and happy new year 2014

\$\endgroup\$
  • 2
    \$\begingroup\$ ... But it's not as complex as possible! I can do a lot worst :->> \$\endgroup\$ – F. Hauri Dec 6 '13 at 1:30
8
votes
\$\begingroup\$

Everyone knows that Moore's Law has taken a new turn, and that all real advances in computing power in the next decade will come in the GPU. With that in mind, I've used LWJGL to write a blazingly fast Hello World program that fully takes advantage of the GPU to generate the string "Hello World."

Since I'm writing java, it is idiomatic to start by copying and pasting someone elses code, I used http://lwjgl.org/wiki/index.php?title=Sum_Example

package magic;
import org.lwjgl.opencl.Util;
import org.lwjgl.opencl.CLMem;
import org.lwjgl.opencl.CLCommandQueue;
import org.lwjgl.BufferUtils;
import org.lwjgl.PointerBuffer;
import org.lwjgl.opencl.CLProgram;
import org.lwjgl.opencl.CLKernel;

import java.nio.IntBuffer;
import java.util.List;

import org.lwjgl.opencl.CL;
import org.lwjgl.opencl.CLContext;
import org.lwjgl.opencl.CLDevice;
import org.lwjgl.opencl.CLPlatform;

import static org.lwjgl.opencl.CL10.*;

public class OpenCLHello {
static String letters = "HeloWrd ";

// The OpenCL kernel
static final String source =
    ""
    + "kernel void decode(global const int *a, global int *answer) { "
    + "  unsigned int xid = get_global_id(0);"
    + "  answer[xid] = a[xid] -1;" 
    + "}";

// Data buffers to store the input and result data in
static final IntBuffer a = toIntBuffer(new int[]{1, 2, 3, 3, 4, 8, 5, 4, 6, 3, 7});
static final IntBuffer answer = BufferUtils.createIntBuffer(11);

public static void main(String[] args) throws Exception {
    // Initialize OpenCL and create a context and command queue
    CL.create();
    CLPlatform platform = CLPlatform.getPlatforms().get(0);
    List<CLDevice> devices = platform.getDevices(CL_DEVICE_TYPE_GPU);
    CLContext context = CLContext.create(platform, devices, null, null, null);
    CLCommandQueue queue = clCreateCommandQueue(context, devices.get(0), CL_QUEUE_PROFILING_ENABLE, null);

    // Allocate memory for our input buffer and our result buffer
    CLMem aMem = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, a, null);
    clEnqueueWriteBuffer(queue, aMem, 1, 0, a, null, null);

    CLMem answerMem = clCreateBuffer(context, CL_MEM_WRITE_ONLY | CL_MEM_COPY_HOST_PTR, answer, null);
    clFinish(queue);

    // Create our program and kernel
    CLProgram program = clCreateProgramWithSource(context, source, null);
    Util.checkCLError(clBuildProgram(program, devices.get(0), "", null));
    // sum has to match a kernel method name in the OpenCL source
    CLKernel kernel = clCreateKernel(program, "decode", null);

    // Execution our kernel
    PointerBuffer kernel1DGlobalWorkSize = BufferUtils.createPointerBuffer(1);
    kernel1DGlobalWorkSize.put(0, 11);
    kernel.setArg(0, aMem);
    kernel.setArg(1, answerMem);
    clEnqueueNDRangeKernel(queue, kernel, 1, null, kernel1DGlobalWorkSize, null, null, null);

    // Read the results memory back into our result buffer
    clEnqueueReadBuffer(queue, answerMem, 1, 0, answer, null, null);
    clFinish(queue);
    // Print the result memory

    print(answer);

    // Clean up OpenCL resources
    clReleaseKernel(kernel);
    clReleaseProgram(program);
    clReleaseMemObject(aMem);
    clReleaseMemObject(answerMem);
    clReleaseCommandQueue(queue);
    clReleaseContext(context);
    CL.destroy();
}





/** Utility method to convert int array to int buffer
 * @param ints - the float array to convert
 * @return a int buffer containing the input float array
 */
static IntBuffer toIntBuffer(int[] ints) {
    IntBuffer buf = BufferUtils.createIntBuffer(ints.length).put(ints);
    buf.rewind();
    return buf;
}


/** Utility method to print an int buffer as a string in our optimized encoding
 * @param answer2 - the int buffer to print to System.out
 */
static void print(IntBuffer answer2) {
    for (int i = 0; i < answer2.capacity(); i++) {
        System.out.print(letters.charAt(answer2.get(i) ));
    }
    System.out.println("");
}

}
\$\endgroup\$
7
votes
\$\begingroup\$

Assembly (x86, Linux/Elf32): 55 points

Everyone knows that when you want a fast program, you need to write in assembly.

Sometimes we can't rely on ld doing its job properly - For optimal performance, it's preferable to build our own Elf header for our hello world executable. This code requires only nasm to build, so is very portable. It relies on no external libraries or runtimes.

Every line and statement is absolutely crucial to the correct functioning of the program - there is no cruft, nothing can be omitted.

Moreover, this really is the shortest way to do it without using the linker - there are no unnecessary loops or declarations to bloat out the answer.

BITS 32

              org     0x08048000

ehdr:                                                 ; Elf32_Ehdr
              db      0x7F, "ELF", 1, 1, 1, 0         ;   e_ident
times 8       db      0
              dw      2                               ;   e_type
              dw      3                               ;   e_machine
              dd      1                               ;   e_version
              dd      _start                          ;   e_entry
              dd      phdr - $$                       ;   e_phoff
              dd      0                               ;   e_shoff
              dd      0                               ;   e_flags
              dw      ehdrsize                        ;   e_ehsize
              dw      phdrsize                        ;   e_phentsize
              dw      1                               ;   e_phnum
              dw      0                               ;   e_shentsize
              dw      0                               ;   e_shnum
              dw      0                               ;   e_shstrndx

ehdrsize      equ     $ - ehdr

phdr:                                                 ; Elf32_Phdr
              dd      1                               ;   p_type
              dd      0                               ;   p_offset
              dd      $$                              ;   p_vaddr
              dd      $$                              ;   p_paddr
              dd      filesize                        ;   p_filesz
              dd      filesize                        ;   p_memsz
              dd      5                               ;   p_flags
              dd      0x1000                          ;   p_align

phdrsize      equ     $ - phdr

section .data
msg     db      'hello world', 0AH
len     equ     $-msg

section .text
global  _start
_start: mov     edx, len
        mov     ecx, msg
        mov     ebx, 1
        mov     eax, 4
        int     80h

        mov     ebx, 0
        mov     eax, 1
        int     80h

filesize      equ     $ - $$

Scoring

  • "Statements" (counting mov, int): 8
  • "Functions, types, variables" (counting org, db, dw, dd, equ, global _start): 37
  • "Source files": 1
  • "Forward declarations" (counting dd _start, dd filesize, dw ehdrsize, dw phdrsize: 4
  • "Control structures" (counting ehdr:, phdr:, section .data, ,section .text, _start:): 5
\$\endgroup\$
6
votes
\$\begingroup\$

PHP/HTML/CSS (88pts)

All the code is available here : https://github.com/martin-damien/code-golf_hello-world

  • This "Hello World" use the Twig template language for PHP (http://twig.sensiolabs.org/).
  • I use an autoload mecanism to simply load classes on the fly.
  • I use a Page class that could handle as many type of elements (implementing the XMLElement interface) and restitute all those lement in a correct XML format.
  • Finally, I use shiny CSS to display a beautifull "Hello World" :)

index.php

<?php

/*
 * SCORE ( 18 pts )
 *
 * file : 1
 * statements : 11
 * variables : 6 (arrays and class instance are counted as a variable)
 */

/*
 * We use the PHP's autoload function to load dynamicaly classes.
 */
require_once("autoload.php");

/*
 * We use a template engine because as you know it is far better
 * to use MVC :-)
 */
require_once("lib/twig/lib/Twig/Autoloader.php");
Twig_Autoloader::register();

/*
 * We create a new Twig Environment with debug and templates cache.
 */
$twig = new Twig_Environment(

    new Twig_Loader_Filesystem(

        "design/templates" /* The place where to look for templates */

    ),
    array(
        'debug' => true,
        'cache' => 'var/cache/templates'
    )

);
/* 
 * We add the debug extension because we should be able to detect what is wrong if needed
 */
$twig->addExtension(new Twig_Extension_Debug());

/*
 * We create a new page to be displayed in the body.
 */
$page = new Page();

/*
 * We add our famous title : Hello World !!!
 */
$page->add( 'Title', array( 'level' => 1, 'text' => 'Hello World' ) );

/*
 * We are now ready to render the content and display it.
 */
$final_result = $twig->render(

    'pages/hello_world.twig',
    array(

        'Page' => $page->toXML()

    )

);

/*
 * Everything is OK, we can print the final_result to the page.
 */
echo $final_result;

?>

autoload.php

<?php

/*
 * SCORE ( 7 pts )
 *
 * file : 1
 * statements : 4
 * variables : 1
 * controls: 1
 */

/**
 * Load automaticaly classes when needed.
 * @param string $class_name The name of the class we try to load.
 */
function __hello_world_autoload( $class_name )
{

    /*
     * We test if the corresponding file exists.
     */
    if ( file_exists( "classes/$class_name.php" ) )
    {
        /*
         * If we found it we load it.
         */
        require_once "classes/$class_name.php";
    }

}

spl_autoload_register( '__hello_world_autoload' );

?>

classes/Page.php

<?php

/*
 * SCORE ( 20 pts )
 *
 * file : 1
 * statements : 11
 * variables : 7
 * controls : 1
 */

/**
 * A web page.
 */
class Page
{

    /**
     * All the elements of the page (ordered)
     * @var array
     */
    private $elements;

    /**
     * Create a new page.
     */
    public function __construct()
    {
        /* Init an array for elements. */
        $this->elements = array();
    }

    /**
     * Add a new element to the list.
     * @param string $class The name of the class we wants to use.
     * @param array $options An indexed array of all the options usefull for the element.
     */
    public function add( $class, $options )
    {
        /* Add a new element to the list. */
        $this->elements[] = new $class( $options );
    }

    /**
     * Render the page to XML (by calling the toXML() of all the elements).
     */
    public function toXML()
    {

        /* Init a result string */
        $result = "";

        /*
         * Render all elements and add them to the final result.
         */
        foreach ( $this->elements as $element )
        {
            $result = $result . $element->toXML();
        }

        return $result;

    }

}

?>

classes/Title.php

<?php

/*
 * SCORE ( 13 pts )
 *
 * file : 1
 * statements : 8
 * variables : 4
 *
 */

class Title implements XMLElement
{

    private $options;

    public function __construct( $options )
    {
        $this->options = $options;
    }

    public function toXML()
    {

        $level = $this->options['level'];
        $text = $this->options['text'];

        return "<h$level>$text</h$level>";

    }

}

?>

classes/XMLElement.php

<?php

/*
 * SCORE ( 3 pts )
 *
 * file : 1
 * statements : 2
 * variables : 0
 */

/**
 * Every element that could be used in a Page must implements this interface !!!
 */
interface XMLElement
{

    /**
     * This method will be used to get the XML version of the XMLElement.
     */
    function toXML();

}

?>

design/stylesheets/hello_world.css

/*
 * SCORE ( 10 pts )
 *
 * file : 1
 * statements : 9
 */

body
{
    background: #000;
}

h1
{
    text-align: center;
    margin: 200px auto;
    font-family: "Museo";
    font-size: 200px; text-transform: uppercase;
    color: #fff;
    text-shadow: 0 0 10px #fff, 0 0 20px #fff, 0 0 30px #fff, 0 0 40px #ff00de, 0 0 70px #ff00de, 0 0 80px #ff00de, 0 0 100px #ff00de, 0 0 150px #ff00de;
}

design/templates/layouts/pagelayout.twig

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">

    <!--

        SCORE ( 11 pts )

        file: 1
        statements: html, head, title, css,  body, content, block * 2 : 8
        variables : 2 blocks defined : 2

    -->

    <head>

        <title>{% block page_title %}{% endblock %}</title>
        <link href="design/stylesheets/hello_world.css" rel="stylesheet" type="text/css" media="screen" />

    </head>

    <body>
        <div id="content">
            {% block page_content %}{% endblock %}
        </div>
    </body>

</html>

design/templates/pages/hello_world.twig

{#

    SCORE ( 6 pts )

    file : 1
    statements : 4
    variables : 1

#}

{% extends 'layouts/pagelayout.twig' %}

{% block page_title %}Hello World{% endblock %}

{% block page_content %}
    {# Display the content of the page (we use raw to avoid html_entities) #}
    {{ Page|raw }}
{% endblock %}
\$\endgroup\$
6
votes
\$\begingroup\$

Brainfuck

369 expression, 29 while loops = 398

> ; first cell empty
;; All the chars made in a generic way
;; by first adding the modulus of char by
;; 16 and then adding mutiples of 16
;; This simplifies adding more characters 
;; for later versions
------>>++++[-<++++>]<[-<+>]        ; CR
+>>++++[-<++++>]<[-<++>]            ; !
++++>>++++[-<++++>]<[-<++++++>]     ; d
---->>++++[-<++++>]<[-<+++++++>]    ; l
++>>++++[-<++++>]<[-<+++++++>]      ; r
->>++++[-<++++>]<[-<+++++++>]       ; o
+++++++>>++++[-<++++>]<[-<+++++++>] ; w
>>++++[-<++++>]<[-<++>]             ; space
---->>++++[-<++++>]<[-<+++>]        ; comma
->>++++[-<++++>]<[-<+++++++>]       ; o
---->>++++[-<++++>]<[-<+++++++>]    ; l
---->>++++[-<++++>]<[-<+++++++>]    ; l
+++++>>++++[-<++++>]<[-<++++++>]    ; e
-------->>++++[-<++++>]<[-<+++++++>]; h
<[.<] ; print until the first empty cell

Output as from K&R The C Programming Language example:

hello, world!
\$\endgroup\$
5
votes
\$\begingroup\$

Ti-Basic 84, 1 Point

:Disp "HELLO WORLD!"

Ti-Basic is pretty basic. But if you really want a justified explanation, here it is:

: starts every command, function, statement, structure, subprogram, you name it

Disp is a predefined function that displays a parameter on the screen

akawhitespace Lets the function Disp know that it has been called and that a parameter should follow the single character of whitespace which actually comes pasted in along with Disp

" Starts defining the string literal

HELLO WORLD Part of the text in the string literal

! Although it is a factorial math operator, it is not evaluated because it is inside a string literal

" Ends the definition of the string literal

\$\endgroup\$
5
votes
\$\begingroup\$

So, I have a very... ... ...peculiar manager. He has this strange idea that the simpler a program is, the more beautiful, the more artistic it should be. Since the Hello World is arguably one of the easiest programs to write, he has asked for something so great he could hang on the wall. After doing some research, he insisted that the thing be written in Piet.

Now, I am not one to question the merits of the most intelligent person to ever grace upper management, so I was tasked with "writing" this program, which can be run on this online piet interpreter. Maybe it's time to look for a more sane manager...

enter image description here

\$\endgroup\$
  • \$\begingroup\$ Plus one for being esoteric. Also, there are dozens of unique "Hello World" programs in Piet, my favorite is the animated one. \$\endgroup\$ – Draco18s Jan 22 '16 at 19:36
4
votes
\$\begingroup\$

A Lipogram in C:

int main(){
    printf("H%cllo World\n", 'd'+1);
}

Th ky btwn 'w' and 'r' on my computr is brokn. It causs problms with som languags. Almost all pr-compilr dirctivs in C us that lttr. Th abov cod spits out warnings about an implicit dclaration of printf(), sinc I cannot us #includ(stdio.h), but it runs fin.

\$\endgroup\$
  • 1
    \$\begingroup\$ you typed "use", though... \$\endgroup\$ – Supuhstar May 3 '14 at 9:14
3
votes
\$\begingroup\$

Ill put this up for reference as community wiki. It is a C# one with bad practices. I define my own ascii data structure. I don't want this to be a competitor but rather "Kid's, you see that man over there... if you don't eat your vegetables you will become like him" kind of example.

IF YOU ARE EASILY DISTURBED BY BAD CODE LOOK AWAY NOW

I usually use this to scare children on Halloween. You should also note that I could not fit all my 256 ascii characters on here because the total chars shoots to around 40,000. Don't try and reproduce this for 2 reasons:

  • It's terrible, horrible, worse than code golf code code.
  • I wrote a program to write most of it.

So uhh... yeah "enjoy!". Also if you enjoy cleaning and improving code cough code review cough this could keep you busy for a while if you are looking for a non-profitable occupation.

namespace System
{
    class P
    {
        static void Main()
        {
            Bit t = new Bit { State = true };
            Bit f = new Bit { State = false };

            Nybble n0 = new Nybble() { Bits = new Bit[4] { f, f, f, f } };
            Nybble n1 = new Nybble() { Bits = new Bit[4] { f, f, f, t } };
            Nybble n2 = new Nybble() { Bits = new Bit[4] { f, f, t, f } };
            Nybble n3 = new Nybble() { Bits = new Bit[4] { f, f, t, t } };
            Nybble n4 = new Nybble() { Bits = new Bit[4] { f, t, f, f } };
            Nybble n5 = new Nybble() { Bits = new Bit[4] { f, t, f, t } };
            Nybble n6 = new Nybble() { Bits = new Bit[4] { f, t, t, f } };
            Nybble n7 = new Nybble() { Bits = new Bit[4] { f, t, t, t } };
            Nybble n8 = new Nybble() { Bits = new Bit[4] { t, f, f, f } };
            Nybble n9 = new Nybble() { Bits = new Bit[4] { t, f, f, t } };
            Nybble n10 = new Nybble() { Bits = new Bit[4] { t, f, t, f } };
            Nybble n11 = new Nybble() { Bits = new Bit[4] { t, f, t, t } };
            Nybble n12 = new Nybble() { Bits = new Bit[4] { t, t, f, f } };
            Nybble n13 = new Nybble() { Bits = new Bit[4] { t, t, f, t } };
            Nybble n14 = new Nybble() { Bits = new Bit[4] { t, t, t, f } };
            Nybble n15 = new Nybble() { Bits = new Bit[4] { t, t, t, t } };

            HByte b0 = new HByte() { Nybbles = new Nybble[2] { n0, n0 } };
            HByte b1 = new HByte() { Nybbles = new Nybble[2] { n0, n1 } };
            HByte b2 = new HByte() { Nybbles = new Nybble[2] { n0, n2 } };
            HByte b3 = new HByte() { Nybbles = new Nybble[2] { n0, n3 } };
            HByte b4 = new HByte() { Nybbles = new Nybble[2] { n0, n4 } };
            HByte b5 = new HByte() { Nybbles = new Nybble[2] { n0, n5 } };
            HByte b6 = new HByte() { Nybbles = new Nybble[2] { n0, n6 } };
            HByte b7 = new HByte() { Nybbles = new Nybble[2] { n0, n7 } };
            HByte b8 = new HByte() { Nybbles = new Nybble[2] { n0, n8 } };
            HByte b9 = new HByte() { Nybbles = new Nybble[2] { n0, n9 } };
            HByte b10 = new HByte() { Nybbles = new Nybble[2] { n0, n10 } };
            HByte b11 = new HByte() { Nybbles = new Nybble[2] { n0, n11 } };
            HByte b12 = new HByte() { Nybbles = new Nybble[2] { n0, n12 } };
            HByte b13 = new HByte() { Nybbles = new Nybble[2] { n0, n13 } };
            HByte b14 = new HByte() { Nybbles = new Nybble[2] { n0, n14 } };
            HByte b15 = new HByte() { Nybbles = new Nybble[2] { n0, n15 } };
            HByte b16 = new HByte() { Nybbles = new Nybble[2] { n1, n0 } };
            HByte b17 = new HByte() { Nybbles = new Nybble[2] { n1, n1 } };
            HByte b18 = new HByte() { Nybbles = new Nybble[2] { n1, n2 } };
            HByte b19 = new HByte() { Nybbles = new Nybble[2] { n1, n3 } };
            HByte b20 = new HByte() { Nybbles = new Nybble[2] { n1, n4 } };
            HByte b21 = new HByte() { Nybbles = new Nybble[2] { n1, n5 } };
            HByte b22 = new HByte() { Nybbles = new Nybble[2] { n1, n6 } };
            HByte b23 = new HByte() { Nybbles = new Nybble[2] { n1, n7 } };
            HByte b24 = new HByte() { Nybbles = new Nybble[2] { n1, n8 } };
            HByte b25 = new HByte() { Nybbles = new Nybble[2] { n1, n9 } };
            HByte b26 = new HByte() { Nybbles = new Nybble[2] { n1, n10 } };
            HByte b27 = new HByte() { Nybbles = new Nybble[2] { n1, n11 } };
            HByte b28 = new HByte() { Nybbles = new Nybble[2] { n1, n12 } };
            HByte b29 = new HByte() { Nybbles = new Nybble[2] { n1, n13 } };
            HByte b30 = new HByte() { Nybbles = new Nybble[2] { n1, n14 } };
            HByte b31 = new HByte() { Nybbles = new Nybble[2] { n1, n15 } };
            HByte b32 = new HByte() { Nybbles = new Nybble[2] { n2, n0 } };
            HByte b33 = new HByte() { Nybbles = new Nybble[2] { n2, n1 } };
            HByte b34 = new HByte() { Nybbles = new Nybble[2] { n2, n2 } };
            HByte b35 = new HByte() { Nybbles = new Nybble[2] { n2, n3 } };
            HByte b36 = new HByte() { Nybbles = new Nybble[2] { n2, n4 } };
            HByte b37 = new HByte() { Nybbles = new Nybble[2] { n2, n5 } };
            HByte b38 = new HByte() { Nybbles = new Nybble[2] { n2, n6 } };
            HByte b39 = new HByte() { Nybbles = new Nybble[2] { n2, n7 } };
            HByte b40 = new HByte() { Nybbles = new Nybble[2] { n2, n8 } };
            HByte b41 = new HByte() { Nybbles = new Nybble[2] { n2, n9 } };
            HByte b42 = new HByte() { Nybbles = new Nybble[2] { n2, n10 } };
            HByte b43 = new HByte() { Nybbles = new Nybble[2] { n2, n11 } };
            HByte b44 = new HByte() { Nybbles = new Nybble[2] { n2, n12 } };
            HByte b45 = new HByte() { Nybbles = new Nybble[2] { n2, n13 } };
            HByte b46 = new HByte() { Nybbles = new Nybble[2] { n2, n14 } };
            HByte b47 = new HByte() { Nybbles = new Nybble[2] { n2, n15 } };
            HByte b48 = new HByte() { Nybbles = new Nybble[2] { n3, n0 } };
            HByte b49 = new HByte() { Nybbles = new Nybble[2] { n3, n1 } };
            HByte b50 = new HByte() { Nybbles = new Nybble[2] { n3, n2 } };
            HByte b51 = new HByte() { Nybbles = new Nybble[2] { n3, n3 } };
            HByte b52 = new HByte() { Nybbles = new Nybble[2] { n3, n4 } };
            HByte b53 = new HByte() { Nybbles = new Nybble[2] { n3, n5 } };
            HByte b54 = new HByte() { Nybbles = new Nybble[2] { n3, n6 } };
            HByte b55 = new HByte() { Nybbles = new Nybble[2] { n3, n7 } };
            HByte b56 = new HByte() { Nybbles = new Nybble[2] { n3, n8 } };
            HByte b57 = new HByte() { Nybbles = new Nybble[2] { n3, n9 } };
            HByte b58 = new HByte() { Nybbles = new Nybble[2] { n3, n10 } };
            HByte b59 = new HByte() { Nybbles = new Nybble[2] { n3, n11 } };
            HByte b60 = new HByte() { Nybbles = new Nybble[2] { n3, n12 } };
            HByte b61 = new HByte() { Nybbles = new Nybble[2] { n3, n13 } };
            HByte b62 = new HByte() { Nybbles = new Nybble[2] { n3, n14 } };
            HByte b63 = new HByte() { Nybbles = new Nybble[2] { n3, n15 } };
            HByte b64 = new HByte() { Nybbles = new Nybble[2] { n4, n0 } };
            HByte b65 = new HByte() { Nybbles = new Nybble[2] { n4, n1 } };
            HByte b66 = new HByte() { Nybbles = new Nybble[2] { n4, n2 } };
            HByte b67 = new HByte() { Nybbles = new Nybble[2] { n4, n3 } };
            HByte b68 = new HByte() { Nybbles = new Nybble[2] { n4, n4 } };
            HByte b69 = new HByte() { Nybbles = new Nybble[2] { n4, n5 } };
            HByte b70 = new HByte() { Nybbles = new Nybble[2] { n4, n6 } };
            HByte b71 = new HByte() { Nybbles = new Nybble[2] { n4, n7 } };
            HByte b72 = new HByte() { Nybbles = new Nybble[2] { n4, n8 } };
            HByte b73 = new HByte() { Nybbles = new Nybble[2] { n4, n9 } };
            HByte b74 = new HByte() { Nybbles = new Nybble[2] { n4, n10 } };
            HByte b75 = new HByte() { Nybbles = new Nybble[2] { n4, n11 } };
            HByte b76 = new HByte() { Nybbles = new Nybble[2] { n4, n12 } };
            HByte b77 = new HByte() { Nybbles = new Nybble[2] { n4, n13 } };
            HByte b78 = new HByte() { Nybbles = new Nybble[2] { n4, n14 } };
            HByte b79 = new HByte() { Nybbles = new Nybble[2] { n4, n15 } };
            HByte b80 = new HByte() { Nybbles = new Nybble[2] { n5, n0 } };
            HByte b81 = new HByte() { Nybbles = new Nybble[2] { n5, n1 } };
            HByte b82 = new HByte() { Nybbles = new Nybble[2] { n5, n2 } };
            HByte b83 = new HByte() { Nybbles = new Nybble[2] { n5, n3 } };
            HByte b84 = new HByte() { Nybbles = new Nybble[2] { n5, n4 } };
            HByte b85 = new HByte() { Nybbles = new Nybble[2] { n5, n5 } };
            HByte b86 = new HByte() { Nybbles = new Nybble[2] { n5, n6 } };
            HByte b87 = new HByte() { Nybbles = new Nybble[2] { n5, n7 } };
            HByte b88 = new HByte() { Nybbles = new Nybble[2] { n5, n8 } };
            HByte b89 = new HByte() { Nybbles = new Nybble[2] { n5, n9 } };
            HByte b90 = new HByte() { Nybbles = new Nybble[2] { n5, n10 } };
            HByte b91 = new HByte() { Nybbles = new Nybble[2] { n5, n11 } };
            HByte b92 = new HByte() { Nybbles = new Nybble[2] { n5, n12 } };
            HByte b93 = new HByte() { Nybbles = new Nybble[2] { n5, n13 } };
            HByte b94 = new HByte() { Nybbles = new Nybble[2] { n5, n14 } };
            HByte b95 = new HByte() { Nybbles = new Nybble[2] { n5, n15 } };
            HByte b96 = new HByte() { Nybbles = new Nybble[2] { n6, n0 } };
            HByte b97 = new HByte() { Nybbles = new Nybble[2] { n6, n1 } };
            HByte b98 = new HByte() { Nybbles = new Nybble[2] { n6, n2 } };
            HByte b99 = new HByte() { Nybbles = new Nybble[2] { n6, n3 } };
            HByte b100 = new HByte() { Nybbles = new Nybble[2] { n6, n4 } };
            HByte b101 = new HByte() { Nybbles = new Nybble[2] { n6, n5 } };
            HByte b102 = new HByte() { Nybbles = new Nybble[2] { n6, n6 } };
            HByte b103 = new HByte() { Nybbles = new Nybble[2] { n6, n7 } };
            HByte b104 = new HByte() { Nybbles = new Nybble[2] { n6, n8 } };
            HByte b105 = new HByte() { Nybbles = new Nybble[2] { n6, n9 } };
            HByte b106 = new HByte() { Nybbles = new Nybble[2] { n6, n10 } };
            HByte b107 = new HByte() { Nybbles = new Nybble[2] { n6, n11 } };
            HByte b108 = new HByte() { Nybbles = new Nybble[2] { n6, n12 } };
            HByte b109 = new HByte() { Nybbles = new Nybble[2] { n6, n13 } };
            HByte b110 = new HByte() { Nybbles = new Nybble[2] { n6, n14 } };
            HByte b111 = new HByte() { Nybbles = new Nybble[2] { n6, n15 } };
            HByte b112 = new HByte() { Nybbles = new Nybble[2] { n7, n0 } };
            HByte b113 = new HByte() { Nybbles = new Nybble[2] { n7, n1 } };
            HByte b114 = new HByte() { Nybbles = new Nybble[2] { n7, n2 } };
            HByte b115 = new HByte() { Nybbles = new Nybble[2] { n7, n3 } };
            HByte b116 = new HByte() { Nybbles = new Nybble[2] { n7, n4 } };
            HByte b117 = new HByte() { Nybbles = new Nybble[2] { n7, n5 } };
            HByte b118 = new HByte() { Nybbles = new Nybble[2] { n7, n6 } };
            HByte b119 = new HByte() { Nybbles = new Nybble[2] { n7, n7 } };
            HByte b120 = new HByte() { Nybbles = new Nybble[2] { n7, n8 } };

            HChar c0 = new HChar() { Code = b0 };
            HChar c1 = new HChar() { Code = b1 };
            HChar c2 = new HChar() { Code = b2 };
            HChar c3 = new HChar() { Code = b3 };
            HChar c4 = new HChar() { Code = b4 };
            HChar c5 = new HChar() { Code = b5 };
            HChar c6 = new HChar() { Code = b6 };
            HChar c7 = new HChar() { Code = b7 };
            HChar c8 = new HChar() { Code = b8 };
            HChar c9 = new HChar() { Code = b9 };
            HChar c10 = new HChar() { Code = b10 };
            HChar c11 = new HChar() { Code = b11 };
            HChar c12 = new HChar() { Code = b12 };
            HChar c13 = new HChar() { Code = b13 };
            HChar c14 = new HChar() { Code = b14 };
            HChar c15 = new HChar() { Code = b15 };
            HChar c16 = new HChar() { Code = b16 };
            HChar c17 = new HChar() { Code = b17 };
            HChar c18 = new HChar() { Code = b18 };
            HChar c19 = new HChar() { Code = b19 };
            HChar c20 = new HChar() { Code = b20 };
            HChar c21 = new HChar() { Code = b21 };
            HChar c22 = new HChar() { Code = b22 };
            HChar c23 = new HChar() { Code = b23 };
            HChar c24 = new HChar() { Code = b24 };
            HChar c25 = new HChar() { Code = b25 };
            HChar c26 = new HChar() { Code = b26 };
            HChar c27 = new HChar() { Code = b27 };
            HChar c28 = new HChar() { Code = b28 };
            HChar c29 = new HChar() { Code = b29 };
            HChar c30 = new HChar() { Code = b30 };
            HChar c31 = new HChar() { Code = b31 };
            HChar c32 = new HChar() { Code = b32 };
            HChar c33 = new HChar() { Code = b33 };
            HChar c34 = new HChar() { Code = b34 };
            HChar c35 = new HChar() { Code = b35 };
            HChar c36 = new HChar() { Code = b36 };
            HChar c37 = new HChar() { Code = b37 };
            HChar c38 = new HChar() { Code = b38 };
            HChar c39 = new HChar() { Code = b39 };
            HChar c40 = new HChar() { Code = b40 };
            HChar c41 = new HChar() { Code = b41 };
            HChar c42 = new HChar() { Code = b42 };
            HChar c43 = new HChar() { Code = b43 };
            HChar c44 = new HChar() { Code = b44 };
            HChar c45 = new HChar() { Code = b45 };
            HChar c46 = new HChar() { Code = b46 };
            HChar c47 = new HChar() { Code = b47 };
            HChar c48 = new HChar() { Code = b48 };
            HChar c49 = new HChar() { Code = b49 };
            HChar c50 = new HChar() { Code = b50 };
            HChar c51 = new HChar() { Code = b51 };
            HChar c52 = new HChar() { Code = b52 };
            HChar c53 = new HChar() { Code = b53 };
            HChar c54 = new HChar() { Code = b54 };
            HChar c55 = new HChar() { Code = b55 };
            HChar c56 = new HChar() { Code = b56 };
            HChar c57 = new HChar() { Code = b57 };
            HChar c58 = new HChar() { Code = b58 };
            HChar c59 = new HChar() { Code = b59 };
            HChar c60 = new HChar() { Code = b60 };
            HChar c61 = new HChar() { Code = b61 };
            HChar c62 = new HChar() { Code = b62 };
            HChar c63 = new HChar() { Code = b63 };
            HChar c64 = new HChar() { Code = b64 };
            HChar c65 = new HChar() { Code = b65 };
            HChar c66 = new HChar() { Code = b66 };
            HChar c67 = new HChar() { Code = b67 };
            HChar c68 = new HChar() { Code = b68 };
            HChar c69 = new HChar() { Code = b69 };
            HChar c70 = new HChar() { Code = b70 };
            HChar c71 = new HChar() { Code = b71 };
            HChar c72 = new HChar() { Code = b72 };
            HChar c73 = new HChar() { Code = b73 };
            HChar c74 = new HChar() { Code = b74 };
            HChar c75 = new HChar() { Code = b75 };
            HChar c76 = new HChar() { Code = b76 };
            HChar c77 = new HChar() { Code = b77 };
            HChar c78 = new HChar() { Code = b78 };
            HChar c79 = new HChar() { Code = b79 };
            HChar c80 = new HChar() { Code = b80 };
            HChar c81 = new HChar() { Code = b81 };
            HChar c82 = new HChar() { Code = b82 };
            HChar c83 = new HChar() { Code = b83 };
            HChar c84 = new HChar() { Code = b84 };
            HChar c85 = new HChar() { Code = b85 };
            HChar c86 = new HChar() { Code = b86 };
            HChar c87 = new HChar() { Code = b87 };
            HChar c88 = new HChar() { Code = b88 };
            HChar c89 = new HChar() { Code = b89 };
            HChar c90 = new HChar() { Code = b90 };
            HChar c91 = new HChar() { Code = b91 };
            HChar c92 = new HChar() { Code = b92 };
            HChar c93 = new HChar() { Code = b93 };
            HChar c94 = new HChar() { Code = b94 };
            HChar c95 = new HChar() { Code = b95 };
            HChar c96 = new HChar() { Code = b96 };
            HChar c97 = new HChar() { Code = b97 };
            HChar c98 = new HChar() { Code = b98 };
            HChar c99 = new HChar() { Code = b99 };
            HChar c100 = new HChar() { Code = b100 };
            HChar c101 = new HChar() { Code = b101 };
            HChar c102 = new HChar() { Code = b102 };
            HChar c103 = new HChar() { Code = b103 };
            HChar c104 = new HChar() { Code = b104 };
            HChar c105 = new HChar() { Code = b105 };
            HChar c106 = new HChar() { Code = b106 };
            HChar c107 = new HChar() { Code = b107 };
            HChar c108 = new HChar() { Code = b108 };
            HChar c109 = new HChar() { Code = b109 };
            HChar c110 = new HChar() { Code = b110 };
            HChar c111 = new HChar() { Code = b111 };
            HChar c112 = new HChar() { Code = b112 };
            HChar c113 = new HChar() { Code = b113 };
            HChar c114 = new HChar() { Code = b114 };
            HChar c115 = new HChar() { Code = b115 };
            HChar c116 = new HChar() { Code = b116 };
            HChar c117 = new HChar() { Code = b117 };
            HChar c118 = new HChar() { Code = b118 };
            HChar c119 = new HChar() { Code = b119 };
            HChar c120 = new HChar() { Code = b120 };

            //72 101 108 108 111 32 87 111 114 108 100 
            Console.WriteLine(c72.ToChar() + "" + c101.ToChar() + c108.ToChar() + c108.ToChar() + c111.ToChar() + c32.ToChar() + c87.ToChar() + c111.ToChar() + c114.ToChar() + c108.ToChar() + c100.ToChar());
            Console.ReadLine();
        }

        public static string FixString(string s, int length)
        {
            return s.Length < length ? FixString("0" + s, length) : s;
        }

    }

    class HChar
    {
        private HByte code;

        public HChar()
        {
            code = new HByte();
        }

        public HByte Code
        {
            get
            {
                return code;
            }
            set
            {
                code = value;
            }
        }

        public char ToChar()
        {
            return (char)Convert.ToUInt32(code + "", 2);
        }

        public override string ToString()
        {
            return base.ToString();
        }

    }

    struct Bit
    {
        private bool state;

        public bool State
        {
            get
            {
                return state;
            }
            set
            {
                state = value;
            }
        }

        public override string ToString()
        {
            return state ? "1" : "0";
        }
    }

    class Nybble
    {
        private Bit[] bits;

        public Nybble()
        {
            bits = new Bit[4];
        }

        public Bit[] Bits
        {
            get
            {
                return bits;
            }
            set
            {
                bits = value;
            }
        }

        public static Nybble Parse(string s)
        {
            s = P.FixString(s, 4);

            Nybble n = new Nybble();

            for (int i = 0; i < 4; i++)
            {
                n.bits[i].State = s[i] == '1';
            }

            return n;
        }


        public override string ToString()
        {
            Text.StringBuilder sb = new Text.StringBuilder();

            foreach (Bit b in bits )
            {
                sb.Append(b + "");
            }

            return sb + "";
        }
    }

    class HByte
    {
        private Nybble[] nybbles;

        public HByte()
        {
            nybbles = new Nybble[2];
        }

        public Nybble[] Nybbles
        {
            get
            {
                return nybbles;
            }
            set
            {
                nybbles = value;
            }
        }

        public static HByte SetAsByte(byte b)
        {
            var hb = new HByte();
            hb.Nybbles[0] = Nybble.Parse(Convert.ToString((byte)(b << 4) >> 4, 2));
            hb.Nybbles[1] = Nybble.Parse(Convert.ToString((b >> 4), 2));
            return hb;
        }

        public static HByte Parse(string s)
        {
            s = P.FixString(s, 8);
            var hb = new HByte();
            for (int i = 0; i < 2; i++)
                hb.Nybbles[i] = Nybble.Parse(s.Substring(i * 4, 4));
            return hb;
        }

        public override string ToString()
        {
            return nybbles[0] + "" + nybbles[1];
        }
    }
}
\$\endgroup\$
  • 6
    \$\begingroup\$ Seems like normal C#-code that's in production ;) \$\endgroup\$ – german_guy Feb 26 '14 at 15:13
2
votes
\$\begingroup\$
package my.complex.hello.world;

/**
 * Messages have the purpose to be passed as communication between
 * different parts of the system.
 * @param <B> The type of the message content.
 */
public interface Message<B> {

    /**
     * Returns the body of the message.
     * @return The body of the message.
     */
    public B getMessageBody();

    /**
     * Shows this message in the given display.
     * @param display The {@linkplain Display} where the message should be show.
     */
    public void render(Display display);
}
package my.complex.hello.world;

/**
 * This abstract class is a partial implementation of the {@linkplain Message}
 * interface, which provides a implementation for the {@linkplain #getMessageBody()}
 * method.
 * @param <B> The type of the message content.
 */
public abstract class AbstractGenericMessageImpl<B> implements Message<B> {

    private B messageBody;

    public GenericMessageImpl(B messageBody) {
        this.messageBody = messageBody;
    }

    public void setMessageBody(B messageBody) {
        this.messageBody = messageBody;
    }

    @Override
    public B getMessageBody() {
        return messageContent;
    }
}
package my.complex.hello.world;

public class StringMessage extends AbstractGenericMessageImpl<String> {

    public StringText(String text) {
        super(text);
    }

    /**
     * {@inheritDoc}
     * @param display {@inheritDoc}
     */
    @Override
    public void render(Display display) {
        if (display == null) {
            throw new IllegalArgumentException("The display should not be null.");
        }
        display.printString(text);
        display.newLine();
    }
}
package my.complex.hello.world;

import java.awt.Color;
import java.awt.Image;

/**
 * A {@code Display} is a canvas where objects can be drawn as output.
 */
public interface Display {
    public void printString(String text);
    public void newLine();
    public Color getColor();
    public void setColor(Color color);
    public Color getBackgroundColor();
    public void setBackgroundColor(Color color);
    public void setXPosition(int xPosition);
    public int getXPosition();
    public void setYPosition(int yPosition);
    public int getYPosition();
    public void setFontSize(int fontSize);
    public int getFontSize();
    public void setDrawAngle(float drawAngle);
    public float getDrawAngle();
    public void drawImage(Image image);
    public void putPixel();
}
package my.complex.hello.world;

import java.awt.Color;
import java.awt.Image;
import java.io.PrintStream;

/**
 * The {@code ConsoleDisplay} is a type of {@linkplain Display} that renders text
 * output to {@linkplain PrintWriter}s. This is a very primitive type of
 * {@linkplain Display} and is not capable of any complex drawing operations.
 * All the drawing methods throws an {@linkplain UnsupportedOpeartionException}.
 */
public class ConsoleDisplay implements Display {

    private PrintWriter writer;

    public ConsoleDisplay(PrintWriter writer) {
        this.writer = writer;
    }

    public void setWriter(PrintWriter writer) {
        this.writer = writer;
    }

    public PrintWriter getWriter() {
        return writer;
    }

    @Override
    public void printString(String text) {
        writer.print(text);
    }

    @Override
    public void newLine() {
        writer.println();
    }

    @Override
    public Color getColor() {
        throw new UnsupportedOperationExcepion("The Console display can't operate with graphics.");
    }

    @Override
    public void setColor(Color color) {
        throw new UnsupportedOperationExcepion("The Console display can't operate with graphics.");
    }

    @Override
    public Color getBackgroundColor() {
        throw new UnsupportedOperationExcepion("The Console display can't operate with graphics.");
    }

    @Override
    public void setBackgroundColor(Color color) {
        throw new UnsupportedOperationExcepion("The Console display can't operate with graphics.");
    }

    @Override
    public void setXPosition(int xPosition) {
        throw new UnsupportedOperationExcepion("The Console display can't operate with graphics.");
    }

    @Override
    public int getXPosition() {
        throw new UnsupportedOperationExcepion("The Console display can't operate with graphics.");
    }

    @Override
    public void setYPosition(int yPosition) {
        throw new UnsupportedOperationExcepion("The Console display can't operate with graphics.");
    }

    @Override
    public int getYPosition() {
        throw new UnsupportedOperationExcepion("The Console display can't operate with graphics.");
    }

    @Override
    public void setFontSize(int fontSize) {
        throw new UnsupportedOperationExcepion("The Console display can't operate with graphics.");
    }

    @Override
    public int getFontSize() {
        throw new UnsupportedOperationExcepion("The Console display can't operate with graphics.");
    }

    @Override
    public void setDrawAngle(float drawAngle) {
        throw new UnsupportedOperationExcepion("The Console display can't operate with graphics.");
    }

    @Override
    public float getDrawAngle() {
        throw new UnsupportedOperationExcepion("The Console display can't operate with graphics.");
    }

    @Override
    public void drawImage(Image image) {
        throw new UnsupportedOperationExcepion("The Console display can't operate with graphics.");
    }

    @Override
    public void putPixel() {
        throw new UnsupportedOperationExcepion("The Console display can't operate with graphics.");
    }
}
package my.complex.hello.world;

/**
 * A {@linkplain Display} is a complex object. To decouple the creation of the
 * {@linkplain Display} from it's use, an object for it's creation is needed. This
 * interface provides a way to get instances of these {@linkplain Display}s.
 */
public interface DisplayFactory {
    public Display getDisplay();
}
package my.complex.hello.world;

/**
 * A {@linkplain DisplayFactory} that always produces {@linkplain ConsoleDisplay}s
 * based on the {@linkplain System#out} field. This class is a singleton, and instances
 * should be obtained through the {@linkplain #getInstance()} method.
 */
public final class ConsoleDisplayFactory implements DisplayFactory {
    private static final ConsoleDisplayFactory instance = new ConsoleDisplayFactory();

    private final ConsoleDisplay display;

    public static ConsoleDisplayFactory getInstance() {
        return instance;
    }

    private ConsoleDisplayFactory() {
        display = new ConsoleDisplay(System.out);
    }

    @Override
    public ConsoleDisplay getDisplay() {
        return display;
    }
}
package my.complex.hello.world;

public class Main {
    public static void main(String[] args) {
        Display display = ConsoleDisplay.getInstance().getDisplay();
        StringMessage message = new StringMessage("Hello World");
        message.render(display);
    }
}

I will add some comments later.

\$\endgroup\$
  • 3
    \$\begingroup\$ "I will add some comments later." How much later? \$\endgroup\$ – celtschk Feb 24 '12 at 19:05
  • \$\begingroup\$ In function main of class Main: ConsoleDisplay does not have a member named getInstance. Did you mean ConsoleDisplayFactory? BTW, please explicitly state the language (Java I guess) and the points. \$\endgroup\$ – celtschk Apr 1 '12 at 17:33
  • \$\begingroup\$ @celtschk: a lot much later \$\endgroup\$ – Silviu Burcea Oct 15 '15 at 15:17
2
votes
\$\begingroup\$

Points: 183

  • 62 statements*
  • 10 classes + 25 methods (properties' getters & setters are distinct) + 8 variable declarations (I think) = 43 declarations of something
  • No module use statements. It does have some defaults, though, and using the full qualification was part of my bowling. So maybe 1 for System? Well, anyway, let's say 0.
  • 1 source file.
  • Not a language that uses forward declarations. Well, 1 MustOverride, which I will count.
  • 76 control statements. Not counted manually so may be slightly inaccurate.

Total: 62 + 43 + 0 + 1 + 1 + 76 = 183

Entry

Public NotInheritable Class OptimizedStringFactory
    Private Shared ReadOnly _stringCache As System.Collections.Generic.IEnumerable(Of System.Collections.Generic.IEnumerable(Of Char)) = New System.Collections.Generic.List(Of System.Collections.Generic.IEnumerable(Of Char))

    Private Shared ReadOnly Property StringCache() As System.Collections.Generic.IEnumerable(Of System.Collections.Generic.IEnumerable(Of Char))
        Get
            Debug.Assert(OptimizedStringFactory._stringCache IsNot Nothing)

            Return OptimizedStringFactory._stringCache
        End Get
    End Property

    Public Shared Function GetOrCache(ByRef s As System.Collections.Generic.IEnumerable(Of Char)) As String
        If s IsNot Nothing Then
            Dim equalFlag As Boolean = False

            For Each cachedStringItemInCache As System.Collections.Generic.IEnumerable(Of Char) In OptimizedStringFactory.StringCache
                equalFlag = True

                For currentStringCharacterIndex As Integer = 0 To cachedStringItemInCache.Count() - 1
                    If equalFlag AndAlso cachedStringItemInCache.Skip(currentStringCharacterIndex).FirstOrDefault() <> s.Skip(currentStringCharacterIndex).FirstOrDefault() Then
                        equalFlag = False
                    End If
                Next

                If Not equalFlag Then
                    Continue For
                End If

                Return New String(cachedStringItemInCache.ToArray())
            Next

            DirectCast(OptimizedStringFactory.StringCache, System.Collections.Generic.IList(Of System.Collections.Generic.IEnumerable(Of Char))).Add(s)

            Return OptimizedStringFactory.GetOrCache(s)
        End If
    End Function
End Class

Public MustInherit Class ConcurrentCharacterOutputter
    Public Event OutputComplete()

    Private _previousCharacter As ConcurrentCharacterOutputter
    Private _canOutput, _shouldOutput As Boolean

    Public WriteOnly Property PreviousCharacter() As ConcurrentCharacterOutputter
        Set(ByVal value As ConcurrentCharacterOutputter)
            If Me._previousCharacter IsNot Nothing Then
                RemoveHandler Me._previousCharacter.OutputComplete, AddressOf Me.DoOutput
            End If

            Me._previousCharacter = value

            If value IsNot Nothing Then
                AddHandler Me._previousCharacter.OutputComplete, AddressOf Me.DoOutput
            End If
        End Set
    End Property

    Protected Property CanOutput() As Boolean
        Get
            Return _canOutput
        End Get
        Set(ByVal value As Boolean)
            Debug.Assert(value OrElse Not value)

            _canOutput = value
        End Set
    End Property

    Protected Property ShouldOutput() As Boolean
        Get
            Return _shouldOutput
        End Get
        Set(ByVal value As Boolean)
            Debug.Assert(value OrElse Not value)

            _shouldOutput = value
        End Set
    End Property

    Protected MustOverride Sub DoOutput()

    Public Sub Output()
        Me.CanOutput = True

        If Me.ShouldOutput OrElse Me._previousCharacter Is Nothing Then
            Me.CanOutput = True
            Me.DoOutput()
        End If
    End Sub

    Protected Sub Finished()
        RaiseEvent OutputComplete()
    End Sub
End Class

Public NotInheritable Class HCharacter
    Inherits ConcurrentCharacterOutputter

    Protected Overrides Sub DoOutput()
        If Me.CanOutput Then
            Console.Write("H"c)
            Me.Finished()
        Else
            Me.ShouldOutput = True
        End If
    End Sub
End Class

Public NotInheritable Class ECharacter
    Inherits ConcurrentCharacterOutputter

    Protected Overrides Sub DoOutput()
        If Me.CanOutput Then
            Console.Write("e"c)
            Me.Finished()
        Else
            Me.ShouldOutput = True
        End If
    End Sub
End Class

Public NotInheritable Class WCharacter
    Inherits ConcurrentCharacterOutputter

    Protected Overrides Sub DoOutput()
        If Me.CanOutput Then
            Console.Write("w"c)
            Me.Finished()
        Else
            Me.ShouldOutput = True
        End If
    End Sub
End Class

Public NotInheritable Class OCharacter
    Inherits ConcurrentCharacterOutputter

    Private Shared Called As Boolean = False

    Protected Overrides Sub DoOutput()
        If Me.CanOutput Then
            If OCharacter.Called Then
                Console.Write("o"c)
            Else
                Console.Write("o ")
                OCharacter.Called = True
            End If
            Me.Finished()
        Else
            Me.ShouldOutput = True
        End If
    End Sub
End Class

Public NotInheritable Class RCharacter
    Inherits ConcurrentCharacterOutputter

    Protected Overrides Sub DoOutput()
        If Me.CanOutput Then
            Console.Write("r"c)
            Me.Finished()
        Else
            Me.ShouldOutput = True
        End If
    End Sub
End Class

Public NotInheritable Class LCharacter
    Inherits ConcurrentCharacterOutputter

    Protected Overrides Sub DoOutput()
        If Me.CanOutput Then
            Console.Write("l"c)
            Me.Finished()
        Else
            Me.ShouldOutput = True
        End If
    End Sub
End Class

Public NotInheritable Class DCharacter
    Inherits ConcurrentCharacterOutputter

    Protected Overrides Sub DoOutput()
        If Me.CanOutput Then
            Console.WriteLine("d")
            Me.Finished()
        Else
            Me.ShouldOutput = True
        End If
    End Sub
End Class

Public Module MainApplicationModule
    Private Function CreateThread(ByVal c As Char) As System.Threading.Thread
        Static last As ConcurrentCharacterOutputter

        Dim a As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()
        Dim cco As ConcurrentCharacterOutputter = DirectCast(a.CreateInstance(GetType(MainApplicationModule).Namespace & "."c & Char.ToUpper(c) & "Character"), ConcurrentCharacterOutputter)
        cco.PreviousCharacter = last
        last = cco

        Return New System.Threading.Thread(AddressOf cco.Output) With {.IsBackground = True}
    End Function

    Public Sub Main()
        Dim threads As New List(Of System.Threading.Thread)

        For Each c As Char In "Helloworld"
            threads.Add(MainApplicationModule.CreateThread(c))
        Next

        For Each t As System.Threading.Thread In threads
            t.Start()
        Next

        For Each t As System.Threading.Thread In threads
            t.Join()
        Next
    End Sub
End Module

Documentation

  • There are no comments in the code. This helps reduce clutter, and comments are unnecessary regardless because I am the sole developer and we have this amazing, detailed documentation - once again written by yours truly.
  • The OptimizedStringFactory holds optimized strings. It has a cache that allows references to efficient IEnumerable(Of Char)s to be used, while avoiding the inherent problems of references. It has been brought to my attention that .NET includes some kind of string pool. However, built-in caching doesn't know enough about the objects we are using - it's unreliable, so I have created my own solution.
  • The ConcurrentOutputCharacter class allows for easy synchronization of multithreaded, single-character output. This stops the output from getting garbled. In the best practices of object-oriented programming, it's declared MustInherit and every character or string to output is derived from it, and also declared NotInheritable. It contains several assertions to assure valid data is being passed.
  • Each *Character contains a single character for our specific case of string output.
  • The main module contains the code for creating the threads. Threading is a very new feature that allows us to take advantage of multicore processors and process output more efficiently. To prevent code duplication, I've used a loop to create the characters.

Beautiful, no?

It's even extensible, due to the aforementioned loops and inheritance, plus the dynamic, reflection-based class loading. This also prevents overzealous obfuscation, so nobody can claim our code by obfuscating it. To change the strings, simply create a dictionary that maps input characters to different output character classes before the reflection code loads them dynamically.

\$\endgroup\$
  • 3
    \$\begingroup\$ As is, this program does not implement the specification. It outputs a comma after the "Hello" and an exclamation mark after the "world". I don't find where it outputs the newline (but maybe I missed it). Also, at the end it waits for a key to be pressed, contrary to the specification. \$\endgroup\$ – celtschk Feb 7 '12 at 20:31
  • 1
    \$\begingroup\$ What language is it, VB? Can I run it on Linux? \$\endgroup\$ – user unknown Feb 7 '12 at 21:09
  • \$\begingroup\$ @userunknown: VB.NET. You can use Mono to run it on Linux. \$\endgroup\$ – Ry- Feb 7 '12 at 23:56
  • 2
    \$\begingroup\$ @celtschk: Corrected now. It's extensible after all ;) \$\endgroup\$ – Ry- Feb 7 '12 at 23:57
  • \$\begingroup\$ The process of counting is still going on? \$\endgroup\$ – user unknown Feb 12 '12 at 1:43
2
votes
\$\begingroup\$

Javascript, a LOT of points

  • Fully integrated i18n support
  • Multiplatform JS, can run on Node and web browsers with customizable context (browsers should use "window")
  • Configurable data source, uses static "Hello world" message by default (for performance)
  • Completely async, great concurrency
  • Good debugging mode, with time analysis on code invoke.

Here we go:

(function(context){
    /**
     * Basic app configuration
    */
    var config = {
        DEBUG:            true,
        WRITER_SIGNATURE: "write",
        LANGUAGE:         "en-US" // default language
    };

    /**
     * Hardcoded translation data
    */
    var translationData = {
        "en-US": {
            "hello_world":       "Hello World!", // greeting in main view
            "invocation":        "invoked", // date of invokation
            "styled_invocation": "[%str%]" // some decoration for better style
        }
    };

    /**
     * Internationalization module
     * Supports dynamic formatting and language pick after load
    */
    var i18n = (function(){
        return {
            format: function(source, info){ // properly formats a i18n resource
                return source.replace("%str%", info);
            },
            originTranslate: function(origin){
                var invoc_stf = i18n.translate("invocation") + " " + origin.lastModified;
                return i18n.format(i18n.translate("styled_invocation"), invoc_stf);
            },
            translate: function(message){
                var localData = translationData[config.LANGUAGE];
                return localData[message];
            },
            get: function(message, origin){
                var timestamp = origin.lastModified;
                if(config.DEBUG)
                    return i18n.translate(message) + " " + i18n.originTranslate(origin);
                else
                    return i18n.translate(message);
            }
        };
    }());

    /**
     * A clone of a document-wrapper containing valid, ready DOM
    */
    var fallbackDocument = function(){
        var _document = function(){
            this.native_context = context;
            this.modules = new Array();
        };
        _document.prototype.clear = function(){
            for(var i = 0; i < this.modules.length; i++){
                var module = this.modules[i];
                module.signalClear();
            };
        };

        return _document;
    };

    /**
     * Provides a native document, scoped to the context
     * Uses a fallback if document not initialized or not supported
    */
    var provideDocument = function(){
        if(typeof context.document == "undefined")
            context.document = new fallbackDocument();
        context.document.lastModified = new context.Date();
        context.document.exception = function(string_exception){
            this.origin = context.navigator;
            this.serialized = string_exception;
        };

        return context.document;
    };

    /**
     * Sends a data request, and tries to call the document writer
    */
    var documentPrinter = function(document, dataCallback){
        if(dataCallback == null)
            throw new document.exception("Did not receive a data callback!");
        data = i18n.get(dataCallback(), document); // translate data into proper lang.
        if(typeof document[config.WRITER_SIGNATURE] == "undefined")
            throw new document.exception("Document provides no valid writer!");

        var writer = document[config.WRITER_SIGNATURE]; 
        writer.apply(document, [data]); //apply the writer using correct context
    };

    /**
     * Produces a "Hello world" message-box
     * Warning! Message may vary depending on initial configuration
    */
    var HelloWorldFactory = (function(){
        return function(){
            this.produceMessage = function(){
                this.validDocument = provideDocument();
                new documentPrinter(this.validDocument, function(){
                    return "hello_world";
                });
            };
        };
    }());

    context.onload = function(){ // f**k yeah! we are ready
        try{
        var newFactory = new HelloWorldFactory();
        newFactory.produceMessage();
        } catch(err){
            console.log(err); // silently log the error
        };
    };
}(window || {}));
\$\endgroup\$
1
vote
\$\begingroup\$

C Program for Hello World:9(?)

#include<stdio.h>
void main(){
char a[100]={4,1,8,8,11,-68,19,11,14,8,0,0};
for(;a[12]<a[4];a[12]++)
 {
    printf("%c",sizeof(a)+a[a[12]]);
 }
}

Combination of ASCII Characters and character array containing integer! Basically,Printing Every digit in character format.

\$\endgroup\$
  • \$\begingroup\$ +1 cause it's pretty awesome, but how do you justify i? \$\endgroup\$ – izabera Feb 26 '14 at 21:09
  • \$\begingroup\$ oops!was using i as a for loop counter.forgot to remove it's declaration. Thanks for Noticing. \$\endgroup\$ – Sushant Parab Feb 27 '14 at 5:56
1
vote
\$\begingroup\$

Python using if-else statements

from itertools import permutations
from sys import stdout, argv

reference = { 100: 'd', 101: 'e', 104: 'h', 108: 'l', 111: 'o', 114: 'r', 119: 'w' }
vowels = [ 'e', 'o' ]
words = [ 
    { 'len': 5, 'first': 104, 'last': 111, 'repeat': True, 'r_char': 108 }, 
    { 'len': 5, 'first': 119, 'last': 100, 'repeat': False, 'r_char': None }
    ]
second_last = 108

def find_words(repeat, r_char):
    output = []
    chars = [ y for x, y in reference.iteritems() ]
    if repeat:
        chars.append(reference[r_char])
    for value in xrange(0, len(chars)):
        output += [ x for x in permutations(chars[value:]) ]
    return output

def filter_word(value, first, last, repeat, r_char):
    output = False
    value = [ x for x in value ]
    first_char, second_char, second_last_char, last_char = value[0], value[1], value[-2], value[-1]
    if first_char == first and last_char == last and second_char != last_char and ord(second_last_char) == second_last:
        if second_char in vowels and second_char in [ y for x, y in reference.iteritems() ]:
            string = []
            last = None
            for char in value:
                if last != None:
                    if char == last and char not in vowels:
                        string.append(char)
                    elif char != last:
                        string.append(char)
                else:
                    string.append(char)
                last = char
            if len(string) == len(value):
                if repeat:
                    last = None
                    for char in value:
                        if last != None:
                            if char == last:
                                output = True
                        last = char
                else:
                    third_char = value[2]
                    if ord(third_char) > ord(second_last_char) and ord(second_char) > ord(second_last_char):
                        output = True
    return output

def find_word(values, first, last, length, repeat, r_char):
    first, last, output, items, count = reference[first], reference[last], [], [], 0
    if repeat:
        r_char = reference[r_char]
    for value in values:
        count += 1
        for item in [ x[:length] for x in permutations(value) ]:
            item = ''.join(item)
            if item not in items and filter_word(value=item, first=first, last=last, r_char=r_char, repeat=repeat):
                items.append(item)
        if debug:
            count_out = '(%s/%s) (%s%%) (%s found)' % (count, len(values), (round(100 * float(count) / float(len(values)), 2)), len(items))
            stdout.write('%s%s' % (('\r' * len(count_out)), count_out))
            stdout.flush()
        if len(items) >= 1 and aggressive:
            break
    for item in items:
        output.append(item)
    return output

if __name__ == '__main__':
    debug = 'debug' in argv
    aggressive = 'aggressive' not in argv
    if debug:
        print 'Building string...'
    data = []
    for word in words:
        repeat = word['repeat']
        r_char = word['r_char']
        length = word['len']
        first_letter = word['first']
        last_letter = word['last']
        possible = find_words(repeat=repeat, r_char=r_char)
        data.append(find_word(values=possible, first=first_letter, last=last_letter, length=5, repeat=repeat, r_char=r_char))
    print ' '.join(x[0] for x in data)

Explanation

This creates a dictionary of ASCII values and their associated characters as it will permit the code to only use those values and nothing else. We ensure that we reference vowels in a separate list and then let it be known that the second last character repeats itself in both strings.

Having done that, we create a list of dictionaries with set rules defining the word length, its first, last, and repeating characters, and then also set a true/false statement for if repeats should be checked.

Once this is done, the script iterates through the list of dictionaries and feeds it through a function that creates all possible permutations of characters from the reference dictionary, taking care to add any repeating characters if necessary.

Afterward, it is then fed through a second function that creates even more permutations for each permutation, but setting a maximum length. This is done to ensure that we find the words that we want to chew through. During this process, it then feeds it through a function that uses a combination of if-else statements that determines if it is worthy of being spat out. If the permutation matches what the statements are calling for, it then spits out a true/false statement and the function that called it adds it to a list.

Once this is done, the script then takes the first item from each list and combines them to state "hello world".

I added some debug features too to let you know how slow it is going. I chose to do this as you don't need to write "hello world" to have it spit out "hello world" if you know how to construct the sentence.

\$\endgroup\$
1
vote
\$\begingroup\$

Well, this is good.

[
  uuid(2573F8F4-CFEE-101A-9A9F-00AA00342820)
  ]
  library LHello
  {
      // bring in the master library
      importlib("actimp.tlb");
      importlib("actexp.tlb");

      // bring in my interfaces
      #include "pshlo.idl"

      [
      uuid(2573F8F5-CFEE-101A-9A9F-00AA00342820)
      ]
      cotype THello
   {
   interface IHello;
   interface IPersistFile;
   };
  };

  [
  exe,
  uuid(2573F890-CFEE-101A-9A9F-00AA00342820)
  ]
  module CHelloLib
  {

      // some code related header files
      importheader(<windows.h>);
      importheader(<ole2.h>);
      importheader(<except.hxx>);
      importheader("pshlo.h");
      importheader("shlo.hxx");
      importheader("mycls.hxx");

      // needed typelibs
      importlib("actimp.tlb");
      importlib("actexp.tlb");
      importlib("thlo.tlb");

      [
      uuid(2573F891-CFEE-101A-9A9F-00AA00342820),
      aggregatable
      ]
      coclass CHello
   {
   cotype THello;
   };
  };


  #include "ipfix.hxx"

  extern HANDLE hEvent;

  class CHello : public CHelloBase
  {
  public:
      IPFIX(CLSID_CHello);

      CHello(IUnknown *pUnk);
      ~CHello();

      HRESULT  __stdcall PrintSz(LPWSTR pwszString);

  private:
      static int cObjRef;
  };


  #include <windows.h>
  #include <ole2.h>
  #include <stdio.h>
  #include <stdlib.h>
  #include "thlo.h"
  #include "pshlo.h"
  #include "shlo.hxx"
  #include "mycls.hxx"

  int CHello::cObjRef = 0;

  CHello::CHello(IUnknown *pUnk) : CHelloBase(pUnk)
  {
      cObjRef++;
      return;
  }

  HRESULT  __stdcall  CHello::PrintSz(LPWSTR pwszString)
  {
      printf("%ws
", pwszString);
      return(ResultFromScode(S_OK));
  }


  CHello::~CHello(void)
  {

  // when the object count goes to zero, stop the server
  cObjRef--;
  if( cObjRef == 0 )
      PulseEvent(hEvent);

  return;
  }

  #include <windows.h>
  #include <ole2.h>
  #include "pshlo.h"
  #include "shlo.hxx"
  #include "mycls.hxx"

  HANDLE hEvent;

   int _cdecl main(
  int argc,
  char * argv[]
  ) {
  ULONG ulRef;
  DWORD dwRegistration;
  CHelloCF *pCF = new CHelloCF();

  hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

  // Initialize the OLE libraries
  CoInitializeEx(NULL, COINIT_MULTITHREADED);

  CoRegisterClassObject(CLSID_CHello, pCF, CLSCTX_LOCAL_SERVER,
      REGCLS_MULTIPLEUSE, &dwRegistration);

  // wait on an event to stop
  WaitForSingleObject(hEvent, INFINITE);

  // revoke and release the class object
  CoRevokeClassObject(dwRegistration);
  ulRef = pCF->Release();

  // Tell OLE we are going away.
  CoUninitialize();

  return(0); }

  extern CLSID CLSID_CHello;
  extern UUID LIBID_CHelloLib;

  CLSID CLSID_CHello = { /* 2573F891-CFEE-101A-9A9F-00AA00342820 */
      0x2573F891,
      0xCFEE,
      0x101A,
      { 0x9A, 0x9F, 0x00, 0xAA, 0x00, 0x34, 0x28, 0x20 }
  };

  UUID LIBID_CHelloLib = { /* 2573F890-CFEE-101A-9A9F-00AA00342820 */
      0x2573F890,
      0xCFEE,
      0x101A,
      { 0x9A, 0x9F, 0x00, 0xAA, 0x00, 0x34, 0x28, 0x20 }
  };

  #include <windows.h>
  #include <ole2.h>
  #include <stdlib.h>
  #include <string.h>
  #include <stdio.h>
  #include "pshlo.h"
  #include "shlo.hxx"
  #include "clsid.h"

  int _cdecl main(
  int argc,
  char * argv[]
  ) {
  HRESULT  hRslt;
  IHello        *pHello;
  ULONG  ulCnt;
  IMoniker * pmk;
  WCHAR  wcsT[_MAX_PATH];
  WCHAR  wcsPath[2 * _MAX_PATH];

  // get object path
  wcsPath[0] = '\0';
  wcsT[0] = '\0';
  if( argc > 1) {
      mbstowcs(wcsPath, argv[1], strlen(argv[1]) + 1);
      wcsupr(wcsPath);
      }
  else {
      fprintf(stderr, "Object path must be specified\n");
      return(1);
      }

  // get print string
  if(argc > 2)
      mbstowcs(wcsT, argv[2], strlen(argv[2]) + 1);
  else
      wcscpy(wcsT, L"Hello World");

  printf("Linking to object %ws\n", wcsPath);
  printf("Text String %ws\n", wcsT);

  // Initialize the OLE libraries
  hRslt = CoInitializeEx(NULL, COINIT_MULTITHREADED);

  if(SUCCEEDED(hRslt)) {


      hRslt = CreateFileMoniker(wcsPath, &pmk);
      if(SUCCEEDED(hRslt))
   hRslt = BindMoniker(pmk, 0, IID_IHello, (void **)&pHello);

      if(SUCCEEDED(hRslt)) {

   // print a string out
   pHello->PrintSz(wcsT);

   Sleep(2000);
   ulCnt = pHello->Release();
   }
      else
   printf("Failure to connect, status: %lx", hRslt);

      // Tell OLE we are going away.
      CoUninitialize();
      }

  return(0);
  }
\$\endgroup\$
0
votes
\$\begingroup\$

Golf-Basic 84, 9 Points

i`I@I:1_A#:0_A@I:0_A#:Endt`Hello World"

Explanation

i`I

Ask the user if they want to quit

@I:1_A#0_A

Record their answer

@I:0_A#:End

If they did in fact wish to end, it terminates

t`Hello World"

If they didn't end, it prints Hello World.

\$\endgroup\$
0
votes
\$\begingroup\$

Hashes and then brute-force de-hashes the characters for "Hello, World!", adds those to a StringBuilder, and logs that with a Logger.

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import sun.security.provider.SHA2;

/**
 * ComplexHelloWorld, made for a challenge, is copyright Blue Husky Programming ©2014 GPLv3<HR/>
 *
 * @author Kyli Rouge of Blue Husky Programming
 * @version 1.0.0
 * @since 2014-02-19
 */
public class ComplexHelloWorld
{
    private static final SHA2 SHA2;
    private static final byte[] OBJECTIVE_BYTES;
    private static final String OBJECTIVE;
    public static final String[] HASHES;
    private static final Logger LOGGER;

    static
    {
        SHA2 = new SHA2();
        OBJECTIVE_BYTES = new byte[]
        {
            72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33
        };
        OBJECTIVE = new String(OBJECTIVE_BYTES);
        HASHES = hashAllChars(OBJECTIVE);
        LOGGER = Logger.getLogger(ComplexHelloWorld.class.getName());
    }

    public static String hash(String password)
    {
        String algorithm = "SHA-256";
        MessageDigest sha256;
        try
        {
            sha256 = MessageDigest.getInstance(algorithm);
        }
        catch (NoSuchAlgorithmException ex)
        {
            try
            {
                LOGGER.logrb(Level.SEVERE, ComplexHelloWorld.class.getName(), "hash", null, "There is no such algorithm as " + algorithm, ex);
            }
            catch (Throwable t2)
            {
                //welp.
            }
            return "[ERROR]";
        }
        byte[] passBytes = password.getBytes();
        byte[] passHash = sha256.digest(passBytes);
        return new String(passHash);
    }

    public static void main(String... args)
    {
        StringBuilder sb = new StringBuilder();
        allHashes:
        for (String hash : HASHES)
            checking:
            for (char c = 0; c < 256; c++)
                if (hash(c + "").equals(hash))
                    try
                    {
                        sb.append(c);
                        break checking;
                    }
                    catch (Throwable t)
                    {
                        try
                        {
                            LOGGER.logrb(Level.SEVERE, ComplexHelloWorld.class.getName(), "main", null, "An unexpected error occurred", t);
                        }
                        catch (Throwable t2)
                        {
                            //welp.
                        }
                    }
        try
        {
            LOGGER.logrb(Level.INFO, ComplexHelloWorld.class.getName(), "main", null, sb + "", new Object[]
            {
            });
        }
        catch (Throwable t)
        {
            try
            {
                LOGGER.logrb(Level.SEVERE, ComplexHelloWorld.class.getName(), "main", null, "An unexpected error occurred", t);
            }
            catch (Throwable t2)
            {
                //welp.
            }
        }
    }

    private static String[] hashAllChars(String passwords)
    {
        String[] ret = new String[passwords.length()];
        for (int i = 0; i < ret.length; i++)
            ret[i] = hash(passwords.charAt(i) + "");
        return ret;
    }
}
\$\endgroup\$
0
votes
\$\begingroup\$

C# - 158

I tell you what, developers these days, paying no attention to SOLID principles. People these days neglect how important it is to do even the simple tasks properly.

First, we need to start with requirements:

  • Prints the specified string to the console
  • Allows for localization
  • Follows SOLID principles

First, let's start with localization. To properly localize strings, we need an alias for the string to use within the program, and the locale we want the string in. We obviously need to store this data in an easily interoperable format, XML. And to do XML properly, we need a schema.

StringDictionary.xsd

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="StringDictionary"
targetNamespace="http://stackoverflow.com/StringDictionary.xsd"
elementFormDefault="qualified"
xmlns="http://stackoverflow.com/StringDictionary.xsd"
xmlns:mstns="http://stackoverflow.com/StringDictionary.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="stringDictionary" type="localizedStringDictionary"/>

<xs:complexType name="localizedStringDictionary">
    <xs:sequence minOccurs="1" maxOccurs="unbounded">
        <xs:element name="localized" type="namedStringElement"></xs:element>
    </xs:sequence>
</xs:complexType>

<xs:complexType name="localizedStringElement">
    <xs:simpleContent>
        <xs:extension base="xs:string">
            <xs:attribute name="locale" type="xs:string"/>
        </xs:extension>
    </xs:simpleContent>
</xs:complexType>

<xs:complexType name="namedStringElement">
    <xs:sequence minOccurs="1" maxOccurs="unbounded">
        <xs:element name="translated" type="localizedStringElement"></xs:element>
    </xs:sequence>
    <xs:attribute name="name" type="xs:string"></xs:attribute>
</xs:complexType>

This defines our XML structure and gets us off to a good start. Next, we need the XML file itself, containing the strings. Make this file an embedded resource in your project.

<?xml version="1.0" encoding="utf-8" ?>
<stringDictionary xmlns="http://stackoverflow.com/StringDictionary.xsd">
    <localized name="helloWorld">
        <translated locale="en-US">Hello, World</translated>
        <translated locale="ja-JP">こんにちは世界</translated>
    </localized>
</stringDictionary>

With that out of the way, one thing we absolutely do not want is any hard coded strings in our program. Use Visual Studio to make resources in your project that we will use for our strings. Ensure to change XmlDictionaryName to match the name of your XML strings file defined earlier.

enter image description here

Since we're dependency inversion, we need a dependency container to handle registering and creating our objects.

IDependencyRegister.cs

public interface IDependencyRegister
{
    void Register<T1, T2>();
}

IDependencyResolver.cs

public interface IDependencyResolver
{
    T Get<T>();
    object Get(Type type);
}

We can provide a simple implementation of both of these interfaces together on one class.

DependencyProvider.cs

public class DependencyProvider : IDependencyRegister, IDependencyResolver
{
    private IReadOnlyDictionary<Type, Func<object>> _typeRegistration;

    public DependencyProvider()
    {
        _typeRegistration = new Dictionary<Type, Func<object>>();
    }

    public void Register<T1, T2>()
    {
        var newDict = new Dictionary<Type, Func<object>>((IDictionary<Type, Func<object>>)_typeRegistration) { [typeof(T1)] = () => Get(typeof(T2)) };
        _typeRegistration = newDict;
    }

    public object Get(Type type)
    {
        Func<object> creator;
        if (_typeRegistration.TryGetValue(type, out creator)) return creator();
        else if (!type.IsAbstract) return this.CreateInstance(type);
        else throw new InvalidOperationException("No registration for " + type);
    }

    public T Get<T>()
    {
        return (T)Get(typeof(T));
    }

    private object CreateInstance(Type implementationType)
    {
        var ctor = implementationType.GetConstructors().Single();
        var parameterTypes = ctor.GetParameters().Select(p => p.ParameterType);
        var dependencies = parameterTypes.Select(Get).ToArray();
        return Activator.CreateInstance(implementationType, dependencies);
    }
}

Starting at the lowest level and working our way up, we need a way to read the XML. Following the S and I in SOLID, we define an interface that our XML string dictionary code uses:

public interface IStringDictionaryStore
{
    string GetLocalizedString(string name, string locale);
}

Thinking about proper design for performance. Retrieving these strings is going to be on the critical path on our program. And we want to be sure that we always retrieve the correct string. For this, we're going to use a dictionary where they key is the hash of the string name and locale, and the value contains our translated string. Once again, following the single responsibility principle, our string dictionary should not care how the strings are hashed, so we make an interface, and provide a basic implementation

IStringHasher.cs

public interface IStringHasher
{
    string HashString(string name, string locale);
}

Sha512StringHasher.cs

public class Sha512StringHasher : IStringHasher
{
    private readonly SHA512Managed _sha;
    public Sha512StringHasher()
    {
        _sha = new SHA512Managed();
    }
    public string HashString(string name, string locale)
    {
        return Convert.ToBase64String(_sha.ComputeHash(Encoding.UTF8.GetBytes(name + locale)));
    }
}

With this, we can define our XML string store that reads an XML file from an embedded resource, and creates a dictionary holding the string definitions

EmbeddedXmlStringStore.cs

public class EmbeddedXmlStringStore : IStringDictionaryStore
{
    private readonly XNamespace _ns = (string)Resources.XmlNamespaceName;

    private readonly IStringHasher _hasher;
    private readonly IReadOnlyDictionary<string, StringInfo> _stringStore;
    public EmbeddedXmlStringStore(IStringHasher hasher)
    {
        _hasher = hasher;
        var resourceName = this.GetType().Namespace + Resources.NamespaceSeperator + Resources.XmlDictionaryName;
        using (var s = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
        {
            var doc = XElement.Load(s);

            _stringStore = LoadStringInfo(doc).ToDictionary(k => _hasher.HashString(k.Name, k.Locale), v => v);
        }
    }

    private IEnumerable<StringInfo> LoadStringInfo(XElement doc)
    {
        foreach (var e in doc.Elements(_ns + Resources.LocalizedElementName))
        {
            var name = (string)e.Attribute(Resources.LocalizedElementNameAttribute);
            foreach (var e2 in e.Elements(_ns + Resources.TranslatedElementName))
            {
                var locale = (string)e2.Attribute(Resources.TranslatedElementLocaleName);
                var localized = (string)e2;
                yield return new StringInfo(name,locale,localized);
            }
        }
    }

    public string GetLocalizedString(string name, string locale)
    {
        return _stringStore[_hasher.HashString(name, locale)].Localized;
    }
}

And the associated StringInfo structure to hold the string information:

StringInfo.cs

public struct StringInfo
{
    public StringInfo(string name, string locale, string localized)
    {
        Name = name;
        Locale = locale;
        Localized = localized;
    }

    public string Name { get; }
    public string Locale { get; }
    public string Localized { get; }
}

Since we might have several ways of looking up strings, we need to insulate the rest of the program from how exactly strings are retrieved, to do this, we define IStringProvider, which will be used throughout the rest of the program to resolve strings:

ILocaleStringProvider.cs

public interface ILocaleStringProvider
{
    string GetString(string stringName, string locale);
}

With an implementation:

StringDictionaryStoreLocaleStringProvider.cs

public class StringDictionaryStoreLocaleStringProvider: ILocaleStringProvider
{
    private readonly IStringDictionaryStore _dictionaryStore;

    public StringDictionaryStoreStringProvider(IStringDictionaryStore dictionaryStore)
    {
        _dictionaryStore = dictionaryStore;
    }

    public string GetString(string stringName, string locale)
    {
        return _dictionaryStore.GetLocalizedString(stringName, locale);
    }
}

Now, to handle locales. We define an interface to get the user's current locale. Isolating this is important, since a program running on the user's computer can read the locale off of the process, but on a web site, the user's locale might come from a database field assoicated with their user.

ILocaleProvider.cs

public interface ILocaleProvider
{
    string GetCurrentLocale();
}

And a default implementation That uses the current culture of the process, since this sample is a console application:

class DefaultLocaleProvider : ILocaleProvider
{
    public string GetCurrentLocale()
    {
        return CultureInfo.CurrentCulture.Name;
    }
}

The rest of our program doesn't really care if we're serving up localized strings or not, so we can hide the localization lookup behind an interface:

IStringProvider.cs

public interface IStringProvider
{
    string GetString(string name);
}

Our implementation of StringProvider is responsible for using the provided implementations of ILocaleStringProvider and ILocaleProvider to return a localized string

DefaultStringProvider.cs

public class DefaultStringProvider : IStringProvider
{
    private readonly ILocaleStringProvider _localeStringProvider;
    private readonly ILocaleProvider _localeProvider;
    public DefaultStringProvider(ILocaleStringProvider localeStringProvider, ILocaleProvider localeProvider)
    {
        _localeStringProvider = localeStringProvider;
        _localeProvider = localeProvider;
    }

    public string GetString(string name)
    {
        return _localeStringProvider.GetString(name, _localeProvider.GetCurrentLocale());
    }
}

Finally, we have our program entry point, which provides the composition root, and gets the string, printing it to the console:

Program.cs

class Program
{
    static void Main(string[] args)
    {
        var container = new DependencyProvider();

        container.Register<IStringHasher, Sha512StringHasher>();
        container.Register<IStringDictionaryStore, EmbeddedXmlStringStore>();
        container.Register<ILocaleProvider, DefaultLocaleProvider>();
        container.Register<ILocaleStringProvider, StringDictionaryStoreLocaleStringProvider>();
        container.Register<IStringProvider, DefaultStringProvider>();

        var consumer = container.Get<IStringProvider>();

        Console.WriteLine(consumer.GetString(Resources.HelloStringName));
    }
}

And that is how you write an enterprise microservice ready, locale aware, Hello World program.

Scores: Files: 17 Namespace Includes: 11 Classes: 14 Variables: 26 Methods: 17 Statements: 60 Control Flow: 2 Forward Declarations (Interface members, xsd complexTypes): 11 Total: 158

\$\endgroup\$
-1
votes
\$\begingroup\$

iX2Web

**iX2001B2 A1CAA3MwlI ZWxsbyBXb3 JsZHxfMAkw DQo==*
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.