Code Golf: печать всей песни "12 дней Рождества" в наименьших строках кода
Распечатайте все 12 стихов популярной праздничной песни.
В 12 стихах я подразумеваю повторение каждой строки, которая исполняется в песне, т.е.
Стих первый:
В первый день Рождества моя настоящая любовь дала мне
куропатка в грушевом дереве.
Второй стих
Во второй день Рождества моя настоящая любовь дала мне
два голубятника-черепахи
и куропатка в грушевом дереве.
...
Стих N:
На n-й день Рождества моя истинная любовь дала мне
(Стих N-1 без первой строки)
(строка добавлена в стихе N)
Ответы
Ответ 1
Общий 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)))
Edit:
Похоже, что вопрос прошел свой путь, и сайт навязывает мне принять ответ. Насколько я вижу, этот самый короткий. Я немного боюсь того, что сделает сайт, если я приму свой ответ - возможно, награжу меня значком нарцисса или мастурбатора.
Вы не можете принимать свои собственные ответы. Справедливо. Я оставлю его открытым. Спасибо всем, кто ответил.
Ответ 2
Использование 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))
Выходы Twelth day:
For the twelfth bug of Christmas, my manager said to me
Tell them it a feature
Say it not supported
Change the documentation
Blame it on the hardware
Find a way around it
Say they need an upgrade
Reinstall the software
Ask for a dump
Run with the debugger
Try to reproduce it
Ask them how they did it and
See if they can do it again.
Ответ 3
Не мой, но интересный...
Это хорошо известный пример из 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 [email protected]'(q)-[w]*%n+r3#l,{}:\nuwloca-O;m .vpbks,fxntdCeghiry"),a+1);}
"Несмотря на то, что на первый взгляд непонятно, это законная программа на языке C, которая при компиляции и запуске будет генерировать 12 стихов" 12 дней Рождества ". Она содержит все строки, необходимые для стихотворения в закодированной форме, вложенной в код Код выполняет итерацию через 12 дней, показывая, что ей нужно.
Он не выиграет в гольф, хотя он составляет около 830 байт.
Ответ 4
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();
Ответ 5
На языке программирования D, используя оператор switch fall-through:
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");
}
}
}
Ответ 6
Bash:
wget -qO- http://tinyurl.com/a3xw8b
Я использовал вывод frizzer.myopenid.com реализации CLisp как начало.
Ответ 7
В С++ вы
std::cout << boost::12_days_of_christmas;
Ответ 8
С#, 421 Символы
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 [email protected] swans [email protected] maids [email protected] ladies [email protected] lords [email protected] pipers [email protected] drummers [email protected]".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 [email protected]"
.Replace("@","ing,|")
.Split('|')[i]+t);
Ответ 9
PHP: 375 символов
$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;}
Ответ 10
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
Ответ 11
Linq для объектов, в 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));
Ответ 12
Perl.
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 символов)
Я хотел сделать это немного красивее и выразительно, но это проблема гольфа.
Этот стиль несколько нарушает правильные стандарты кодирования. Но этот гольф для вас.
Lingua:: EN:: Number
Здесь менее компактная версия с менее хитрыми трюками.
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";
}
Ответ 13
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 символа
Ответ 14
LilyPond, 340 символов (короче Common Lisp)
"Это сезон! (И довольно уместно, учитывая, что LilyPond в первую очередь используется для набора музыки... Можно легко адаптировать этот код для создания ноты для песни в дополнение к только лирике.)
Адаптировано из решения для физнера.
#(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 символе точно соответствует физцеру, но на три байта короче:
#(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))
Ответ 15
рубин. Я думаю, что это довольно красноречиво (тяжелая работа на одной линии):
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(", ")
}
Ответ 16
perl -MTemplate -e 'Template->new()->process("12dayxmas.tt")'
12dayxmas.tt
[%
list = [
{ day => 'first', item => 'A partridge in a pear tree.'},
{ day => 'second', item => 'Two turtle doves, and '},
{ day => 'third', item => 'Three french hens, '},
{ day => 'fourth', item => 'Four calling birds, '},
{ day => 'fifth', item => 'Five gold rings, '},
{ day => 'sixth', item => 'Six geese a-laying, '},
{ day => 'seventh', item => 'Seven swans a-swimming, '},
{ day => 'eighth', item => 'Eight maids a-milking, '},
{ day => 'nineth', item => 'Nine ladies dancing, '},
{ day => 'tenth', item => 'Ten lords a-leaping, '},
{ day => 'eleventh', item => 'Eleven pipers piping, '},
{ day => 'twelfth', item => 'Twelve drummers drumming, '}
];
-%]
[%
FOREACH list;
present = item _ present;
-%]
On the [% day %] day of Christmas my true love gave me [% present %]
[% END %]
Ответ 17
Здесь 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");
}
Ответ 18
h
В моем готовом языке, где команда h
печатает "Hello, World!". О, подождите, вы имеете в виду, что не то, о чем мы говорим?
Ответ 19
Python (71 + 467, включая пробелы)
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)))
Ответ 20
С#:
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 символов, не считая отступов. Добавляет некоторые дополнительные символы для правильного ввода номеров. Вероятно, можно улучшить немного.
Ответ 21
С#
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);
}
Ответ 22
Я не могу победить версию Lisp, но все равно интересно.
Версия Delphi:
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 году.
Ответ 23
Рубин
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 байта с использованием UNF LF.
Ответ 24
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];
}
Ответ 25
26 байтов!..
Как следует из URL-адреса, его можно считать.. cheating:
http://github.com/dbr/so_scripts/tree/master/golf_tdoc/cheating.bash
Ответ 26
Здесь версия 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"])
Ответ 27
Другой С#
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"));
Ответ 28
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]);
}
Ответ 29
Как насчет одной строки! Это находится на С#.
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!");}
Ответ 30
С#: 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()
)
);