Эта проблема возникла для меня после установки модуля под Podfile и pod install
. Попробовав кучу разных исправлений, я, наконец, просто импортировал Pod вручную (перетащив необходимые файлы в мой проект), и это решило проблему.
Язык Common 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)))
Редактирование:
похоже, что вопрос выполнил свой курс, и сайт ворчит меня для принятия ответа. Насколько я вижу, этот является самым коротким. Я немного боюсь того, что сделает сайт, если я признаю, что мой собственный ответ - вероятно, награждает меня значком Самовлюбленного человека или Онаниста.
Вы не можете принять свои собственные ответы. Достаточно ярмарка. Я оставлю его открытым. Благодаря всем, кто ответил.
Вот несколько разных способов для 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())));
не очень приятно. но его мало. :)
Наткнулся на эту тему, и это выглядело так весело, что я не смог устоять - вот еще одна версия 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>');
}
})();
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);
}
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
В C ++ вы бы
std::cout << boost::12_days_of_christmas;
$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;}
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 символа
Рубин. Я думаю, что это довольно кратко (тяжелая работа все в одной строке):
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(", ")
}
Вот версия 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>")
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 символа, не считая отступов. Добавляет некоторые дополнительные символы в правильном расширении номеров. Хотя, возможно, его можно немного улучшить.
Objective-C / Какао
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]);
}
Не мое, но интересное ...
Это хорошо известный пример из http://en.wikipedia.org/wiki/Obfuscated_code (автор: Джеймс О. Коплиен):
#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);}
«Хотя На первый взгляд, неразборчиво, это легальная программа на Си, которая при компиляции и запуске сгенерирует 12 стихов «12 дней Рождества» и содержит все строки, необходимые для стихотворения, в зашифрованном виде, вставленном в код. 12 дней показывают, что ему нужно ».
Это не выиграет гольф, хотя, это около 830 байтов.
Используя 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))
Результаты двенадцатого дня:
For the twelfth bug of Christmas, my manager said to me Tell them it's a feature Say it's 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.
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.");
Java, основанная на втором решении Эско:
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 символов (не считая отступов и переносов). И этот полностью работает и не печатает каждый стих в одной строке. Выходные данные:
В первый день Рождества моя настоящая любовь подарила мне:
куропатку в грушевом дереве.Во второй день Рождества моя настоящая любовь подарила мне:
двух горлиц и
куропатку в грушевом дереве.В третий день Рождества моя настоящая любовь подарила мне:
три французских курицы,
две горлицы и
куропатку в грушевом дереве....
РЕДАКТИРОВАТЬ: Немного улучшенная версия, основанная на идее Балабастера о замене общей строки одним символом:
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 символов (хотя я добавил запятую) что я пропустил раньше).
Несмотря на то, что это закончилось какое-то время, я все еще хотел бы испытать эти вызовы игры в гольф кода ...
Лучшее, что я мог сделать с 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
Как насчет одной строки! Это в 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#
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"));
Общее количество Ruby
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.
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)}
assert_raise(Exception() { whatever.merge })
, т.е. это ищет метод, названный Exception
, который называют с данным блоком. Добавление parentheses resolves та неоднозначность. (Уже зафиксированный ответ)
– Daniel Rikowski
20 October 2012 в 15:08
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 с помощью оператора переключения провалитесь:
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");
}
}
}
meshgrid
и сериализация 2-х векторов, но никогда не рассматривал использование их таким образом.
– Brendan
17 September 2011 в 03:00
Вот версия 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"])
Не видел никого для Java (который не известен его минимальным синтаксисом btw), поэтому сначала, я сделал это
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 символами без пробелов, если сигнатура метода переключается на надлежащее основное () тогда, это 596.
, Если бы у меня был интерес сделать третью версию, я попробовал бы перечислимый прием также.
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);
Bash:
wget -qO- http://tinyurl.com/a3xw8b
я использовал вывод frizzer.myopenid.com реализация CLisp как запуск.
423 байта с Языком:: EN:: Число:
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);
Или 480 байтов в жемчуге, не используя Язык:: EN:: Числа:
@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
Это должно смочь быть уменьшенным далее, так как числа являются очень повторяющимися.