Code Golf: Imprimez toute la chanson "12 Days of Christmas" dans le moins de lignes de code

Imprimer tous les 12 versets de la populaire chanson de vacances .

12 versets je veux dire la répétition de chaque ligne est chanté dans la chanson, c'est à dire

Verset Un: Le premier jour de Noël, mon véritable amour m'a donné une perdrix dans un poirier.

Verset Deux Le deuxième jour de Noël, mon véritable amour m'a donné deux tourterelles et une perdrix dans un poirier.

...

Verset N: Le nième jour de Noël mon véritable amour m'a donné (Verset n-1 sans la première ligne) (ligne ajoutée au verset N)

25
demandé sur Doug T. 2008-12-20 18:20:58

30 réponses

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."))))

Modifier:

Ci-dessus est de 412 caractères si vous supprimez les espaces.

Celui-ci:

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

Est de 344 caractères si vous supprimez les espaces et ~ les nouvelles lignes entre guillemets dans la chaîne de format:

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

Modifier:

Il semble que la question ait suivi son cours, et le site me harcèle pour accepter une réponse. Pour autant que je puisse voir, celui-ci est le plus court. J'ai un peu peur de ce que le site fera si j'accepte ma propre réponse - probablement me décerner un badge narcissique ou Masturbateur.

Vous ne pouvez pas accepter vos propres réponses. Juste assez. Je vais le laisser ouvert. Merci à tous ceux qui ont répondu.

44
répondu fizzer 2008-12-29 19:56:29

En Utilisant 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))

Sorties douze jours:

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.
37
répondu Juliet 2008-12-20 17:15:50

Pas le mien, mais intéressant...

Ceci est un exemple bien connu de http://en.wikipedia.org/wiki/Obfuscated_code (auteur: 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);}

" bien qu'inintelligible à première vue, c'est un programme C légal qui, une fois compilé et exécuté, générera les 12 versets des 12 jours de Noël. Il contient toutes les chaînes requises pour le poème sous une forme codée insérée dans le code. Le code itère à travers les jours 12 affichant ce dont il a besoin de."

Il ne gagnera pas le golf, il est d'environ 830 octets.

27
répondu BoltBait 2008-12-20 17:08:57
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();
15
répondu annakata 2008-12-20 19:25:00

Dans le langage de programmation D, en utilisant l'instruction 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");
        }
    }
}
15
répondu dsimcha 2008-12-21 16:02:01

Bash:

wget -qO- http://tinyurl.com/a3xw8b

J'ai utilisé la sortie de frizzer.myopenid.com l'implémentation CLisp de comme début.

14
répondu strager 2017-05-23 12:01:24

En C++ vous

std::cout << boost::12_days_of_christmas;
14
répondu Jasper Bekkers 2008-12-22 23:39:42

C#, 421 Caractères

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

Version espacée:

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);
11
répondu Mindaugas Mozūras 2009-12-29 13:18:42

PHP: 375 caractères

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

Modifier: mise à jour de la version exécutable (377) caractères

<?$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;}
9
répondu Jasper Bekkers 2008-12-22 22:29:28

Linq aux objets, en 580 caractères (sans espace)

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));
7
répondu Daniel Earwicker 2008-12-21 13:20:03

VB.Net - 530 Caractères (pas d'espaces), 634 (espaces)

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
7
répondu jrcs3 2010-08-04 02:30:39

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 Caractères )

, je voulais le faire un peu plus agréable et expressif, mais c'est un golf défi.

Ce style viole quelque peu les normes de codage appropriées. Mais c'est du golf pour toi.

Lingua::FR::Number

Voici la version moins compacte avec des astuces moins sournoises.

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";
}
6
répondu Kent Fredric 2008-12-20 18:31:07
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 caractères

6
répondu bd808 2008-12-20 23:14:13

LilyPond, 340 caractères (plus court que Common Lisp)

'Tis la saison! (Et plutôt approprié, étant donné que LilyPond est principalement utilisé pour composer de la musique... On peut facilement adapter ce code pour produire des partitions pour la chanson en plus des paroles.)

Adapté de la solution de 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))

Utilisation: $ lilypond thisfile.ly

Cette version, en 341 caractères, correspond exactement à la sortie de fizzer, mais est trois octets plus court :

#(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))
6
répondu KirarinSnow 2009-12-15 20:15:56

Ruby. Je pense que c'est assez concis (le travail acharné est tout sur une ligne):

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(", ")
}
5
répondu DanSingerman 2008-12-20 17:42:30

Utilisation De Template Toolkit

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 %]
4
répondu Brad Gilbert 2008-12-20 18:00:42

Voici une solution 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");
}
4
répondu jmucchiello 2008-12-20 18:56:38
h

Dans mon langage inventé où la commande h imprime " Hello, World!". Attends, tu veux dire que ce n'est pas de ça qu'on parle?

4
répondu dancavallaro 2008-12-20 19:18:16

Python (71 + 467 y compris les espaces)

import sys
sys.path += ["TDOC.zip"]
import TDOC
TDOC.print_verse()

Où TDOC.zip (467 octets) contient 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)))
4
répondu jfs 2008-12-20 22:32:21

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 caractères, sans compter l'indentation. Ajoute quelques caractères supplémentaires pour obtenir les extensions de nombre à droite. Peut probablement être amélioré sur un peu, cependant.

3
répondu Ian Varley 2008-12-20 16:37:38

Je ne peux pas battre la version Lisp, mais c'est toujours amusant.

La version 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;

Au fait, pour vous tous, Joyeuses Fêtes et excellente programmation en 2009.

3
répondu Toon Krijthe 2008-12-20 16:48:31

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];
}
3
répondu Chris Bartow 2008-12-20 19:41:05

26 octets!..

Comme l'indique L'URL, il peut être considéré.. tricherie:

Http://github.com/dbr/so_scripts/tree/master/golf_tdoc/cheating.bash

3
répondu dbr 2008-12-21 08:57:55

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

Total: 593 octets utilisant UNIX LF.

3
répondu Lucas Jones 2008-12-31 16:16:38

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);
     }
3
répondu cgreeno 2010-06-10 17:21:25

Voici une version 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"]

Il arrive à 527 caractères. Puisque sans un bon espacement c'est plutôt incompréhensible, voici une version plus étalée:

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"])
2
répondu Gracenotes 2008-12-21 02:35:57

Objectif - C / Cacao

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]);
}
2
répondu Ryan Townshend 2008-12-21 03:08:16

Un Autre 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"));

Emprunté fortement aux réponses précédentes (hey, réutilisation du code) tout en ajoutant des économies supplémentaires.

481 caractères une fois que vous supprimez les espaces inutiles:

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")); 
2
répondu Cameron MacFarland 2008-12-21 07:30:17

Que diriez-vous d'une ligne! C'est en 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!");}
2
répondu The Alpha Nerd 2008-12-21 16:27:57

Voici une version erlang (~586 caractères):

-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.
2
répondu cheng81 2008-12-23 12:26:36