打印流行节日歌曲的所有 12 首诗句。
我所说的12节是指歌曲中所唱的每一行的重复,即
诗歌一:圣诞节的第一天,我的真爱在梨树上给了我一只鹧鸪。
第二节 圣诞节的第二天,我的真爱给了我两只斑鸠和梨树上的一只鹧鸪。
...
第 N 节:在圣诞节的第 n 天,我的真爱给了我(第 N-1 节没有第一行)(第 N 节中添加的行)
打印流行节日歌曲的所有 12 首诗句。
我所说的12节是指歌曲中所唱的每一行的重复,即
诗歌一:圣诞节的第一天,我的真爱在梨树上给了我一只鹧鸪。
第二节 圣诞节的第二天,我的真爱给了我两只斑鸠和梨树上的一只鹧鸪。
...
第 N 节:在圣诞节的第 n 天,我的真爱给了我(第 N-1 节没有第一行)(第 N 节中添加的行)
普通 Lisp:
(mapc #'princ
(reverse (maplist #'(lambda(l)
(format nil
"On the ~:R day of Christmas my true love gave to me~%~{~a~%~}~%"
(length l) l))
'("twelve drummers drumming,"
"eleven pipers piping,"
"ten lords a-leaping,"
"nine ladies dancing,"
"eight maids a-milking,"
"seven swans a-swimming,"
"six geese a-laying,"
"five gold rings,"
"four calling birds,"
"three french hens,"
"two turtle doves, and"
"a partridge in a pear tree."))))
编辑:
如果去掉空格,上面是 412 个字符。
这个:
(let ((g))
(dotimes (i 12)
(format t
"On the ~:R day of Christmas my true love gave to me~%~{~R ~:*~
~[~;~;turtle doves and~;french hens,~;calling birds,~;gold rings,~
~;geese a-laying,~;swans a-swimming,~;maids a-milking,~
~;ladies dancing,~;lords a-leaping,~;pipers piping,~
~;drummers drumming,~]~%~}a partridge in a pear tree~2%"
(1+ i) g)
(push (+ i 2) g)))
如果在格式字符串中去掉空格和 ~ 引用换行符,则为 344 个字符:
(let((g))(dotimes(i 12)(format t"On the ~:R day of Christmas my true love gave to me~%~{~R ~:*~[~;~;turtle doves and~;french hens,~;calling birds,~;gold rings,~;geese a-laying,~;swans a-swimming,~;maids a-milking,~;ladies dancing,~;lords a-leaping,~;pipers piping,~;drummers drumming,~]~%~}a partridge in a pear tree~2%"(1+ i)g)(push(+ i 2)g)))
编辑:
看起来问题已经解决了,该网站正在唠叨我接受答案。据我所知,这个是最短的。如果我接受我自己的答案,我有点害怕网站会做什么——可能会给我一个自恋者或自慰者徽章。
你不能接受自己的答案。很公平。我会把它打开。感谢大家的回应。
使用 F#:
#light
open System.Net; open System.Text.RegularExpressions
printf "%s" ((new WebClient()).DownloadString("http://www.textfiles.com/holiday/12-bugs")
|> (fun x -> (new Regex("Lines: \d+\s+([\s\S]+)--")).Match(x).Groups.[1].Value))
第十二天输出:
对于圣诞节的第十二个错误,我的经理对我说 告诉他们这是一个功能 说不支持 更改文档 归咎于硬件 找到解决方法 说他们需要升级 重新安装软件 要求转储 使用调试器运行 尝试重现它 问他们是怎么做到的 看看他们能不能再做一次。
不是我的,但很有趣……
这是来自http://en.wikipedia.org/wiki/Obfuscated_code的一个著名示例(作者:James O. Coplien):
#include <stdio.h>
main(t,_,a)char *a;{return!0<t?t<3?main(-79,-13,a+main(-87,1-_,
main(-86,0,a+1)+a)):1,t<_?main(t+1,_,a):3,main(-94,-27+t,a)&&t==2?_<13?
main(2,_+1,"%s %d %d\n"):9:16:t<0?t<-72?main(_,t,
"@n'+,#'/*{}w+/w#cdnr/+,{}r/*de}+,/*{*+,/w{%+,/w#q#n+,/#{l,+,/n{n+,/+#n+,/#\
;#q#n+,/+k#;*+,/'r :'d*'3,}{w+K w'K:'+}e#';dq#'l \
q#'+d'K#!/+k#;q#'r}eKK#}w'r}eKK{nl]'/#;#q#n'){)#}w'){){nl]'/+#n';d}rw' i;# \
){nl]!/n{n#'; r{#w'r nc{nl]'/#{l,+'K {rw' iK{;[{nl]'/w#q#n'wk nw' \
iwk{KK{nl]!/w{%'l##w#' i; :{nl]'/*{q#'ld;r'}{nlwb!/*de}'c \
;;{nl'-{}rw]'/+,}##'*}#nc,',#nw]'/+kd'+e}+;#'rdq#w! nr'/ ') }+}{rl#'{n' ')# \
}'+}##(!!/")
:t<-50?_==*a?putchar(31[a]):main(-65,_,a+1):main((*a=='/')+t,_,a+1)
:0<t?main(2,2,"%s"):*a=='/'||main(0,main(-61,*a,
"!ek;dc i@bK'(q)-[w]*%n+r3#l,{}:\nuwloca-O;m .vpbks,fxntdCeghiry"),a+1);}
“虽然乍一看难以理解,但它是一个合法的 C 程序,在编译和运行时会生成《圣诞节的 12 天》的 12 节经文。它包含以编码形式内联在代码中的诗歌所需的所有字符串。代码遍历 12 天,显示它需要什么。”
但它不会赢得高尔夫,它大约是 830 字节。
class TrueLove: ITrueLove
{
List<IPresent> give(int day)
{
List<IPresent> lovesLabourLost = new List<IPresent>();
//if this was C++ could you replace this with a Figgy Duff Device?
for (int i=1; i<=day; i++)
{
if(day > 1 && i<=2) {lovesLabourLost .Add(new TurtleDove());}
if(day > 2 && i<=3) {lovesLabourLost .Add(new FrenchHen());}
if(day > 3 && i<=4) {lovesLabourLost .Add(new CallingBird());}
if(day > 4 && i<=5) {lovesLabourLost .Add(new GOLDRING());}
if(day > 5 && i<=6) {lovesLabourLost .Add(new LayingGeese());}
if(day > 6 && i<=7) {lovesLabourLost .Add(new SwimmingSwan());}
if(day > 7 && i<=8) {lovesLabourLost .Add(new MilikingMaid());}
if(day > 8 && i<=9) {lovesLabourLost .Add(new DancingLady());}
if(day > 9 && i<=10) {lovesLabourLost .Add(new LeapingLord());}
if(day > 10 && i<=11) {lovesLabourLost .Add(new PipingPiper());}
if(day > 11 && i<=12) {lovesLabourLost .Add(new DrummingDrummer());}
}
return lovesLabourLost && (new PartridgeInPearTree());
}
}
static class Me: IDemanding
{
static ITrueLove myTrueLove = new TrueLove();
static List<IPresent> myPresents = new List<IPresent>();
static void demandPresents()
{
for (int i=1; i<=daysOfChristmas; i++)
{
List<IPresent> MOAR = myTrueLove.give(i);
foreach (IPresent another in MOAR)
{
myPresents.Add(another);
}
}
}
}
const int daysOfChristmas = 12;
Me.demandPresents();
在 D 编程语言中,使用 switch 语句贯穿:
import std.stdio;
void main() {
for(uint i = 1; i < 13; i++) {
writeln("On the ", i, " day of Christmas, my true love gave to me:");
switch(i) {
case 12:
writeln("twelve drummers drumming,");
case 11:
writeln("eleven pipers piping,");
case 10:
writeln("ten lords a-leaping,");
case 9:
writeln("nine ladies dancing,");
case 8:
writeln("eight maids a-milking,");
case 7:
writeln("seven swans a-swimming,");
case 6:
writeln("six geese a-laying,");
case 5:
writeln("five gold rings,");
case 4:
writeln("four calling birds,");
case 3:
writeln("three french hens,");
case 2:
writeln("two turtle doves, and");
case 1:
writeln("a partridge in a pear tree.\n");
}
}
}
在 C++ 中,你会
std::cout << boost::12_days_of_christmas;
var t="";for(int i=0;i++<12;)Console.Write("On the {0}{1} day of Christmas, my true love gave to me: {2}\n",i,i<2?"st":i<3?"nd":i<4?"rd":"th",t="|a partridge in a pear tree.|two turtle doves, and |three french hens,|four calling birds,|five gold rings|six geese a-lay@seven swans a-swimm@eight maids a-milk@nine ladies danc@ten lords a-leap@eleven pipers pip@twelve drummers drumm@".Replace("@","ing,|").Split('|')[i]+t);
var t="";
for(int i = 0; i++ < 12;)
Console.Write("On the {0}{1} day of Christmas, my true love gave to me: {2}\n",
i,
i < 2 ? "st" : i < 3 ? "nd" : i < 4 ? "rd" : "th",
t="|a partridge in a pear tree.
|two turtle doves, and
|three french hens,
|four calling birds,
|five gold rings
|six geese a-lay
@seven swans a-swimm
@eight maids a-milk
@nine ladies danc
@ten lords a-leap
@eleven pipers pip
@twelve drummers drumm@"
.Replace("@","ing,|")
.Split('|')[i]+t);
$v=split(":",":a partridge in a pear tree.\n:two turtle doves, and:three french hens:four calling birds:five gold rings:six geese a-lay:seven swans a-swimm:eigth maids a-milk:nine ladies danc:ten lords a-leap:eleven pipers pip:twelve drummers drumm");while($i<12){?>On the <?=date(jS,$i*86400)," day of Christmas my true love gave to me",$s=", ".$v[++$i].($i>5?'ing':'').$s;}
编辑:更新的可运行版本(377)字符
<?$v=split(":",":a partridge in a pear tree.\n:two turtle doves, and:three french hens:four calling birds:five gold rings:six geese a-lay:seven swans a-swimm:eigth maids a-milk:nine ladies danc:ten lords a-leap:eleven pipers pip:twelve drummers drumm");while($i<12){?>On the <?=date(jS,$i*86400)," day of Christmas my true love gave to me",$s=", ".$v[++$i].($i>5?'ing':'').$s;}
VB.Net - 530 个字符(无空格)、634 个(空格)
Module ChristmasSong
Sub Main()
Dim i&, f$ : Dim d$() = {"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"}, g$() = {"a partridge in a pear tree.", "two turtle doves, and ", "three french hens, ", "four calling birds, ", "five gold rings, ", "six geese a-laying, ", "seven swans a-swimming, ", "eigth maids a-milking, ", "nine ladies dancing, ", "ten lords a-leaping, ", "eleven pipers piping, ", "twelve drummers drumming, "}
For i = 0 To 11 : f = g(i) & f : Console.WriteLine("On the {0} day of Christmas, my true love gave to me {1}", d(i), f) : Next
End Sub
End Module
Linq to objects,580 个字符(没有空格)
Console.WriteLine(Enumerable.Range(1, 13).SelectMany(day =>
Enumerable.Repeat("\nOn the " + day +
(day == 1 ? "st" :
(day == 2 ? "nd" :
(day == 3 ? "rd" :
"th"))) + " day of Christmas my true love gave to me ", 1)
.Concat((new []
{
"twelve drummers drumming,",
"eleven pipers piping,",
"ten lords a-leaping,",
"nine ladies dancing,",
"eight maids a-milking,",
"seven swans a-swimming,",
"six geese a-laying,",
"five gold rings,",
"four calling birds,",
"three french hens,",
"two turtle doves, and",
"a partridge in a pear tree."
}).Reverse().Take(day).Reverse()))
.Aggregate((a, b) => a + "\n" + b));
珀尔。
use Lingua::EN::Numbers qw(num2en_ordinal);
print 'On the ', num2en_ordinal($_+1),' day of Christmas my true love gave to me, ', reverse(( split /\|/, "a partridge in a pear tree.\n|two turtle doves, and |three french hens, |four calling birds, |five gold rings, |six geese a-laying, |seven swans a-swimming, |eight maids a-milking, |nine ladies dancing, |ten lords a leaping, |eleven pipers piping, |twelve drummers drumming, ")[ 0 .. $_ ]) for 0 .. 11;
(459 个字符)
我想让它变得更好,更有表现力,但这是一个高尔夫挑战。
这种风格在某种程度上违反了适当的编码标准。但这对你来说是高尔夫。
这是不太紧凑的版本,具有较少的偷偷摸摸的技巧。
use Lingua::EN::Numbers qw(num2en_ordinal);
my @gifts = (
'a partridge in a pear tree.',
'two turtle doves, and ',
'three french hens, ',
'four calling birds, ',
'five gold rings, ',
'six geese a-laying, ',
'seven swans a-swimming, ',
'eight maids a-milking, ',
'nine ladies dancing, ',
'ten lords a leaping, ',
'eleven pipers piping, ',
'twelve drummers drumming, '
);
for my $verse_id ( 0 .. $#gifts ) {
printf 'On the %s day of Christmas my true love gave to me, ', num2en_ordinal($verse_id +1);
print reverse @verse[ 0 .. $verse_id ];
print "\n";
}
for d in range(12):print"On the %s day of Christmas, my true love gave to me\n\t%s\n"%("first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth|eleventh|twelfth".split("|")[d],"\n\t".join("twelve drummers drumming|eleven pipers piping|ten lords a-leaping|nine ladies dancing|eight maids a-milking|seven swans a-swimming|six geese a-laying|five gold rings|four calling birds|three french hens|two turtle doves and|a partridge in a pear tree.".split("|")[11-d:]))
Python,422 个字符
'这是季节!(而且相当合适,因为 LilyPond 主要用于排版音乐......除了歌词之外,人们可以轻松地修改此代码来为歌曲制作乐谱。)
改编自 fizzer 的解决方案。
#(map(lambda(x)(format #t"On the ~:R day of Christmas my true love gave to me~{ ~R~:*~[~;~;turtle doves and~;French hens,~;calling birds,~;gold rings,~;geese a-laying,~;swans a-swimming,~;maids a-milking,~;ladies dancing,~;lords a-leaping,~;pipers piping,~;drummers drumming,~]~} a partridge in a pear tree.
"x(iota(1- x)x -1)))(iota 12 1))
用法:$ lilypond thisfile.ly
此版本包含 341 个字符,与 fizzer 的输出完全匹配,但短了三个字节:
#(map(lambda(x)(format #t"On the ~:R day of Christmas my true love gave to me~{
~R ~:*~[~;~;turtle doves and~;french hens,~;calling birds,~;gold rings,~;geese a-laying,~;swans a-swimming,~;maids a-milking,~;ladies dancing,~;lords a-leaping,~;pipers piping,~;drummers drumming,~]~}
a partridge in a pear tree
"x(iota(1- x)x -1)))(iota 12 1))
红宝石。我认为这非常简洁(辛勤工作都在一条线上):
days = %w{First Second Third Fourth Fifth Sixth Seventh Eighth Ninth Tenth Eleventh Twelfth}
presents = [
"twelve drummers drumming",
"eleven pipers piping",
"ten lords a leaping",
"nine ladies dancing",
"eight maids a-milking",
"seven swans a-swimming",
"six geese a-laying",
"five gold rings",
"four calling birds",
"three french hens",
"two turtle doves, and",
"a partridge in a pear tree"
]
0.upto(11) { |i|
puts "On the #{days[i]} of Christmas my true love gave to me " + presents.last(i+1).join(", ")
}
perl -MTemplate -e 'Template->new()->process("12dayxmas.tt")'
[% 清单 = [ { day => 'first', item => '梨树上的鹧鸪'}, { day => 'second', item => '两只斑鸠和'}, { day => 'third', item => '三只法国母鸡, '}, { day => 'fourth', item => '四只呼唤鸟,'}, { day => 'fifth', item => '五枚金戒指, '}, { day => '第六', item => '六鹅产蛋, '}, { day => 'seventh', item => '七只天鹅游泳,'}, { day => '第八', item => '八个女仆挤奶, '}, { day => '第九', item => '九位女士跳舞, '}, { day => 'tenth', item => '十主跳跃, '}, { day => '十一',item => '十一风笛,'}, { day => '第十二',item => '十二个鼓手打鼓,'} ]; -%] [% FOREACH 清单; 礼物=物品_礼物; -%] 在圣诞节的 [% day %] 那天,我的真爱给了我 [% present %] [% 结尾 %]
这是一个PHP解决方案:
$day = Array('first','second','third','fourth','fifth','sixth','seventh',
'eighth','ninth','tenth','eleventh','twelfth');
$gifts = Array('Twelve drummers drumming,',
'Eleven pipers piping,',
'Ten lords a-leaping,',
'Nine ladies dancing,',
'Eight maids a-milking,',
'Seven swans a-swimming,',
'Six geese a-laying,',
'FIVE GOLDEN RINGS,',
'Four calling birds,',
'Three French hens,',
'Two turtle doves, and',
'A partridge in a pear tree');
for ($i = 0; $i < 12; ++$i) {
printf("On the $day[$i] of Christmas my true love gave to me\n" .
implode("\n", array_slice($gifts,-($i+1))) . "\n\n");
}
h
在我编造的语言中,命令h
打印“Hello,World!”。哦等等,你的意思是这不是我们在说什么?
import sys
sys.path += ["TDOC.zip"]
import TDOC
TDOC.print_verse()
其中 TDOC.zip(467 字节)包含 TDOC.py:
def print_verse(presents="""\
twelve drummers drumming,
eleven pipers piping,
ten lords a-leaping,
nine ladies dancing,
eigth maids a-milking,
seven swans a-swimming,
six geese a-laying,
five gold rings,
four calling birds,
three french hens,
two turtle doves, and
a partridge in a pear tree.""".split("\n")):
if presents:
print_verse(presents[1:])
number = presents[0].split(" ", 1)[0]
print("On the %s day of Christmas my true love gave to me %s" % (
dict(a="first", two="second", three="third", five="fifth").get(number, number+"th"),
" ".join(presents)))
C#:
string[] s = new string[]{
"a partridge in a pear tree.",
"two turtle doves, and ",
"three french hens, ",
"four calling birds, ",
"five gold rings, ",
"six geese a-laying, ",
"seven swans a-swimming, ",
"eight maids a-milking, ",
"nine ladies dancing, ",
"ten lords a-leaping, ",
"eleven pipers piping, ",
"twelve drummers drumming, "
};
string t = "";
for (int x = 0; x < s.Length; x++) {
t = s[x] + t;
Console.Write("On the "
+ (x + 1).ToString()
+ (x == 0 ? "st" : (x == 1 ? "nd" : (x == 2 ? "rd" : "th")))
+ " day of christmas, my true love gave to me: " + t + "\n");
}
574 个字符,不包括缩进。添加一些额外的字符以使号码扩展正确。不过,可能会有所改进。
C#
string[] days = new string[] {"First",
"Second", "Third", "Fourth", "Fifth", "Sixth",
"Seventh", "Eighth", "Ninth", "Tenth", "Eleventh", "Twelfth"};
string[] presents = new string[] {"a partridge in a pear tree.",
"two turtle doves, and",
"three french hens,",
"four calling birds,",
"five gold rings,",
"six geese a-laying,",
"seven swans a-swimming,",
"eigth maids a-milking,",
"nine ladies dancing,",
"ten lords a-leaping,",
"eleven pipers piping,",
"twelve drummers drumming,"};
int cnt =0;
foreach (string s in presents)
{
Console.WriteLine(string.Format("On the {0} day of Christmas my true love gave to me", days[cnt++]));
foreach (string p in presents.Take(cnt).Reverse())
Console.WriteLine(p);
Console.WriteLine(System.Environment.NewLine);
}
我无法击败 Lisp 版本,但它仍然很有趣。
德尔福版本:
procedure TheTwelfDaysOfChristmas(const AVerse: TStrings);
const
cPresentList : array[1..12] of string = (
'a partridge in a pear tree',
'two turtle doves, and ',
'three french hens, ',
'four calling birds, ',
'five gold rings, ',
'six geese a-laying, ',
'seven swans a-swimming, ',
'eigth maids a-milking, ',
'nine ladies dancing, ',
'ten lords a-leaping, ',
'eleven pipers piping, ',
'twelve drummers drumming, '
);
cTime : array[1..12] of string = (
'first',
'second',
'third',
'fourth',
'fifth',
'sixth',
'seventh',
'eighth',
'nineth',
'tenth',
'eleventh',
'twelfth'
);
var
present : string;
i : Integer;
begin
present := '';
for i := 1 to 12 do begin
present := cPresentList[i] + present;
AVerse.Add(Format('On the %s day of Christmas my true love gave me %s.',
[cTime[i], present]));
end;
end;
顺便说一句,对于你们所有人,2009 年节日快乐,编程很棒。
红宝石
a=["and a partridge in a pear tree","turtle doves","French hens","calling birds","golden rings","geese a-laying","swans a-swimming","maids a-milking","ladies dancing","lords a-leaping","pipers piping","drummers drumming"]
b=["","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve"]
c=["first","second","third","fourth","fifth","sixth","seventh","eighth","nineth","tenth","eleventh","twelfth"]
0.upto(11){|d|puts "On the "+c[d]+" day of Christmas, my true love gave to me:\n"+b[d]+" "+a[d]+",";(d-1).downto(0){|e| f=", ";f = "." if e==0;puts b[e]+" "+a[e]+f;}}
总计:593 字节,使用 UNIX LF。
PHP
$g = array("a partridge in a pear tree.\n",
"two turtle doves, and",
"three french hens,",
"four calling birds,",
"five gold rings,",
"six geese a-laying,",
"seven swans a-swimming,",
"eight maids a-milking,",
"nine ladies dancing,",
"ten lords a-leaping,",
"eleven pipers piping,",
"twelve drummers drumming,"
);
$d = array("first", "second", "third", "fourth", "fifth", "sixth",
"seventh", "eighth", "nineth", "tenth", "eleventh", "twelfth");
foreach($d as $i=>$v){
echo "On the $v day of Christmas my true love gave to me";
for($j=$i;$j>=0;$j--) echo " ",$g[$j];
}
26 字节!..
正如 URL 所暗示的,它可能被认为是.. 作弊:
http://github.com/dbr/so_scripts/tree/master/golf_tdoc/cheating.bash
这是一个 Haskell 版本:
import Data.List
main=putStrLn$unlines$map(uncurry(\n->(++)("On the "++show n++case n of{1->"st";2->"nd";3->"rd";_->"th"}++" day of Christmas, my true love gave to me: ")))$zip[1..]$(\a->(drop 4$head a):tail a)$ map(intercalate", ".reverse)$tail$inits["and a partridge in a pair tree","two turtle doves","three french hens","four calling birds","five gold rings","six geese a-laying","seven swans a-swimming","eight maids a milking","nine ladies dancing","ten lords a-leaping","eleven pipers piping","twelve drummers drumming"]
它有 527 个字符。由于没有良好的间距,它相当难以理解,这里有一个更分散的版本:
import Data.List
main = putStrLn
$ unlines
$ map (uncurry (\n -> (++) ("On the " ++ show n ++ case n of { 1 -> "st"; 2 -> "nd"; 3 -> "rd"; _ -> "th"} ++ " day of Christmas, my true love gave to me: ")))
$ zip [1..]
$ (\a -> (drop 4 $ head a) : tail a)
$ tail
$ map (intercalate ", " . reverse)
(inits ["and a partridge in a pair tree", "two turtle doves", "three french hens", "four calling birds", "five gold rings", "six geese a-laying", "seven swans a-swimming", "eight maids a milking", "nine ladies dancing", "ten lords a-leaping", "eleven pipers piping", "twelve drummers drumming"])
另一个 C#
var l="a partridge in a pear tree.|two turtle doves, and|three french hens,|four calling birds,|five gold rings,|six geese a-laying,|seven swans a-swimming,|eight maids a-milking,|nine ladies dancing,|ten lords a-leaping,|eleven pipers piping,|twelve drummers drumming,".Split('|');
for (int i = 1; i < 13; i++)
Console.Write(
"On the {0}{2} day of christmas\rmy true love gave to me \r{1}\r\r",
i,
string.Join("\r", l.Take(i).Reverse().ToArray()),
(i==1?"st":i==2?"nd":i==3?"rd":"th"));
从以前的答案中大量借用(嘿,代码重用),同时增加了额外的节省。
去掉不必要的空格后 481 个字符:
var l="a partridge in a pear tree.|two turtle doves, and|three french hens,|four calling birds,|five gold rings,|six geese a-laying,|seven swans a-swimming,|eight maids a-milking,|nine ladies dancing,|ten lords a-leaping,|eleven pipers piping,|twelve drummers drumming,".Split('|');for(int i=1;i<13;i++)Console.Write("On the {0}{2} day of christmas, my true love gave to me \r{1}\r\r",i,String.Join("\r",l.Take(i).Reverse().ToArray()),(i==1?"st":i==2?"nd":i==3?"rd":"th"));
Objective-C / Cocoa
NSArray *days = [NSArray arrayWithObjects:@"first", @"second", @"third", @"forth",
@"fifth", @"six", @"seventh", @"eigth",
@"ninth", @"tenth", @"eleventh", @"twelth", nil];
NSArray *gifts = [NSArray arrayWithObjects:
@"a partridge in a pear tree.\n\n",
@"two turtle doves, and\n",
@"three french hens,\n",
@"four calling birds,\n",
@"five gold rings,\n",
@"six geese a-laying,\n",
@"seven swans a-swimming,\n",
@"eigth maids a-milking,\n",
@"nine ladies dancing,\n",
@"ten lords a-leaping,\n",
@"eleven pipers piping,\n",
@"twelve drummers drumming,\n",
nil];
NSMutableString *aggregator = [NSMutableString string];
for(int i = 0; i < 12; i++) {
[aggregator insertString:[gifts objectAtIndex:i] atIndex:0];
printf("on the %s day of xmas, my true love gave to me %s", [[days objectAtIndex:i] UTF8String], [aggregator UTF8String]);
}
一条线怎么样!这是在 C# 中。
Xmas(){Console.WriteLine("On the first day of Christmas,\r\nmy true love sent to me\r\nA partridge in a pear tree.\r\n\r\nOn the second day of Christmas,\r\nmy true love sent to me\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the third day of Christmas,\r\nmy true love sent to me\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the fourth day of Christmas,\r\nmy true love sent to me\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the fifth day of Christmas,\r\nmy true love sent to me\r\nFive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the sixth day of Christmas,\r\nmy true love sent to me\r\nSix geese a-laying,\r\nFive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the seventh day of Christmas,\r\nmy true love sent to me\r\nSeven swans a-swimming,\r\nSix geese a-laying,\r\nFive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the eighth day of Christmas,\r\nmy true, love sent to me\r\nEight maids a-milking,\r\nSeven swans a-swimming,\r\nSix geese a-laying,\r\nFive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the ninth day of Christmas,\r\nmy true love sent to me\r\nNine ladies dancing,\r\nEight maids a-milking,\r\nSeven swans a-swimming,\r\nSix geese a-laying,\r\nFive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the tenth day of Christmas,\r\nmy true love sent to me\r\nTen lords a-leaping,\r\nNine ladies dancing,\r\nEight maids a-milking,\r\nSeven swans a-swimming,\r\nSix geese a-laying,\r\nfive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the eleventh day of Christmas,\r\nmy true love sent to me\r\nEleven pipers piping,\r\nTen lords a-leaping,\r\nNine ladies dancing,\r\nEight maids a-milking,\r\nSeven swans a-swimming,\r\nSix geese a-laying\r\nFive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree.\r\n\r\nOn the twelfth day of Christmas,\r\nmy true love sent to me\r\nTwelve drummers drumming,\r\nEleven pipers piping,\r\nTen lords a-leaping,\r\nNine ladies dancing,\r\nEight maids a-milking,\r\nSeven swans a-swimming,\r\nSix geese a-laying,\r\nFive golden rings,\r\nFour calling birds,\r\nThree French hens,\r\nTwo turtle doves,\r\nAnd a partridge in a pear tree!");}
C#:395 个字符(不包括空格...)
for (var x = 0; x++ < 12; )
Console.Write(
"On the {0} day of Christmas,\nMy true love gave to me\n{1}\n\n",
x + (x < 2 ? "st" : x < 3 ? "nd" : x < 4 ? "rd" : "th"),
String.Join(
"\n",
"a partridge in a pear tree.|turtle doves and|french hens|calling birds|gold rings|geese a-laying|swans a-swimming|maids a-milking|ladies dancing|lords a-leaping|pipers piping|drummers drumming"
.Split('|').Take(x).Select((y, i) => (i > 0 ? (i + 1) + " " : "") + y).Reverse().ToArray()
)
);
这是一个 erlang 版本(约 586 个字符):
-module (xmas).
-export ([xmas/0]).
xmas() ->
W = ["twelve drummers drumming, ",
"eleven pipers piping, ",
"ten lords a-leaping, ",
"nine ladies dancing, ",
"eight maids a-milking, ",
"seven swans a-swimming, ",
"six geese a-laying, ",
"five gold rings, ",
"four calling birds, ",
"three french hens, ",
"two turtle doves, and ",
"a partridge in a pear tree."],
io:format(lists:foldl(
fun(X,Acc) -> Acc ++ X ++ "~n" end, "",
["On the " ++ day_str(Q) ++
" day of Christmas, my true love gave me " ++
lists:foldl(
fun(X,Acc)-> Acc++X end,
"", lists:nthtail(12-Q,W)) ||
Q <- lists:seq(1,12)]),[]).
day_str(Q) ->
case Q of
1 -> "1st";
2 -> "2nd";
3 -> "3rd";
N -> erlang:integer_to_list(N,10) ++ "th"
end.
(443 包括可选的换行符)
print """
eJzlk91xxCAMhN9TxRZwSRMp4GpQjGw04ccDunOu+wjcgMkkk8vlxRjQst9q4JygnjFLqQpHN+QZ
r75I1UgV8QYtF0bIV8ZC9tGMyCCsVLSIWxiS2pSpWCnzy9N5P7HylJM7fqRuGXopGhjOtuoJZPID
RuqljPh4E2MunCYPz8mMvmw9Z1P5496tHhOFIGnBm2E38+/kkXkIR9o8B4diQGbz03xVPkb4rBwL
c7X79hzoZlCnX2DmK6ch6iZA3ShV466bxNjJ7yINy6J+JE0XIJK4liZKeN/D3HPIJIlHMrZ6BHLC
1URp6tR/MbiO3VQrt7XSAwamtUM/TDM4jL7cXYFVVi61DR38sbukG4fr0GvZFXDlEmPrU//Z8/+j
/n0CsHRGTA==
""".decode("base64").decode("zlib")
即使已经结束了一段时间,我仍然喜欢尝试这些代码高尔夫挑战......
我能用MATLAB 做的最好的事情:383个字符(删除空格和续行符号后)
a = {'twelve drummers drumming';...
'eleven pipers piping';...
'ten lords a-leaping';...
'nine ladies dancing';...
'eight maids a-milking';...
'seven swans a-swimming';...
'six geese a-laying';...
'five gold rings';...
'four calling birds';...
'three french hens';...
'two turtle doves and';...
'a partridge in a pear tree.';’’};
b = {'st','nd','rd','th'};
for i = 1:12,...
disp(char(['On the ',num2str(i),b{min(i,4)},...
' day of Christmas my true love gave to me'],...
a{13-i:13}));...
end
423 字节,Lingua::EN::Number:
use Lingua::EN::Numbers qw/num2en num2en_ordinal/;
@l=map{($i++?num2en($i):'a')." $_"}split/\n/,<<"";
partridge in a pear tree
turtle doves, and
french hens
calling birds
gold rings
geese a-laying
swans a-swimming
maids a-milking
ladies dancing
lords a-leaping
pipers piping
drummers drumming
print"On the ".num2en_ordinal($_+1)
." day of Christmas, my true love gave to me ",
join(', ',reverse@l[0..$_]),"\n\n"for(0..11);
或者不使用 Lingua::EN::Numbers 的 perl 中的 480 字节:
@n=qw/first second third forth fifth sixth seventh eigth nineth tenth eleventh twelfth/;
@l=<DATA>;chomp@l;
print"On the $n[$_] day of Christmas, my true love gave to me ",
join(', ',reverse@l[0..$_]),"\n\n"for(0..11);
__DATA__
a partridge in a pear tree
two turtle doves, and
three french hens
four calling birds
five gold rings
six geese a-laying
seven swans a-swimming
eight maids a-milking
nine ladies dancing
ten lords a-leaping
eleven pipers piping
twelve drummers drumming
它应该能够进一步减少,因为数字非常重复。
Console.WriteLine(File.ReadAllText("12daysxmas.txt"));
(将字符串常量与代码分开是一种很好的做法,这样您就可以轻松地翻译它们。)
dynamic
另外,这是我对C# 4 中即将到来的关键字的致敬:
string lyric = "On day {0} of Christmas a dynamic gave to me {1} dynamics.";
int total = 0;
for (int day = 1; day <= 12; day++)
{
total += day;
Console.WriteLine(string.Format(lyric, day, total));
}
Console.WriteLine("I wonder what all these dynamics are? I guess I'll find out at runtime.");
Ruby:458 个字符
(+ 4 个换行符使其保持在 80 列以下)
n=%w{first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth}
s=''
["a partridge in a pear tree","two turtle doves, and","three french hens",
"four calling birds","five gold rings","six geese a-laying","seven swans a-swimming",
"eight maids a-milking","nine ladies dancing","ten lords a leaping",
"eleven pipers piping","twelve drummers drumming"].map{|p|
puts "On the #{n.pop} day of Christmas my true love gave to me: "+(s=p+', '+s)}
Java,基于 Esko 的第二种解决方案:
class C{
public static void main(String[]d){
String s="";
d="first1second1third1fourth1fifth1sixth1seventh1eighth1ninth1tenth1eleventh1twelfth".split("1");
String[]g="a partridge in a pear tree1two turtle doves,\nand 1three french hens,\n1four calling birds,\n1five gold rings,\n1six geese a-laying\n1seven swans a-swimming,\n1eight maids a-milking,\n1nine ladies dancing,\n1ten lords a-leaping,\n1eleven pipers piping,\n1twelve drummers drumming,\n".split("1");
for(int i=0;i<12;)
System.out.println("On the "+d[i]+" day of Christmas my true love gave to me:\n"+
(s=g[i++]+s)+".\n");
}
}
如果我计算正确,那是 579 个字符(不包括缩进和换行符)。而这个是完全可运行的,并且不会将每一节都打印在一行上。输出是:
在圣诞节的第一天,我的真爱给了我:
梨树上的一只鹧鸪。圣诞节的第二天,我的真爱给了我:
两只斑鸠,和
梨树上的一只鹧鸪。在圣诞节的第三天,我的真爱给了我:
三只法国母鸡、
两只斑鸠和
梨树上的一只鹧鸪。...
编辑:略微改进的版本,基于 balabaster 用一个字符替换公共字符串的想法:
class C{
public static void main(String[]d){
String s="";
d="first1second1third1fourth1fifth1sixth1seventh1eighth1ninth1tenth1eleventh1twelfth".split("1");
String[]g="a partridge in a pear tree1two turtle doves,\nand 1three french hens,\n1four calling birds,\n1five gold rings,\n1six geese a-lay#seven swans a-swimm#eight maids a-milk#nine ladies danc#ten lords a-leap#eleven pipers pip#twelve drummers drumm#".replace("#","ing,\n1").split("1");
for(int i=0;i<12;)
System.out.println("On the "+d[i]+" day of Christmas my true love gave to me:\n"+
(s=g[i++]+s)+".\n");
}
}
它现在减少到 562 个字符(尽管我添加了一个以前错过的逗号)。
这不会赢,但这是我的 576 个字符的 Java 版本(可编译和可运行)。
class T{enum D{first,second,third,fourth,fifth,sixth,seventh,eighth,ninth,tenth,eleventh,twelfth}public static void main(String[] args){String o="",s="s, ",i="ing, ";String t[]={"a partridge in a pear tree","two turtle doves, and ","three french hen"+s,"four calling bird"+s,"five gold ring"+s,"six geese a-lay"+i,"seven swans a-swimm"+i,"eight maids a-milk"+i,"nine ladies danc"+i,"ten lords a-leap"+i,"eleven pipers pip"+i,"twelve drummers drumm"+i};int j=0;while(j<12)System.out.println("On the "+D.values()[j]+" day of Christmas my true love gave to me "+(o=t[j++]+o));}}
这里有一些 C# 的不同方法
List<string> lines = new List<string>(new string[]{
"twelve drummers drumming,\n\r"
, "eleven pipers piping,\n\r"
, "ten lords a-leaping,\n\r"
, "nine ladies dancing,\n\r"
, "eigth maids a-milking,\n\r"
, "seven swans a-swimming,\n\r"
, "six geese a-laying,\n\r"
, "five gold rings,\n\r"
, "four calling birds,\n\r"
, "three french hens,\n\r"
, "two turtle doves, and \n\r"
, "a partridge in a pear tree."
});
string[] day = {
"first"
,"second"
,"thrid"
,"forth"
,"fifth"
,"six"
,"seventh"
,"eigth"
,"ninth"
,"tenth"
,"eleventh"
,"twelth"
};
for (int i = 0; i < 12; i++)
Console.WriteLine(string.Format("On the {0} day of christmas, my true love gave to me\n\r{1}", day[i], string.Concat(lines.GetRange(11 - i, i + 1).ToArray())));
不是很好。但它很小。:)
没有看到 Java 的任何内容(顺便说一句,它的最小语法并不为人所知)所以首先我做了这个
String g;
public void sing() {
g = "";
for(Entry<?,?> e : mm("first", "a partridge in a pear tree",
"second", "two turtle doves, and ",
"third", "three french hens, ",
"fourth", "four calling birds, ",
"fifth", "five gold rings, ",
"sixth", "six geese a-laying ",
"seventh", "seven swans a-swimming, ",
"eigth", "eight maids a-milking, ",
"ninth", "nine ladies dancing, ",
"tenth", "ten lords a-leaping, ",
"eleventh", "eleven pipers piping, ",
"twelfth", "twelve drummers drumming, ").entrySet()) {
System.out.println("On the "+e.getKey()+
" day of Christmas my true love gave to me "+e.getValue()+".");
}
}
public Map<?,?> mm(String... s) {
Map m = new LinkedHashMap();
for(int i=0;i<s.length;i=i+2) {
g = s[i+1] + g;
m.put(s[i], g);
}
return m;
}
并意识到它相当复杂(重 708 个字符),所以我选择了一个更简单的解决方案(改编自其他答案,行更改仅是为了便于阅读):
public void sing() {
String s = "";
String[]d={"first","second","third","fourth",
"fifth","sixth","seventh","eighth",
"ninth","tenth","eleventh","twelfth"};
String[]g={"a partridge in a pear tree",
"two turtle doves, and ",
"three french hens, ",
"four calling birds, ",
"five gold rings, ",
"six geese a-laying ",
"seven swans a-swimming, ",
"eight maids a-milking, ",
"nine ladies dancing, ",
"ten lords a-leaping, ",
"eleven pipers piping, ",
"twelve drummers drumming, "};
int i=0;
while(i<12)
System.out.println("On the "+d[i]+" day of Christmas my true love gave to me "+
(s=g[i++]+s)+".");
}
这是没有空格的 576 个字符,如果方法签名切换到正确的 main() 那么它是 596。
如果我有兴趣制作第三个版本,我也会尝试枚举技巧。
AC/C++ 版本使用单个缓冲区和指针算法。一个包含,一个声明,技术上只有两行代码在 main 中进行打印:
#include <stdio.h>
char *days =
"twelve drummers drumming, \n"
"eleven pipers piping, \n"
"ten lords a-leaping, \n"
"nine ladies dancing, \n"
"eight maids a-milking, \n"
"seven swans a-swimming, \n"
"six geese a-laying, \n"
"five gold rings, \n"
"four calling birds, \n"
"three french hens, \n"
"two turtle doves, and \n"
"a partridge in a pear tree.\n\n";
void main()
{
for (int i = 1; i <= 12; i++)
printf("On the %d%s day of Christmas, my true love gave to me:\n%s",
i,i == 1 ? "st" : (i == 2 ? "nd" : "th"), days + (12-i)*28);
}
C ++中非常简单的解决方案:
#include <iostream.h>
char*a[]={"a partridge in a pear tree.\n","two turtle doves, and","three french hens,","four calling birds,","five gold rings,","six geese a-laying,","seven swans a-swimming,","eight maids a-milking,","nine ladies dancing,","ten lords a-leaping,","eleven pipers piping,","twelve drummers drumming,"};
char*b[]={"first","second","third","fourth","fifth","sixth","seventh","eighth","nineth","tenth","eleventh", "twelfth"};
int main(){for(int i=0;i<12;i++){std::cout<<"On the "<<b[i]<<" day of Christmas my true love gave to me, \n";for(int j=i;j>=0;j--)std::cout<<a[j]<<" \n";}}
595 个字符,但如果您允许某些人使用的“1st, 2nd, 3rd”等符号,它可以减少到 513 个字符。
LUA 540(没有标签和返回)
t={"twelve drummers drumming,","eleven pipers piping,","ten lords a-leaping,","nine ladies dancing,","eight maids a-milking,","seven swans a-swimming,","six geese a-laying,","five gold rings,","four calling birds,","three french hens,","two turtle doves, and","a partridge in a pear tree."}
f=function(i)
r=i.."th"
if (i==1) then r=i.."st"
elseif (i==2) then r=i.."nd"
elseif (i==3) then r=i.."rd"
end
return r
end
for i=1,12 do
s="On the "..f(i).." day of Christmas my true love gave to me"
for j=13-i,12 do
s=s.." "..t[j]
end
print(s)
end
不幸的是,我们没有字符串到数组函数或通过日期库执行“第一次”的方法。正确运行于http://www.lua.org/cgi-bin/demo
这是一个Javascript版本。我能做的最好的就是压缩后的 497 个字符。
s = "", k = "ing, ", t = [":first:a:partridge in a pear tree",
":second:two:turtle doves, and ",
"th:ird:ree:french hens, ",
"four:th::calling birds, ",
"fi:fth:ve:gold rings, ",
"six:th::geese a-lay" + k,
"seven:th::swans a-swimm" + k,
"eight:h::maids a-milk" + k,
"nin:th:e:ladies danc" + k,
"ten:th::lords a-leap" + k,
"eleven:th::pipers pip" + k,
"twel:fth:ve:drummers drumm"]
for (i = 0; i < 12; i++)
document.write("On the " + (v = t[i].split(":"))[0] + v[1]
+ " day of Christmas my true love gave to me "
+ (s = v[0] + v[2] + " " + v[3] + s) + "<p>")
s="",k="ing, ",t=[":first:a:partridge in a pear tree",":second:two:turtle doves, and ","th:ird:ree:french hens, ","four:th::calling birds, ","fi:fth:ve:gold rings, ","six:th::geese a-lay"+k,"seven:th::swans a-swimm"+k,"eight:h::maids a-milk"+k,"nin:th:e:ladies danc"+k,"ten:th::lords a-leap"+k,"eleven:th::pipers pip"+k,"twel:fth:ve:drummers drumm"];for(i=0;i<12;i++)document.write("On the "+(v=t[i].split(":"))[0]+v[1]+" day of Christmas my true love gave to me "+(s=v[0]+v[2]+" "+v[3]+s)+"<p>")
偶然发现这个线程,它看起来非常有趣,我无法抗拒 - 这是另一个 JavaScript 版本 - 它不是最短的,但我喜欢它在循环内使用递归和闭包的方式。
(function(){
var v = [
{d:'first', p:'a partridge in a pear tree'},
{d:'second', p:'two turtle doves, and '},
{d:'third', p:'three french hens, '},
{d:'fourth', p:'four calling birds, '},
{d:'fifth', p:'five gold rings, '},
{d:'sixth', p:'six geese a-laying, '},
{d:'seventh', p:'seven swans a-swimming, '},
{d:'eighth', p:'eight maids a-milking, '},
{d:'ninth', p:'nine ladies dancing, '},
{d:'tenth', p:'ten lords a-leaping, '},
{d:'eleveth', p:'eleven pipers piping, '},
{d:'twelth', p:'twelve drummers drumming, '}
];
for (var i=0;i<12;i++)
{
document.write('On the '+v[i].d+' day of Christmas my true love gave to me ');
(function(i){
document.write(v[i].p);
if (i>0)
{
arguments.callee(--i);
}
})(i);
document.write('.<p>');
}
})();