Sam*_*son 47 language-agnostic architecture code-complexity
与流行的代码高尔夫挑战相反,这里展示了许多常客的天才,我希望看到这种天才以相反的方式得到体现。
挑战是成功执行“Hello World”,特别关注过于复杂的问题。不是冗长,不是晦涩,只是纯粹的草率/过于复杂。
将《Daily WTF》视为灵感。
function mb2($o){return (int)($o*2);}
$alphabet = str_split("abcdefghijklmnopqrstuvwxyz");
$alphabet[] = " ";
$output = "";
for ($i = 0; $i <= 10; $i++)
switch (mb2($i*.5)) {
case 0: $output = $output . $alphabet[07]; break;
case 1: $output = $output . $alphabet[04]; break;
case 2: $output = $output . $alphabet[11]; break;
case 3: $output = $output . $alphabet[11]; break;
case 4: $output = $output . $alphabet[14]; break;
case 5: $output = $output . array_pop($alphabet); break;
case 6: $output = $output . $alphabet[22]; break;
case 7: $output = $output . $alphabet[14]; break;
case 8: $output = $output . $alphabet[17]; break;
case 9: $output = $output . $alphabet[11]; break;
case 10: $output = $output . $alphabet[03]; break;
}
print $output; // hello world
Run Code Online (Sandbox Code Playgroud)
bal*_*pha 120
你自找的。Python:
# Copyright (c) 1999 - 2010
# Large Company, Inc. ("THE COMPANY")
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COMPANY AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COMPANY OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
# THE POSSIBILITY OF SUCH DAMAGE.
"""This program outputs an enthusiastic "Hello World" in english.
"""
# FIXME: Where are the unit tests for this? QA called and says we
# can't ship this without tests. Also, while writing documentation
# may be boring, you can't expect everyone to understand all this!
# Go ahead and write some docstrings! -- O.D. 2004/7/22
class Expression(object):
def get_value(self, **kwargs):
"""get_value returns the value of this Expression.
Any keyword arguments that the method receives should
be passed on to the get_value methods of possibly called
subexpressions, even if this method does not handle
them.
This method must be reimplemented by the subclass."""
raise NotImplementedError
class Word(Expression):
def __init__(self, value):
self.value = value
def get_value(self, **kwargs):
return self.value
class Sentence(Expression):
def __init__(self, expressions, punctuation = "."):
self.expressions = list(expressions)
self.punctuation = punctuation
def get_value(self, separator = " ", **kwargs):
mainpart = separator.join(
subexpression.get_value(separator = separator, **kwargs)
for subexpression in self.expressions
)
if len(mainpart) > 0:
capitalized = mainpart[0].upper() + mainpart[1:]
else:
capitalized = ""
# FIXME: We're hardcoding "" here. Should we be prepared for
# languages that require a separator before the punctuation mark?
# NB: A workaround for now would be adding an empty word
return "".join((capitalized, self.punctuation))
class Hello(Word):
# FIXME: We should be prepared for languages where "hello" is
# represented by more than one word.
hello_by_language = {"en": "hello", "de": "hallo"}
def __init__(self, language = "en"):
super(Hello, self).__init__(self.hello_by_language[language])
class World(Word):
# FIXME: We should be prepared for languages where "world" is
# represented by more than one word.
world_by_language = {"en": "world", "de": "Welt"}
def __init__(self, language = "en"):
super(World, self).__init__(self.world_by_language[language])
class HelloWorld(Sentence):
def __init__(self, punctuation, language):
hello = Hello(language)
world = World(language)
super(HelloWorld, self).__init__([hello, world], punctuation)
class EnthusiasticHelloWorld(HelloWorld):
def __init__(self, language):
# FIXME: We should be prepared for languages where enthusiasm
# is not expressed with an exclamation mark.
super(EnthusiasticHelloWorld, self).__init__("!", language)
def main():
english_enthusiastic_hello_world = EnthusiasticHelloWorld("en")
print english_enthusiastic_hello_world.get_value()
if __name__ == "__main__":
main()
Run Code Online (Sandbox Code Playgroud)
Joh*_*ooy 64
有人可以帮助我加快我的程序吗?Python 即使只运行一行也太慢了!
python -c '[__import__("os").write(1,__import__("urllib2").urlopen("http://stackoverflow.com/questions/2052137").read()[x+__import__("urllib2").urlopen("http://stackoverflow.com/questions/2052137").read().find("Hello World")]) for x,_ in enumerate("Hello World")]'
Run Code Online (Sandbox Code Playgroud)
chr*_*ris 35
我认为很难击败 GNU “Hello World”(查看 tar 以充分享受它的辉煌,包括测试、makefile(s!)、man 等):
/* hello.c -- print a greeting message and exit.
Copyright 1992, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2005,
2006, 2007, 2008 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
#include "system.h"
/* String containing name the program is called with. */
const char *program_name;
static const struct option longopts[] =
{
{ "greeting", required_argument, NULL, 'g' },
{ "help", no_argument, NULL, 'h' },
{ "next-generation", no_argument, NULL, 'n' },
{ "traditional", no_argument, NULL, 't' },
{ "version", no_argument, NULL, 'v' },
{ NULL, 0, NULL, 0 }
};
/* Different types of greetings; only one per invocation. */
typedef enum {
greet_gnu, greet_new, greet_traditional, greet_user
} greeting_type;
/* Forward declarations. */
static void print_help (void);
static void print_version (void);
int
main (int argc, char *argv[])
{
int optc;
int lose = 0;
const char *greeting_msg = NULL;
greeting_type g = greet_gnu;
program_name = argv[0];
/* Set locale via LC_ALL. */
setlocale (LC_ALL, "");
#if ENABLE_NLS
/* Set the text message domain. */
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
#endif
/* Even exiting has subtleties. On exit, if any writes failed, change
the exit status. The /dev/full device on GNU/Linux can be used for
testing; for instance, hello >/dev/full should exit unsuccessfully.
This is implemented in the Gnulib module "closeout". */
atexit (close_stdout);
while ((optc = getopt_long (argc, argv, "g:hntv", longopts, NULL)) != -1)
switch (optc)
{
/* --help and --version exit immediately, per GNU coding standards. */
case 'v':
print_version ();
exit (EXIT_SUCCESS);
break;
case 'g':
greeting_msg = optarg;
g = greet_user;
break;
case 'h':
print_help ();
exit (EXIT_SUCCESS);
break;
case 'n':
g = greet_new;
break;
case 't':
g = greet_traditional;
break;
default:
lose = 1;
break;
}
if (lose || optind < argc)
{
/* Print error message and exit. */
if (optind < argc)
fprintf (stderr, _("%s: extra operand: %s\n"),
program_name, argv[optind]);
fprintf (stderr, _("Try `%s --help' for more information.\n"),
program_name);
exit (EXIT_FAILURE);
}
/* Print greeting message and exit. */
if (g == greet_traditional)
printf (_("hello, world\n"));
else if (g == greet_new)
/* TRANSLATORS: Use box drawing characters or other fancy stuff
if your encoding (e.g., UTF-8) allows it. If done so add the
following note, please:
[Note: For best viewing results use a UTF-8 locale, please.]
*/
printf (_("\
+---------------+\n\
| Hello, world! |\n\
+---------------+\n\
"));
else if (g == greet_user)
puts (greeting_msg);
else if (g == greet_gnu)
puts (_("Hello, world!"));
else {
/* No need for this impossible message to be translated. */
fprintf (stderr, "Impossible hello value %d\n", g);
exit (EXIT_FAILURE);
}
exit (EXIT_SUCCESS);
}
/* Print help info. This long message is split into
several pieces to help translators be able to align different
blocks and identify the various pieces. */
static void
print_help (void)
{
/* TRANSLATORS: --help output 1 (synopsis)
no-wrap */
printf (_("\
Usage: %s [OPTION]...\n"), program_name);
/* TRANSLATORS: --help output 2 (brief description)
no-wrap */
fputs (_("\
Print a friendly, customizable greeting.\n"), stdout);
puts ("");
/* TRANSLATORS: --help output 3: options 1/2
no-wrap */
fputs (_("\
-h, --help display this help and exit\n\
-v, --version display version information and exit\n"), stdout);
puts ("");
/* TRANSLATORS: --help output 4: options 2/2
no-wrap */
fputs (_("\
-t, --traditional use traditional greeting format\n\
-n, --next-generation use next-generation greeting format\n\
-g, --greeting=TEXT use TEXT as the greeting message\n"), stdout);
printf ("\n");
/* TRANSLATORS: --help output 5 (end)
TRANSLATORS: the placeholder indicates the bug-reporting address
for this application. Please add _another line_ with the
address for translation bugs.
no-wrap */
printf (_("\
Report bugs to <%s>.\n"), PACKAGE_BUGREPORT);
}
/* Print version and copyright information. */
static void
print_version (void)
{
printf ("hello (GNU %s) %s\n", PACKAGE, VERSION);
/* xgettext: no-wrap */
puts ("");
/* It is important to separate the year from the rest of the message,
as done here, to avoid having to retranslate the message when a new
year comes around. */
printf (_("\
Copyright (C) %s Free Software Foundation, Inc.\n\
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n\
This is free software: you are free to change and redistribute it.\n\
There is NO WARRANTY, to the extent permitted by law.\n"),
"2008");
}
Run Code Online (Sandbox Code Playgroud)
cfe*_*ern 23
我很偏执。我不信任编译器。我必须告诉它如何完成它的工作(C#):
using System;
using System.Reflection;
Run Code Online (Sandbox Code Playgroud)
。
static void Main()
{
Type ConsoleType = Type.GetType("System.Console");
Type StringType = Type.GetType("System.String");
Type CharArrayType = Type.GetType("System.Char[]");
MethodInfo WriteLineMethod = ConsoleType.GetMethod("WriteLine", new Type[] { StringType });
MethodInfo ReadLineMethod = ConsoleType.GetMethod("ReadLine");
ConstructorInfo StringConstructorInfo = StringType.GetConstructor(new Type[] { CharArrayType });
object HelloWorldStringObject = StringConstructorInfo.Invoke(new object[] {
new char[] { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' } });
WriteLineMethod.Invoke(null, new object[] { HelloWorldStringObject });
ReadLineMethod.Invoke(null, new object[] { });
}
Run Code Online (Sandbox Code Playgroud)
mar*_*cgg 20
找到适合工作的语言始终是一个问题。脑残怎么样?
+++++ +++++
[
> +++++ ++
> +++++ +++++
> +++
> +
<<<< -
]
> ++ .
> + .
+++++ ++ .
.
+++ .
>++ .
<< +++++ +++++ +++++ .
> .
+++ .
----- - .
----- --- .
> + .
> .
Run Code Online (Sandbox Code Playgroud)
Mat*_*lia 15
C++ 模板滥用。
#include <iostream>
#include <string>
#include <new>
namespace HelloLand
{
template<int Ordinal=1> class Hello
{
private:
Hello<Ordinal<<1> * next;
//We don't want no damned copies
Hello(const Hello<Ordinal> & Other) {}
Hello<Ordinal>& operator=(const Hello<Ordinal>& Other) {}
public:
Hello()
{
next=new Hello<Ordinal<<1>;
}
~Hello()
{
delete next;
}
std::string GetString()
{
return next->GetString() + GetChar();
}
char GetChar();
};
template <> char Hello<1<<0>::GetChar() { return '!'; }
template <> char Hello<1<<1>::GetChar() { return 'd'; }
template <> char Hello<1<<2>::GetChar() { return 'l'; }
template <> char Hello<1<<3>::GetChar() { return 'r'; }
template <> char Hello<1<<4>::GetChar() { return 'o'; }
template <> char Hello<1<<5>::GetChar() { return 'w'; }
template <> char Hello<1<<6>::GetChar() { return ' '; }
template <> char Hello<1<<7>::GetChar() { return 'o'; }
template <> char Hello<1<<8>::GetChar() { return 'l'; }
template <> char Hello<1<<9>::GetChar() { return 'l'; }
template <> char Hello<1<<10>::GetChar() { return 'e'; }
template <> char Hello<1<<11>::GetChar() { return 'H'; }
template<> class Hello<1<<12>
{
public:
std::string GetString()
{
return "";
}
};
}
int main()
{
HelloLand::Hello<> hello;
std::cout<<hello.GetString()<<std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我最喜欢这个东西的是:
dsi*_*cha 12
class Letter {
void print();
static Letter factory(char character) {
Class cl = Class.forName(new String(character));
java.lang.reflect.Constructor co = cl.getConstructor(null);
return (Letter) co.newInstance(null);
}
}
// We don't want to hard code any strings in case the value of
// "H" changes and we want to override it.
class H extends Letter {
void print() {
System.out.println(this.getName());
}
}
class E extends Letter {
void print() {
System.out.println(this.getName());
}
}
class L extends Letter {
void print() {
System.out.println(this.getName());
}
}
class O extends Letter {
void print() {
System.out.println(this.getName());
}
}
class W extends Letter {
void print() {
System.out.println(this.getName());
}
}
class R extends Letter {
void print() {
System.out.println(this.getName());
}
}
class D extends Letter {
void print() {
System.out.println(this.getName());
}
}
public class Main {
public static void main() {
Letter.factory('H').print();
Letter.factory('E').print();
Letter.factory('L').print();
Letter.factory('L').print();
Letter.factory('O').print();
Letter.factory('W').print();
Letter.factory('O').print();
Letter.factory('R').print();
Letter.factory('L').print();
Letter.factory('D').print();
}
}
Run Code Online (Sandbox Code Playgroud)
Bal*_*usC 12
确实不值得“每日 WTF”,但我无法抗拒使用 Java 创建多语言 Hello World :)
\n\npackage mypackage;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URL;\nimport java.net.URLEncoder;\nimport java.util.HashSet;\nimport java.util.Locale;\nimport java.util.Set;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class HelloWorldInAllLanguages {\n\n private static final String HELLO_WORLD = "Hello World";\n private static final String DEFAULT_LANGUAGE = "en";\n private static final String DEFAULT_ENCODING = "UTF-8";\n private static final String TRANSLATOR_URL = "http://ajax.googleapis.com"\n + "/ajax/services/language/translate?v=1.0&q=%s&langpair=%2s%%7C%2s";\n private static final String REGEX = ".*\\\\{\\"translatedText\\":\\"(.*)\\"\\\\}";\n private static final int MATCH_GROUP = 1;\n\n public static void main(String[] args) throws IOException {\n Set<String> processedLanguages = new HashSet<String>();\n for (Locale locale : Locale.getAvailableLocales()) {\n String language = locale.getLanguage();\n if (processedLanguages.add(language)) {\n String url = String.format(TRANSLATOR_URL, \n URLEncoder.encode(HELLO_WORLD, DEFAULT_ENCODING), \n DEFAULT_LANGUAGE, language);\n BufferedReader reader = null;\n String json = null;\n try {\n reader = new BufferedReader(new InputStreamReader(\n new URL(url).openStream(), DEFAULT_ENCODING));\n json = reader.readLine();\n } finally {\n if (reader != null) {\n reader.close();\n }\n }\n Matcher matcher = Pattern.compile(REGEX).matcher(json);\n matcher.find();\n String text = matcher.group(MATCH_GROUP);\n System.out.println(locale.getDisplayLanguage() + ": " + text);\n }\n }\n }\n\n}\nRun Code Online (Sandbox Code Playgroud)\n\n为了避免谷歌翻译服务被其他人堆满,这就是输出,这样你就不需要自己尝试了;)
\n\n\n日语:\xe3\x83\x8f\xe3\x83\xad\xe3\x83\xbc\xe3\x83\xaf\xe3\x83\xbc\xe3\x83\xab\xe3\x83\x89\n西班牙语:Hola Mundo \n英语:Hello World\n塞尔维亚语:\xd0\xa5\xd0\xb5\xd0\xbb\xd0\xbb\xd0\xbe \xd0\xa1\xd0\xb2\xd0\xb5\xd1\x82\n马其顿语:Hello World\ n阿拉伯语:\xd9\x85\xd8\xb1\xd8\xad\xd8\xa8\xd8\xa7\xd8\xa7\xd9\x84\xd8\xb9\xd8\xa7\xd9\x84\xd9\x85\xd9\x8a \n挪威语:Hello World\n阿尔巴尼亚语:Hello World\n保加利亚语:\xd0\x97\xd0\xb4\xd1\x80\xd0\xb0\xd0\xb2\xd0\xb5\xd0\xb9、\xd0\xa1\xd0\xb2 \xd1\x8f\xd1\x82\n希伯来语: \xd7\xa9\xd7\x9c\xd7\x95\xd7\x9d \xd7\xa2\xd7\x95\xd7\x9c\xd7\x9d\n匈牙利语: Hello World\n葡萄牙语: Ol\xc3\xa1 Mundo\n希腊语: Hello World\n瑞典语: Hello World\n德语: Hallo Welt\n芬兰语: Hello World\n冰岛语: Hello World\n捷克语: Hello World\n斯洛文尼亚语: Hello World\n斯洛伐克语: Hello World\n意大利语: \n土耳其语:Merhaba D\xc3\xbcnya\n中文:\xe4\xb8\x96\xe7\x95\x8c\xe6\x82\xa8\xe5\xa5\xbd\n泰语:Hello World\n立陶宛语:Hello World \n罗马尼亚语:Hello World\n荷兰语:Hello World\n爱尔兰语:Hello World\n法语:Bonjour tout le monde\n韩语:\xec\x95\x88\xeb\x85\x95\xed\x95\x98\xec\x84\xb8\ xec\x9a\x94\n爱沙尼亚语:Hello World\n印度尼西亚语:Hello World\n俄语:\xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82 \xd0\xbc\xd0\xb8 \xd1\x80\n拉脱维亚语:Hello World\n希伯来语:\xd7\xa9\xd7\x9c\xd7\x95\xd7\x9d \xd7\x94\xd7\xa2\xd7\x95\xd7\x9c\xd7\x9d\n克罗地亚语: 你好世界\n印地语: \xe0\xa4\xa8\xe0\xa4\xae\xe0\xa4\xb8\xe0\xa5\x8d\xe0\xa4\xa4\xe0\xa5\x87 \xe0\xa4\xb5\xe0 \xa4\xbf\xe0\xa4\xb6\xe0\xa5\x8d\xe0\xa4\xb5\n白俄罗斯语:\xd0\x9f\xd1\x80\xd1\x8b\xd0\xb2\xd1\x96\xd1\x82\ xd0\xb0\xd0\xbd\xd0\xbd\xd0\xb5 \xd1\x81\xd0\xb2\xd0\xb5\xd1\x82\n加泰罗尼亚语:Hola m\xc3\xb3n\n乌克兰语:\xd0\x9f\xd1\ x80\xd0\xb8\xd0\xb2\xd1\x96\xd1\x82 \xd1\x81\xd0\xb2\xd1\x96\xd1\x82\n波兰语:Hello World\n越南语:Xin ch\xc3\xa0o th\xe1 \xba\xbf gi\xe1\xbb\x9bi\n马耳他语: Hello dinja\n马来语: Hello World\n丹麦语: Hello World\n\n
class String
def tack p
self << p
end
def hello
tack 'hello'
end
def comma
tack ','
end
def blank
tack ' '
end
def world
tack 'world'
end
end
puts String.new.hello.comma.blank.world.capitalize
Run Code Online (Sandbox Code Playgroud)