12 días de golfmas

13

Desafío

En cada uno de los 12 días de Navidad, emite el verso apropiado de "12 días de Navidad", de acuerdo con la fecha, de lo contrario, emite el coro de "Ojalá pudiera ser Navidad todos los días".

\nSe permiten nuevas líneas iniciales y / o finales ( ) y espacios finales. No puede leer de ninguna fuente externa.

Básicamente, lo que debe hacer es leer la fecha del sistema y emitir el verso correspondiente de los "12 días de Navidad".

12 días de navidad

Los Doce Días de Navidad es la temporada festiva cristiana, que comienza el día de Navidad (25 de diciembre) y termina el 5 de enero.

Ejemplos

Si la fecha es el 25 de diciembre (imprima el verso más corto / primero):

On the first day of Christmas 
my true love sent to me:
a Partridge in a Pear Tree

Si la fecha es el 31 de diciembre (imprima el séptimo verso):

On the seventh day of Christmas
my true love sent to me:
7 Swans a Swimming
6 Geese a Laying
5 Golden Rings
4 Calling Birds
3 French Hens
2 Turtle Doves
and a Partridge in a Pear Tree

Si la fecha es el 5 de enero (imprima el verso más largo / último / 12):

On the twelth day of Christmas
my true love sent to me:
12 Drummers Drumming
11 Pipers Piping
10 Lords a Leaping
9 Ladies Dancing
8 Maids a Milking
7 Swans a Swimming
6 Geese a Laying
5 Golden Rings
4 Calling Birds
3 French Hens
2 Turtle Doves
and a Partridge in a Pear Tree

Si la fecha no está dentro del rango del 25 de diciembre al 5 de enero inclusive:

Well I wish it could be Christmas every day
When the kids start singing and the band begins to play
Oh I wish it could be Christmas every day
So let the bells ring out for Christmas 

¡Feliz Navidad!

Decaimiento Beta
fuente
Entonces, ¿tenemos que escribir un programa que lea la fecha del sistema e imprimir en consecuencia? Sus preguntas parecen incompletas, sin especificar tantos detalles.
Optimizador
8
¿Otro desafío de compresión de texto sin formato? No es un fan.
John Dvorak el
La gente de Java no se divierte, pero intentará cumplir.
Rodolfo Dias
3
Esto no es un duplicado. Ese programa fue un simple desafío de complejidad kolmogrov: esto incluye leer la fecha y la salida en función de esa lectura.

Respuestas:

6

CJam, 557 550 530 528 522 519 bytes

et3<(;" Christmas":P;:(31b7+372%_C<{"On the ""first second third"S/"four fif six seven eigh nin ten eleven twelf"S/"th"f++@:X=" day of"P"
my true love sent to me:
""and a Partridge in a Pear Tree."a[D,2>Sm*"Turtle Dove
French Hen
Calling Bird
Golden Ring
Geese a Lay
Swans a Swimm
Maids a Milk
Ladies Danc
Lords a Leap
Pipers Pip
Drummers Drumm"N/'s4*"ing"a7*+]z+X)<W%N*X!{4>}*}{;"Well"" I wish it could be"P" every day
"++_"When the kids start singing and the band begins to play
Oh"\"So let the bells ring out for"P}?

Pruébalo aquí. Para probar diferentes fechas, reemplace et3<(;con algo como [12 25].

Probablemente todavía hay margen de mejora.

et                    "Read the current datetime as an array [year month day hour ...].":
  3<                  "Discard hours, minutes etc.";
    (;                "Discard year.";
      " Christmas":P; "Store the string in P and discard.";

:(                    "Decrement month and day.";
  31b                 "Interpret as base-31 digits. So on [12 25] we get 365 (what a coincidence).
                       On [12 31] we get 371. On [1 1] we get 0. On [1 5] we get 4.";
     7+               "Add 7.";
       372%           "Take modulo 372. Now the 12 days result in 0 to 11, others are greater.";
           _C<        "Duplicate and check if it's less than 12.";

{...}{...}?           "Run the first block for the 12 days, the second block otherwise.";

"On the 12 days:";
"On the "             "Push the string.";
"first ... third"S/   "Push first to third. Split by spaces.";
"four ... telf"S/     "Push other ordinal numbers, split by spaces.";
"th"f+                "Add th to each.";
+                     "Append to get first to twelfth.";
@:X                   "Pull day number to the top. Store in X.";
=                     "Select ordinal number.";
" day of"P            "Push ` day of Christmas`.";
"\nmy true...\n"      "Push that string, too".;
"and a Part..."a      "Push day 1 string and wrap in array.";
[                     "Remember beginning of array.";
D,2>                  "Push range [2 3 ... 12].";
Sm*                   "Append a space to each.";
"Turtle..."N/         "Push all the gifts. Split into lines.";
's4*                  "Push `ssss`.";
"ing"a7*              "Push an array with 7 copies of `ing`.";
+                     "Add the two.";
]                     "Close array, containing numbers, gifts and endings.";
z                     "Zip/transpose the array.";
+                     "Add day-1 line.";
X)                    "Push day and decrement.";
<                     "Slice off unwanted days.";
W%                    "Reverse array.";
N*                    "Join lines with line breaks.";
X!                    "Logical not of day, is 1 on day 1 and 0 on all other days.";
{4>}*                 "On day 1, remove first 4 characters (`and `).";

"On all days:";
;                     "Discard day from stack.";
"Well"                "Push the string.";
" I..."P"...day\n"    "Push the rest of the line in 3 strings.";
++_                   "Join those three into one, and duplicate.";
"When...\nOh"         "Push next line and `Oh`.";
\                     "Swap with duplicate line.";
"So ... for"P         "Push final line.";
Martin Ender
fuente
5 Golden R(ing)¿inaceptable? ¡Maldición! ¿Hay alguna forma de aplicar tanto el -ingfinal como el -s final al número 5?
Level River St el
5

Python 2, 681 676 673 670 667 bytes

import time
N=time.localtime();D,M=N.tm_mday,N.tm_mon
Q=((D<6>M<2)*(31+D)+(M>11)*D)-24
print["Well%sWhen the kids start singing and the band begins to play\nOh%sSo let the bells ring out for~"%((" I wish it could be~ every day\n",)*2),"On the %s day of~\nmy true love sent to me:\n"%("twel first second third four fif six seven eigh nin ten eleven".split()[Q%12]+"th"*(Q>3))+"\n".join("%d %s"%(i,"Turtle Doves$French Hens$Calling Birds$Golden Rings$Geese a Lay$Swans a Swimm$Maids a Milk$Ladies Danc$Lords a Leap$Pipers Pip$Drummers Drumm".split("$")[i-2]+"ing"*(i>5))for i in range(Q,1,-1))+"\nand "*(Q>1)+"a Partridge in a Pear Tree"][Q>0].replace("~"," Christmas")

Intenté competir contra CJam ... y fallé como esperaba. Tal vez si pudiera descubrir cómo zlib, pero no sé ...

(Gracias a @FryAmTheEggman por las sugerencias por chat)

Sp3000
fuente
4

¡Es grande! ¡Es grosero! Es feo! Sus...

Java: 894 887 883 882 bytes

Golfizado:

class C{public static void main(String[]a){java.util.Calendar d=java.util.Calendar.getInstance();String p="a Partridge in a Pear Tree\n",t="Well Z\nWhen the kids start singing and the band begins to play\nOh Z\nSo let the bells ring out for X".replaceAll("Z","I wish it could be X every day"),r="";String[]s=(" day of X\nMy true love gave to me:\nçfirstçsecondçthirdçfourthçfifthçsixthçseventhçeighthçninthçtenthçeleventhçtwelfthç Turtle Doves\nç French Hens\nç Calling Birds\nç Golden Rings\nç Geese a LayY\nç Swans a SwimmY\nç Maids a MilkY\nç Ladies DancY\nç Lords a LeapY\nç Pipers PipY\nç Drummers DrummY\n").replaceAll("Y","ing").split("ç");int n=d.get(d.DAY_OF_YEAR),o=(n>358)?(n-358):(n<6)?(n+7):-1,j;if(o==-1)r=t;else{r+=("On the "+s[o]+s[0]);for(j=o+11;j-->12;r+=(j-11+s[j]));r+=(o!=1)?"and "+p:p;}System.out.print(r.replaceAll("X","Christmas"));}}

Sin golf:

class C {

    public static void main(String[] a) {
        java.util.Calendar d = java.util.Calendar.getInstance();
        String p = "a Partridge in a Pear Tree\n", t = "Well Z\nWhen the kids start singing and the band begins to play\nOh Z\nSo let the bells ring out for X".replaceAll("Z", "I wish it could be X every day"), r = "";
        String[] s = (" day of X\nMy true love gave to me:\nçfirstçsecondçthirdçfourthçfifthçsixthçseventhçeighthçninthçtenthçeleventhçtwelfthç Turtle Doves\nç French Hens\nç Calling Birds\nç Golden Rings\nç Geese a LayY\nç Swans a SwimmY\nç Maids a MilkY\nç Ladies DancY\nç Lords a LeapY\nç Pipers PipY\nç Drummers DrummY\n").replaceAll("Y", "ing").split("ç");
        int n = d.get(d.DAY_OF_YEAR), o = (n > 358) ? (n - 358) : (n < 6) ? (n + 7) : -1, j;
        if (o == -1) {
            r = t;
        } else {
            r += ("On the " + s[o] + s[0]);
            for (j = o + 11; j-- > 12; r += (j - 11 + s[j]));
            r += (o != 1) ? "and " + p : p;
        }
        System.out.print(r.replaceAll("X", "Christmas"));
    }
}

Después de jugar mucho y ganar 14 bytes, creo que dejaré de jugar con él.

Y sí, sé que, en los años bisiestos, mi idea puede tener un pequeño problema, pero ... fue mi forma de cortar algunos bytes del código. Oh bien.

Rodolfo Dias
fuente
1
Eres demasiado duro con Java ...
Beta Decay
1
@BetaDecay Quizás, lo estoy. Y tal vez debería intentar jugar al golf en algo que no sea Java: P
Rodolfo Dias
¿Crees que puedes poner resaltado de sintaxis de código en tu código? Prefiero código colorido sobre código blanco y negro. Me ayuda a distraerme del hecho de que todo el código representa el código de la máquina de alguna forma.
TheNumberOne
@TheBestOne con mucho gusto lo haría ... si descubriera cómo activarlo.
Rodolfo Dias
3
Pruebe <!-- language: lang-java -->antes de un bloque de código. Úselo <!-- language-all: lang-java -->para todos los bloques de código en su documento. Para obtener más información, consulte codegolf.stackexchange.com/editing-help
TheNumberOne el
1

Erlang, 748 bytes

Una versión limpia de 7 bits sin gzip-9 tiene 748 bytes:

f()->[maps:get(C,#{$N=>"ing",$x=>10,$q=>"th",$z=>" Christmas"},C)||C<-s(t(calendar:local_time()))].
t({{_,1,D},_})->D+7;t({{_,12,D},_})->D-24;t(_)->1.
s(X)when X<1;X>12->L=" I wish it could bez every dayx","Well"++L++"When qe kids start sNN and qe band begins to playxOh"++L++"So let qe bells rN out forz";
s(I)->"On qe "++element(I,{"first","second","qird","fourq","fifq","sixq","sevenq","eighq","ninq","tenq","elevenq","twelq"})++" day ofzxmy true love sent to me:x"++r(I).
r(0)->"";r(I)->element(I,{"a Partridge in a Pear Tree","2 Turtle Dovesxand ","3 French Hensx","4 CallN Birdsx","5 Golden RNsx","6 Geese a LayNx","7 Swans a SwimmNx","8 Maids a MilkNx","9 Ladies DancNx","10 Lords a LeapNx","11 Pipers PipNx","12 Drummers DrummNx"})++r(I-1).

Una solución gzip-9 + base64 tiene una longitud de 750 bytes:

f()->s(t(calendar:local_time())).
t({{_,1,D},_})->D+8;t({{_,12,D},_})->D-23;t(_)->1.
s(I)->try element(I,binary_to_term(base64:decode("g1AAAAkQeNrdlF9OGzEQxsNrJF44wXeEhtK/jyUqRQoCARLPTnYSW+u1oxlv0jz3BL1C71D1Cj1C79BDtOOQhQqpCKv0D5VW8u5a883vmxnbbte9jxfkPQ6xdGLhEiax9RXGhH3LTlJjBLQgXqEyq/6FpYBkCbWrBJIMJ4gLM31gQrXeGueXMek/QYqYe407tnfNcBbhKV0KKZiAs3ZsE6aRryPq3unxJcnUsaQcijj9QbHfrJC4Jfi4IAiFlGEaetk3OFFsdtWM4AL0kwzjnInqHm1EhSZRXdxU/bnoLs5bTp4w1B3p5xLcloc3eZJ1XJLmMV4zhYnFGwpSmvRdV7GoUbYg6x72jfe5D68UV36N4v1V36ZFEE9wEH2l43eqIHK/TB+6tru3RUxPcUAkpGIjs1KW3wr56Wo2F4pQgvkMZ0ujp9Ho6pomg/5R8s8bcnIzWwT+HEcmXzQGR87XGfNvW/mysRJcWQteKFzlSDA0YZIh/z1rX7s7qXC6Bo8wiry2MiIzz5gPwO23biZ98XEaDHDi5sSSl8z5ICuwtdP1e0m+zP8uhtw2Ta7A+mVdg/+hKN8Bkz8M5Q==")))catch _:_->s(1)end.

Una función Erlang codificada en UTF-8 tiene 421 caracteres (935 bytes).

f()->s(t(calendar:local_time())).
t({{_,1,D},_})->D+8;t({{_,12,D},_})->D-23;t(_)->1.
s(I)->try element(I,binary_to_term(<<<<(C-$㐀):14>>||C<-"哔㐀㐤䑸檷䵅焸伱㠱怶悑券摝汈佊玏㵊塐專㔒染孡㵯徵峆䫽㳳欄捐拵㟔㸽䒻焄䋓垐啂庐嚯栏奕挮浫柍濦斝憻䮽埅牃栺整䲸䔢仇椕斡㯜愹䙣㔭㘅溄暫玡乘㖐㶵廁㴠撞㰋䃟䨄㻗刚淥朞壽㖊娞泓拙母倅戒奴㸩娠㼷䶰䞦填显彻己㵲克㪐傊䈿䠛㭾悐戉压咀㲅夘䖧彤欸䡛㭭䨳吂焤擎䉲㷪㮛䡈䢙䕝欕䏛宠拎䫓巣㝐凩淄應东歹墝䧉㾘敞䃡䲜䡬㹒媽㧕勆屑憈䊱濚䇷扃滱䕝犍沿䥝犙㤐䟜㔇檗坷庈㬫焰厺憮潴䤱䍱䐉㹆㲎杒妷撯宥帶㧢夈㿤䁧䛨湽㮣庚㶠珥㯋䌛傜圵怓爜䗉姳䐙㯎槆匶煯液恄姅堭刨䬹䢃㓑喒㱿柖慾漻幜㾠丼撊挭圢㳏䎘㟰䋛冸婽灜䖠旃囦攤嵼柤含怭儿䧭㶾朿曨佰橍徰䎦䥶㟿届䇰㩌猌浀㐀㐀㐀">>))catch _:_->s(1)end.
Paul Guyot
fuente
0

Javascript (665)

__=new Date("12/31");M=_.getMonth();D=_.getDate();d=M?(M==11)*(D-24):D+7;if(!d||d>12)s="Well K\nWhen the kids start singing and the bands begin to play\nOh K\nSo let the bells ring out for Christmas".replace(/K/g,"I wish it could be Christmas every day");else{for(s="On the "+"0first0second0third0fourth0fifth0sixth0seventh0eight0ninth0tenth0elevent0twelth".split(0)[d]+" day of Chirstmas\nmy true love sent to me:";--d;)s+="\n"+(d+1)+" "+"0Turtle Doves0French Hens0CallZ Birds0Golden RZs0Geese a LayZ0Swans a SwimmZ0Maids a MilkZ0Ladies DancZ0Lords a LeapZ0Pipers PipZ0Drummers DrummZ".split(0)[d].replace("Z","ing");s+="\n"+(D!=25?"and ":"")+"a Partridge in a Pear Tree"}alert(s)

Puede probarlo agregando paréntesis al primer new Datecambio, es decir:

_=new Date;M=_...

a

_=new Date("1/5");M=_...

Aquí está embellecido:

_ = new Date("12/31");
M = _.getMonth();
D = _.getDate();
d = M ? (M == 11) * (D - 24) : D + 7;
if (!d || d > 12) s = "Well K\nWhen the kids start singing and the bands begin to play\nOh K\nSo let the bells ring out for Christmas".replace(/K/g, "I wish it could be Christmas every day");
else {
    for (s = "On the " + "0first0second0third0fourth0fifth0sixth0seventh0eight0ninth0tenth0elevent0twelth".split(0)[d] + " day of Chirstmas\nmy true love sent to me:"; --d;) s += "\n" + (d + 1) + " " + "0Turtle Doves0French Hens0CallZ Birds0Golden RZs0Geese a LayZ0Swans a SwimmZ0Maids a MilkZ0Ladies DancZ0Lords a LeapZ0Pipers PipZ0Drummers DrummZ".split(0)[d].replace("Z", "ing");
    s += "\n" + (D != 25 ? "and " : "") + "a Partridge in a Pear Tree"
}
alert(s)
soktinpk
fuente
0

C # en Linqpad - 866 bytes

Bueno, al menos venció a Java;) Los años bisiestos se manejan dentro del código.

Sin formato:

void Main(){var w=DateTime.Now;int y=w.Year%4,d=w.DayOfYear,c=0,p=0;string t="Well Z\nWhen the kids start singing and the band begins to play\nOh Z\nSo let the bells ring out for X".Replace("Z","I wish it could be X every day").Replace("X","Christmas"),o="On the ",x=" day of Christmas\nmy true love sent to me:\n";string[]z={"first","second","third","forth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelth"},b={"a Partridge in a Pear Tree\n","and ","2 Turtle Doves\n","3 French Hens\n","4 Calling Birds\n","5 Golden Rings\n","6 Geese a Laying\n","7 Swans a Swimming\n","8 Maids a Milking\n","9 Ladies Dancing\n","10 Lords a Leaping\n","11 Pipers Piping\n","12 Drummers Drumming\n"};if(y==0){p=1;}if(d>358){c=d-358-p;}else if(d<6){c=d+7;}else{t.Dump();return;}if(c==1){o+=z[0]+x+b[0];}else{o+=z[c-1]+x;for(int i=c;i>=0;i--){o+=b[i];}}o.Dump();}

Formateado:

void Main()
{
var w=DateTime.Now;
int y=w.Year%4,d=w.DayOfYear,c=0,p=0;
string t="Well Z\nWhen the kids start singing and the band begins to play\nOh Z\nSo let the bells ring out for X".Replace("Z","I wish it could be X every day").Replace("X","Christmas"),
o="On the ",x=" day of Christmas\nmy true love sent to me:\n";

string[]z={"first","second","third","forth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelth"},

b={"a Partridge in a Pear Tree\n","and ","2 Turtle Doves\n","3 French Hens\n","4 Calling Birds\n","5 Golden Rings\n","6 Geese a Laying\n",
"7 Swans a Swimming\n","8 Maids a Milking\n","9 Ladies Dancing\n","10 Lords a Leaping\n","11 Pipers Piping\n","12 Drummers Drumming\n"};

if(y==0)
{
    p=1;
}

if(d>358)
{
    c=d-358-p;
}
else if(d<6)
{
    c=d+7;
}
else
{
    t.Dump();
    return;
}

if(c==1)
{
    o+=z[0]+x+b[0];
}
else
{
    o+=z[c-1]+x;
    for(int i=c;i>=0;i--)
    {
        o+=b[i];
    }
}
o.Dump();
}
tsavinho
fuente
¿Cómo maneja esto los años bisiestos?
Beta Decay
@BetaDecay Al principio, uso un módulo en el año int y=w.Year%4. Si el módulo yes 0, agrego uno ccon la ayuda de p.
tsavinho