您可以证明最复杂的“ Hello world”程序[关闭]


41

您的老板要求您编写一个“ hello world”程序。由于您获得了代码行的报酬,因此您希望使其尽可能复杂。但是,如果您仅添加无用的代码行,或者显然是无用的或令人困惑的内容,那么您将永远无法通过代码审查获得它。因此,挑战在于:

编写一个“ hello world”程序,该程序在您可以为代码中的每种复杂性给出“合理性”的条件下尽可能复杂。

该程序所需的行为是仅输出一行“ Hello world”(不带引号,但末尾带有换行符),然后成功退出。

“辩解”包括:

  • 流行语兼容性(“现代软件是面向对象的!”)
  • 公认的良好编程习惯(“每个人都知道您应该分开模型和视图”)
  • 可维护性(“如果这样做,我们以后可以更轻松地进行XXX”)
  • 当然还有其他可以证明的理由(在其他情况下)使用真实代码。

显然,愚蠢的理由将不被接受。

另外,您还必须“证明”您选择的语言(因此,如果您选择固有的冗长语言,则必须说明为什么它是“正确”的选择)。有趣的语言,如unlambda相似或INTERCAL是不能接受的(除非你可以给一个非常使用它们很好的理由)。

符合条件的条目的分数计算如下:

  • 每条陈述1分(或您选择的语言所对应的任何陈述)。
  • 对于函数,类型,变量等的每个定义,需要加1分(主函数除外,如适用)。
  • 每个模块的use语句,文件include指令,命名空间using语句或类似名称为1点。
  • 每个源文件1分。
  • 每个必要的前向声明要加1分(如果您可以通过重新排列代码来摆脱它,则必须“证明”选择的排列为什么是“正确”的)。
  • 每个控制结构1点(如果,同时,用于等)

请记住,您必须“调整”每一行。

如果所选语言足够不同,以致无法应用此方案(并且您可以为其使用提供很好的“证明”),请提出一种与您选择的语言最相似的评分方法。

要求参赛者计算其参赛分数并将其写在答案中。



7
不知何故,这些“越来越多,越来越大”-挑战只持续了5分钟。我们来做一个ProxyPoolFactoryPoolFacadePoolProxyFactory(Pool)!您需要一个限制,例如:从现在起20分钟内完成!另一个问题是“愚蠢的理由将不被接受”。这不仅是主观的,而且从一开始就是无效的,因为我们知道,整个事情都是愚蠢的。好的-让我们使用一个不太傻的东西,而不是ProxyPoolPool,可能是PoolProxyProxy?
用户未知

1
@ChristopheD:虽然我不知道这样的问题,但我的问题并不在于此:您必须“合理化”您的选择(即仅使其变得更复杂是不够的,您必须给出复杂性的充分理由)。
celtschk 2012年

3
我不确定对理由的“明显不愚蠢”的限制是否可以与常见问题解答达成一致,在常见问题中说:“本网站上的所有问题均应具有客观的主要获胜标准。 “
dmckee,2012年

21
这似乎很难被击败GNU的Hello World(gnu.org/software/hello) - 2.7版本的源代码是586 KB的下载作为一个压缩存档,完成自动测试,国际化,文档等

Answers:


48

C ++,trollpost

您可以证明最复杂的“ Hello world”程序

#include <iostream>

using namespace std;

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

我的大脑不能证明写更长的书:)


6
最好的答案在这里。
Joe Z.

12
“使用命名空间标准”是没有道理的!另外,您的main接受了不使用的参数。浪费!;)
Riot

3
对我来说太复杂了。这是什么意思?是否可以添加一些单元测试?
内森·库珀

20

在这里,我将通过上述脚本语言的操作符以及数据结构(如列表字典)的生成器,以优美有效的方式解决称为Python的脚本语言的强大功能和可用性。

但是,恐怕我不完全理解“尽可能复杂”和“合理化”这两个词的使用。不过,这是我惯用的,不言自明的,直接的策略的摘要,紧接着是您将发现的Python实际实现,完全符合该语言的俏皮,高级特性:

  1. 定义字母–显而易见的第一步。为了扩展性,我们选择整个ascii范围。请注意,使用内置列表生成器可以为我们节省数小时的繁琐列表初始化。

  2. 告诉我们字母表中每个字母要使用多少个。这只是表示为另一个列表!

  3. 将这两个列表合并到一个方便的字典中,其中的键是ascii点,值是所需的数量。

  4. 我们现在准备开始制作角色!首先从字典中创建一个字符串。这将包含我们最终输出中所需的所有字符,以及每个字符的正确数量!

  5. 声明所需的字符顺序,并启动一个新列表,该列表将保留我们的最终输出。通过简单的迭代,我们将生成的字符放到最终位置并打印结果!

这是实际的实现

# 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)

好的,只是做了一个简短但愚蠢的问题,并添加了一堆文本而不是TL; DR代码解决方案


n这里的定义算作1行还是11?
Draco18s


16

斯卡拉(Scala),得分:62

好吧,我把帽子扔进了戒指。

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'
}

索引LHWCChain.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'
}

索引OHWCChain.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 ()
}

当然,对于纯函数方法,0个臭味变量。一切都布置在类型系统中,并且很简单。聪明的编译器可以对其进行最优化。

该程序清晰,简单且易于理解。它易于测试且通用,并且避免了过度设计的陷阱(我的团队想将indexedOHWCChain和indexedLHWCChain重新编码为一个通用的次要特征,该特征具有目标数组和长度字段,但这简直太愚蠢了!)。


14个文件在哪里?
celtschk 2012年

1
在列0中的每个右括号之后,将创建一个新文件。每个对象,类和特征一个文件。如果仅修改单个对象,则可以加快构建过程。
用户未知

然后,请在答案中明确指出。
celtschk'2

1
这不是complex原始问题所要求的。只是非常verbose。它们是有区别的。
monokrome 2013年

5
+1为“ Javacode是样板程序,而scala是简洁的语言”。其次是我见过的最简洁的代码。
Tim S.

8

纯Bash 没有叉子 (一些计数,似乎是85左右...)

  • 6个函数initRotString 2个变量,3个语句
  • 14个功能binToChar 2个变量,7个语句+子定义:1个func,1个var,2个stat
  • 34个函数rotIO 9个变量,25个语句
  • 9个函数RLE 4个变量,5个statments
  • 22个 主要 13个变量,9个陈述

特点

  • 二级RLE:第一个二进制编码每个字符,第二个用于重复字符
  • 基于键的修改后的rot13rotIO函数像Rot13一样执行旋转,但是对96个值而不是26个值(* rot47)进行旋转,但是通过提交的键进行了移位。
  • 第二版使用gzipuuencode通过perl(比的安装更为普遍uudecode

完整的重写(错误更正,ascii艺术图和两级规则):

#!/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

(所使用的密钥V922/G/,2:也基于HelloWorld,但这没关系;)

结果(按要求):

Hello world!

还有另一个版本:

#!/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

使用相同的键,可能会呈现如下内容:

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

世界您好,2014年新年快乐


2
...但是它并不那么复杂!我可以做很多更糟糕的事情:->>
F. Hauri

8

众所周知,摩尔定律已经有了新的发展,未来十年计算能力的所有真正进步都将出现在GPU中。考虑到这一点,我使用LWJGL编写了一个速度非常快的Hello World程序,该程序充分利用了GPU的优势来生成字符串“ Hello World”。

由于我正在编写Java,因此从复制和粘贴别人的代码开始是惯用的,因此我使用了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("");
}

}

7

组装(x86,Linux / Elf32):55分

每个人都知道,当您需要快速的程序时,需要使用汇编语言编写。

有时我们不能依靠ld自己的工作来完成-为了获得最佳性能,最好为hello world可执行文件构建自己的Elf标头。该代码仅需nasm构建,因此非常可移植。它不依赖外部库或运行时。

每行和每条语句对于程序的正确运行都是至关重要的-没有多余的东西,什么都不能省略。

而且,这确实是不使用链接器的最短方法-没有不必要的循环或声明来掩盖答案。

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     $ - $$

计分

  • “声明”(计数mov,int):8
  • “功能,类型,变量”(计数orgdbdwddequglobal _start):37
  • “源文件”:1
  • “前向声明”(计数dd _startdd filesizedw ehdrsizedw phdrsize:4
  • “控制结构”(计数ehdr:phdr:section .data, ,section .text_start:):5

6

PHP / HTML / CSS(88分)

所有代码都在这里提供:https : //github.com/martin-damien/code-golf_hello-world

  • 该“ Hello World”使用PHP的Twig模板语言(http://twig.sensiolabs.org/)。
  • 我使用自动加载机制来简单地动态加载类。
  • 我使用Page类,它可以处理多种类型的元素(实现XMLElement接口),并以正确的XML格式重新设置所有这些元素。
  • 最后,我使用闪亮的CSS来显示漂亮的“ 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();

}

?>

设计/样式表/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;
}

设计/模板/布局/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>

设计/模板/页面/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 %}

6

脑干

369个表达式,29个while循环= 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

来自K&R的输出C编程语言示例:

hello, world!

5

Ti-Basic 84,1点

:Disp "HELLO WORLD!"

Ti-Basic非常基础。但是,如果您真的想要一个合理的解释,这里是:

: 启动每个命令,函数,语句,结构,子程序,将其命名

Disp 是预定义的功能,可在屏幕上显示参数

aka whitespace让函数Disp知道它已经被调用,并且参数应该跟随空格的单个字符,该空格实际上与Disp

" 开始定义字符串文字

HELLO WORLD 字符串文字中的部分文本

! 尽管它是阶乘数学运算符,但由于它位于字符串文字中,因此不会进行评估

" 结束字符串文字的定义


5

所以,我有一个非常……特殊的经理。他有一个奇怪的想法,即程序越简单,越漂亮,它应该越具有艺术性。由于Hello World可以说是最容易编写的程序之一,因此他要求的东西太棒了,可以挂在墙上。经过研究后,他坚持要用Piet编写。

现在,我不是一个质疑最聪明的人能胜任高层管理人员的优点的人,所以我受命“编写”该程序,该程序可以在此在线piet解释器上运行也许是时候寻找一个更健全的经理了……

在此处输入图片说明


再加上一个深奥的东西。另外,Piet中有许多独特的“ Hello World”程序,我最喜欢的是动画程序
Draco18s

4

C中的唇形图

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

我的计算机上的btwn'w'和'r'是bronn。它与som languags产生因果关系。C中几乎所有的PR编译器指令都是这样的。从头开始,cod发出有关printf()隐式声明的警告,因为我无法使用#includ(stdio.h),但它运行良好。


1
您输入了“使用”,但是…
Supuhstar 2014年

3

作为社区Wiki,我将其作为参考。这是C#的一种不好的做法。我定义了自己的ascii数据结构。我不希望这成为竞争对手,而是“孩子,你看到那边的那个人……如果你不吃蔬菜,你会变得像他一样”。

如果您容易受到错误代码的干扰,请立即查找

我通常用它在万圣节吓到孩子们。您还应该注意,我不能将我所有的256个ASCII字符都放在这里,因为总字符数增加到40,000。请勿出于以下两个原因尝试重现此内容:

  • 这比高尔夫代码更可怕,更可怕,更糟糕。
  • 我编写了一个程序来编写大部分程序。

所以,嗯...是的“享受!”。另外,如果您喜欢清洁和改善代码咳嗽,请执行代码审查咳嗽,如果您正在寻找一种非盈利性职业,这可能会让您忙一阵子。

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];
        }
    }
}

6
好像正在生产中的普通C#代码;)
german_guy14年

2
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);
    }
}

我稍后会添加一些评论。


3
“我稍后会添加一些评论。” 多少时间?
celtschk 2012年

main类的函数中MainConsoleDisplay没有名为的成员getInstance。你是说ConsoleDisplayFactory吗 顺便说一句,请明确说明语言(我想是Java)和要点。
celtschk 2012年

@celtschk:很久以后
Silviu Burcea 2015年

2

积分:183

  • 62条声明*
  • 10个类+ 25个方法(属性的getter和setter是不同的)+ 8个变量声明(我认为)= 43个声明
  • 没有模块使用语句。但是,它确实有一些默认值,使用完整资格是我打保龄球的一部分。那么也许1 System呢?好吧,无论如何,假设0。
  • 1个源文件。
  • 不是使用前向声明的语言。好吧,1 MustOverride,我将数。
  • 76条控制声明。没有手动计数,因此可能会有些不准确。

总计:62 + 43 + 0 + 1 + 1 + 76 = 183

条目

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

文献资料

  • 代码中没有注释。这有助于减少混乱情况,并且不需要注释,因为我是唯一的开发人员,而我们拥有如此惊人的详细文档-再次由您真正撰写。
  • OptimizedStringFactory拥有优化的字符串。它具有一个高速缓存,该高速缓存允许使用对有效IEnumerable(Of Char)s的引用,同时避免引用的内在问题。引起我注意的是.NET包含某种字符串池。但是,内置缓存对我们正在使用的对象了解不多-不可靠,因此我创建了自己的解决方案。
  • ConcurrentOutputCharacter类允许多线程的,单字符输出的容易同步。这可以防止输出乱码。在面向对象编程的最佳实践中,对它进行了声明,MustInherit并从中派生出每个要输出的字符或字符串,并进行了声明NotInheritable。它包含几个断言,以确保传递有效数据。
  • *Character对于我们的特定字符串输出情况,每个字符都包含一个字符。
  • 主模块包含用于创建线程的代码。线程是一项非常新的功能,它使我们能够利用多核处理器并更有效地处理输出。为了防止代码重复,我使用了一个循环来创建字符。

美丽,不?

由于上述循环和继承,加上基于反射的动态类加载,它甚至可以扩展。这也可以防止过度混淆,因此没有人可以通过混淆来声明我们的代码。要更改字符串,只需创建一个字典,即可在反射代码动态加载它们之前将输入字符映射到不同的输出字符类。


3
照原样,该程序未实现该规范。它在“ Hello”之后输出一个逗号,在“ world”之后输出一个感叹号。我找不到它在哪里输出换行符(但也许我错过了)。同样,最后,它与规范相反,等待按键被按下。
celtschk'2

1
VB是什么语言?我可以在Linux上运行它吗?
用户未知

@userunknown:VB.NET。您可以使用Mono在Linux上运行它。
2012年

2
@celtschk:现在已更正。毕竟它是可扩展的;)
Ry- 2012年

计数过程仍在进行吗?
用户未知

2

Javascript,很多要点

  • 完全集成的i18n支持
  • 多平台JS,可以在具有可自定义上下文的Node和Web浏览器上运行(浏览器应使用“窗口”)
  • 可配置的数据源,默认情况下使用静态“ Hello world”消息(以提高性能)
  • 完全异步,并发性好
  • 良好的调试模式,对代码调用进行时间分析。

开始了:

(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 || {}));

1

Hello World的C程序: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]]);
 }
}

ASCII字符和包含整数的字符数组的组合!基本上,以字符格式打印每个数字。


+1确实很棒,但是您如何证明我的正当性呢?
izabera 2014年

oops!正在使用i作为for循环计数器。忘记删除它的声明了。感谢您的注意。
Sushant Parab,2014年

1

Python使用if-else语句

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)

说明

这将创建一个ASCII值及其相关字符的字典,因为它将允许代码仅使用这些值,而不能使用其他值。我们确保在单独的列表中引用元音,然后知道倒数第二个字符在两个字符串中重复出现。

完成此操作后,我们将创建一个词典列表,其中包含设置规则,这些规则定义了单词长度,单词的第一个,最后一个和重复字符,然后还设置了一个true / false语句来确定是否应检查重复。

完成此操作后,脚本将遍历字典列表,并通过一个函数创建该函数,该函数会创建参考字典中所有可能的字符排列,并在必要时小心添加任何重复的字符。

然后,它通过第二个函数输入,该函数为每个排列创建更多排列,但设置最大长度。这样做是为了确保我们找到想要咀嚼的单词。然后,在此过程中,它将通过使用if-else语句组合(确定是否值得吐出)的函数将其馈入。如果排列与语句所要求的相匹配,则它将发出true / false语句,并且调用它的函数会将其添加到列表中。

完成此操作后,脚本将从每个列表中获取第一项并将其组合以声明“ hello world”。

我还添加了一些调试功能,以使您知道它的运行速度。我选择这样做是因为如果您知道如何构造句子,则无需编写“ hello world”即可吐出“ hello world”。


1

好吧,这很好。

[
  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);
  }

0

高尔夫基础84,9分

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

说明

i`I

询问用户是否要退出

@I:1_A#0_A

记录他们的答案

@I:0_A#:End

如果他们确实希望结束,则终止

t`Hello World"

如果他们没有结束,它将打印Hello World。


0

哈希然后用蛮力对“ Hello,World!”字符进行哈希处理,将这些字符添加到中StringBuilder,并使用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;
    }
}

0

C#-158

我告诉你,如今的开发人员,没有注意SOLID原则。如今,人们忽略了正确完成甚至简单任务的重要性。

首先,我们需要从需求开始:

  • 将指定的字符串输出到控制台
  • 允许本地化
  • 遵循SOLID原则

首先,让我们从本地化开始。为了正确地对字符串进行本地化,我们需要在程序中使用该字符串的别名以及要在其中使用该字符串的语言环境。显然,我们需要以易于互操作的格式XML来存储此数据。为了正确执行XML,我们需要一个模式。

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>

这定义了我们的XML结构,并使我们有了一个良好的开端。接下来,我们需要包含字符串的XML文件本身。将此文件作为项目中的嵌入式资源。

<?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>

这样一来,我们绝对不想要的一件事就是程序中的任何硬编码字符串。使用Visual Studio在您的项目中创建将用于字符串的资源。确保更改XmlDictionaryName以匹配先前定义的XML字符串文件的名称。

在此处输入图片说明

由于我们是依赖关系反转,因此我们需要一个依赖关系容器来处理注册和创建对象。

IDependencyRegister.cs

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

IDependencyResolver.cs

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

我们可以在一个类中同时提供这两个接口的简单实现。

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);
    }
}

从最低级别开始并逐步进行,我们需要一种读取XML的方法。在SOLID S和之后I,我们定义XML字符串字典代码使用的接口:

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

考虑适当的性能设计。检索这些字符串将成为我们程序中的关键路径。并且,我们要确保始终检索正确的字符串。为此,我们将使用一个字典,它们的键是字符串名称和语言环境的哈希,并且值包含我们翻译的字符串。再一次,遵循单一责任原则,我们的字符串字典不应该在乎如何对字符串进行哈希处理,因此我们创建了一个接口并提供了基本的实现

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)));
    }
}

这样,我们可以定义XML字符串存储,该存储从嵌入式资源中读取XML文件,并创建一个包含字符串定义的字典。

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;
    }
}

和关联的StringInfo结构来保存字符串信息:

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; }
}

由于我们可能有几种查找字符串的方法,因此我们需要将程序的其余部分与精确检索字符串的方式隔离开来,为此,我们定义IStringProvider,它将在程序的其余部分中用于解析字符串:

ILocaleStringProvider.cs

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

使用实现:

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);
    }
}

现在,处理语言环境。我们定义一个接口来获取用户的当前语言环境。隔离这一点很重要,因为在用户计算机上运行的程序可以从进程中读取语言环境,但是在网站上,用户的语言环境可能来自与其用户关联的数据库字段。

ILocaleProvider.cs

public interface ILocaleProvider
{
    string GetCurrentLocale();
}

还有一个默认实现,它使用该过程的当前区域性,因为此示例是一个控制台应用程序:

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

我们程序的其余部分实际上并不关心是否要提供本地化的字符串,因此我们可以将本地化查找隐藏在接口后面:

IStringProvider.cs

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

我们的StringProvider实现负责使用提供的实现ILocaleStringProviderILocaleProvider返回本地化的字符串

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());
    }
}

最后,我们有程序入口点,该入口提供合成根,并获取字符串,并将其打印到控制台:

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));
    }
}

这就是您编写准备就绪,可识别语言环境的Hello World程序的企业微服务的方式。

分数:文件:17命名空间包括:11类:14变量:26方法:17语句:60控制流:2前向声明(接口成员,xsd complexTypes):11总计:158


-1

iX2Web

**iX2001B2 A1CAA3MwlI ZWxsbyBXb3 JsZHxfMAkw DQo==*
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.