Bu yıllık bir görev, tamam


22

1≤n≤365 bir sayı verildiğinde, yılın ertesi gününü "Gün-Sayı Ayı" biçiminde verin. Örneğin, 1 verildiğinde, "1" olmadan "1 Ocak" yazmalısınız.

Gregoryen takvimi kullanılacak ve program artık yılları hesaba katmamalı, bu nedenle programınız hiçbir zaman "29 Şubat" yazmamalı. Herhangi bir yöntem, daha önce belirtilen "Gün-Sayı Ayı" biçimini izlediği sürece kullanılabilir. Programınız ayrıca sıralı olarak doğru çıktı vermelidir, yani her zaman 1., 2., 3. çıktıları göstermelidir, sırasıyla 1, 2 veya 3, herhangi bir giriş için gün sayısı olmalıdır. Önde gelen boşluklara veya diğer girintilere izin verilir.

Bu kod golf, yani karakterlerin en kısa çözümü kazanır.

Test durumları:

1 gives 1st January
2 gives 2nd January
3 gives 3rd January
365 gives 31st December
60 gives 1st March
11 gives 11th January

4
Ayrıca, 365 sayıdaki bir hatayı zorlamanız gerekiyor mu? Program bunun geçersiz bir girdi olduğunu varsayabilir ve bununla başa çıkması gerekmeyebilir mi?
Rɪᴋᴇʀ

5
Herkesin anadili İngilizce olmadığı için, o gün 11, 12 ve 13 sayılarını "th", "1" ile biten rakamları "st", "2" "nd", "3" eklemek isteyebilirsiniz. "rd" yi ve diğerlerini "th" al.
Adám

9
Whoa, cevapları bu kadar çabuk kabul etme. Özellikle yanlış cevaplar!
Adám

6
En azından eklemek gerekir 11(11 inci Ocak) ve 21(21 st testi davalara Ocak).
Arnauld

1
Test senaryolarını düzenlerken, belki de test senaryosu formatınızın tam olarak ne olduğunu belirtin. Birkaç cevaplayıcı, bunun 123=gerekli çıktının bir parçası olduğunu düşündü . Ya da sadece şöyle bir şey okumak için test durumlarınızı düzenleyin: 365gives31st December
Adám

Yanıtlar:


9

PHP ,38 40 30 28 bayt

<?=date("jS F",86399*$argn);

Çevrimiçi deneyin!

php -nFGirişi ile çalıştırın STDIN. Örnek (yukarıdaki betiğin adı y.php):

$ echo 1|php -nF y.php
1st January
$ echo 2| php -nF y.php
2nd January
$ echo 3| php -nF y.php
3rd January
$ echo 11|php -nF y.php
11th January
$ echo 21|php -nF y.php
21st January
$ echo 60|php -nF y.php
1st March
$ echo 365|php -nF y.php
31st December

açıklama

day number * number of seconds per day(86400) ile çarparak 1970'de istenen gün için (uygun bir artık yıl değil) bir dönem zaman damgası oluşturun . Bununla birlikte, bu bir gün daha yüksek bir verim verecek, bunun yerine number of seconds in a day - 1(86399) ile çarparak giriş numaraları aralığı için (1≤365) her doğru günün sonunun zaman damgası ile sonuçlanacaktır. Ardından çıktı için PHP'nin yerleşik tarih formatını kullanın.


neden -ngerekli?
Ven,

@Ven her durumda olmayabilir, ancak yerel php.ini dosyasında tutarsız davranış yaratabilecek ayarları devre dışı bırakır.
640KB

6

Jelly ,  79 78  77 bayt

-1 bir hatayı düzeltmek :) (indeks bulmak için önceden devredilmemeli, sonradan geri göndermeliyiz, fakat sonra baştan ziyade kuyruğa girebiliriz)
-1 yansıma kullanarak - ( )⁽©ṅB+30_2¦2⁽0ṗb4+28m0

⁽0ṗb4+28m0SRṁRƲœiµṪȮ%30%20«4ị“nḄƲf⁷»s3¤Ṗ,ị“£ṢtẒ⁽ẹ½MḊxɲȧėAṅ ɓaṾ¥D¹ṀẏD8÷ṬØ»Ḳ¤$K

Sonucu basan tam bir program

Çevrimiçi deneyin!

Nasıl?

bunu daha sonra güncelleyecek ...

⁽©ṅB+30_2¦2SRṁRƲZœiµḢȮ%30%20«4ị“nḄƲf⁷»s3¤Ṗ,ị“...»Ḳ¤$K - Main Link: integer, n
⁽©ṅB+30_2¦2SRṁRƲZœi - f(n) to get list of integers, [day, month]
⁽©ṅ                 - compressed literal 2741
   B                - to a list of binary digits -> [ 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1]
    +30             - add thirty                    [31,30,31,30,31,30,31,31,30,31,30,31]
         ¦          - sparse application...
        2           - ...to indices: [2]
       _  2         - ...action: subtract two       [31,28,31,30,31,30,31,31,30,31,30,31]
               Ʋ    - last four links as a monad - i.e. f(x):
           S        -   sum x                       365
            R       -   range                       [1..365]
              R     -   range x (vectorises)        [[1..31],[1..28],...]
             ṁ      -   mould like                  [[1..31],[32..59],...]
                Z   - transpose                     [[1,32,...],[2,33,...],...]
                 œi - 1st multi-dimensional index of n  -> [day, month]

µḢȮ%30%20«4ị“nḄƲf⁷»s3¤Ṗ,ị“...»Ḳ¤$K - given [day, month] format and print
µ                                  - start a new monadic chain - i.e. f(x=[day, month])
 Ḣ                                 - head -- get the day leaving x as [month])
  Ȯ                                - print it (with no newline) and yield it
   %30                             - modulo by thirty
      %20                          - modulo by twenty
         «4                        - minimum of that and four
                     ¤             - nilad followed by link(s) as a nilad:
            “nḄƲf⁷»                -   dictionary words "standard"+" the" = "standard the"
                   s3              -   split into threes = ["sta","nda","rd ","the"]
           ị                       - index into
                      Ṗ            - remove rightmost character
                               ¤   - nilad followed by link(s) as a nilad:
                         “...»     -   dictionary words "January"+" February"+...
                              Ḳ    -   split at spaces = ["January","February",...]
                        ị          - index into (vectorises across [month])
                       ,           - pair                  e.g. ["th", ["February"]]
                                K  - join with spaces           ["th ", "February"]
                                   - print (implicitly smashes)   th February

4
"Standart" "numarası şaşırtıcı.
Ven

@Ven'le aynı fikirdeyim ! Ayrıca, 05AB1E cevabımda"thstndrd" 2 ( .•oθ2(w•2ô) boyutundaki parçalara bölünmüş sıkıştırılmış string ile karşılaştırıldığında bir bayt kaydetti , bu yüzden teşekkürler. :)
Kevin Cruijssen

1
Bu şimdiye kadar gördüğüm en uzun Jelly programlarından biri olmalı.
JAD

6

C # (Visual C # Etkileşimli Derleyici) , 115 113 109 98 bayt

g=>$"{f=(g=p.AddDays(g-1)).Day}{"tsnr"[f=f%30%20<4?f%10:0]}{"htdd"[f]} {g:MMMM}";DateTime p;int f;

9 byte'ı kaydettiği için @someone'ye teşekkürler

Çevrimiçi deneyin!


1
@KevinCruijssen Modülleri düzene soktum, şimdi düzeltilmesi gerekiyor.
Cehalet'in Uygulanması

.code.tio(2,22): error CS0165: Use of unassigned local variable 'p'Yapısal şeyin işe yaramadığı anlaşılıyor.
JAD

var g=new DateTime().AddDays(n-1)olsa çalışır
JAD

Benim tarafımdan @JAD hatası düzeltildi
Cehalet


5

Python 3.8 (yayın öncesi) , 112 bayt

lambda x:str(d:=(t:=gmtime(x*86399)).tm_mday)+'tsnrhtdd'[d%5*(d%30%20<4)::4]+strftime(' %B',t)
from time import*

Çevrimiçi deneyin!

Garip bir şekilde, parantez içerisinde olmak zorunda değilim d:=(t:=gmtime(~-x*86400), çünkü tercüman yalnızca ()atama ifadesi etrafında karakter olup olmadığını denetler , ifadenin parantez içinde olmadığını kontrol eder.

-2 gwaugh sayesinde .
-5 Xnor'a teşekkürler .


5

Perl 6 , 166 161 bayt

{~(.day~(<th st nd rd>[.day%30%20]||'th'),<January February March April May June July August September October November December>[.month-1])}o*+Date.new(1,1,1)-1

Çevrimiçi deneyin!

Alanın çoğunu kaplayan tüm ay adlarını kodlar. Dostum, Perl 6 gerçekten uygun bir tarih formatlayıcısına ihtiyaç duyuyor.


4

Hack, 115 59 39 bayt

$x==>date("jS F",mktime(0,0,0,1,$x));

Golf yaparken @gwaugh benimkiyle aynı çözüme ulaştığından, bunun yerine Hack'i gönderiyorum :).


Vay, harika beyinler aynı şekilde düşünüyor. :) +1 size efendim!
640KB

@gwaugh haha, sadece bir üst seviye program yapabileceğimi bilmiyordum. Ben de onu en üst seviye yapmak için düzenleyeceğim ve daha iyi bir skor elde etmenin bir yolunu bulacağım e ;-)
Ven

1
@gwaugh Benimki Hack yaptım.
Ven,

1
Muhtemelen mktime()aramanız için artık olmayan bir yıl parametresi belirtmek isteyeceksiniz, aksi takdirde artık yılda bir çalıştırıldığında yanlış çıktı döndürecektir. (cevabımı yapmak zorunda kaldı).
640KB

4

JavaScript (ES6),  117  113 bayt

@Tsh sayesinde 4 bayt kaydedildi

d=>(n=(d=new Date(1,0,d)).getDate())+([,'st','nd','rd'][n%30%20]||'th')+' '+d.toLocaleString('en',{month:'long'})

Çevrimiçi deneyin!

Yorumlananlar

d =>                     // d = input day
  ( n =                  //
    ( d =                // convert d to
      new Date(1, 0, d)  //   a Date object for the non leap year 1901
    ).getDate()          // save the corresponding day of month into n
  ) + (                  //
    [, 'st', 'nd', 'rd'] // ordinal suffixes
    [n % 30 % 20]        // map { 1, 2, 3, 21, 22, 23, 31 } to { 'st', 'nd', 'rd' }
    || 'th'              // or use 'th' for everything else
  ) + ' ' +              // append a space
  d.toLocaleString(      // convert d to ...
    'en',                // ... the English ...
    { month: 'long' }    // ... month name
  )                      //

Tarihi yerleşik olmayan, 188 bayt

f=(d,m=0)=>d>(k=31-(1115212>>m*2&3))?f(d-k,m+1):d+([,'st','nd','rd'][d%30%20]||'th')+' '+`JanuaryFebruaryMarchAprilMayJuneJulyAugustSeptemberOctoberNovemberDecember`.match(/.[a-z]*/g)[m]

Çevrimiçi deneyin!


Her ayın 11, 12, 13'ü için başarısız oluyor
Süresi dolmuş veriler

1
@ExpiredData Bunu bildirdiğiniz için teşekkür ederiz. Şimdi düzeltildi.
Arnauld

Yorumumu yoksay, bir ID10T hatası yaptım.
asgallant

Düğümlerin dil etiketlerini nasıl işlediğinden emin değilim, ancak kullanımı kullanmak gibi 0işe yarayacak gibi görünüyor "en". Ve toLocaleString4 bayt kurtarmak için değişiyor . 110 bayt
tsh

@tsh toLocaleStringTanınmayan bir dize veya sayısal bir değer iletildiğinde sistem varsayılan ayarlarını kullanıyor gibi görünüyor . Yani, herhangi bir şey olabilir. Bu parametre temel olarak bir TIO örneğinde etkisizdir, çünkü yine de sadece İngilizce yerel ayarlar kuruludur .
Arnauld,

4

Smalltalk, 126 bayt

d:=Date year:1day:n.k:=m:=d dayOfMonth.10<k&(k<14)and:[k:=0].o:={#st.#nd.#rd}at:k\\10ifAbsent:#th.m asString,o,' ',d monthName

1
Smalltalk'ı tanımıyorum ama bu doğru 11th,12th,13thmu? Eğer doğru okursam, tamsayıyı 10'a bölersiniz, ancak bu, bunun 11st,12nd,13rdfarkında değilken koddaki başka bir şey düzelmezse sonuçlanacağı anlamına gelir .
Kevin Cruijssen

@KevinCruijssen Haklısın. Buna dikkatimi çektiğin için teşekkür ederim. Bunu düzeltmek için biraz daha bayt harcamam gerekecek.
Leandro Caniglia

1
@KevinCruijssen, Tamam. Tekrar teşekkürler.
Leandro Caniglia

3

C # (Visual C # Etkileşimli Derleyici) , 141 139 133 124 122 bayt

a=>{var d=s.AddDays(a-1);int x=d.Day,m=x%30%20;return x+"thstndrd".Substring(m<4?m*2:0,2)+d.ToString(" MMMM");};DateTime s

11,12,13'inci 4 bayttan tasarruf ettirmeyi daha hızlı kaldırma yöntemi için Arnauld sayesinde

Çevrimiçi deneyin!


C # 8 kullanarak, bu azaltılabilir: a=>{var d=s.AddDays(a-1);int x=d.Day,m=x%30%20;return x+"thstndrd"[(m<4?m*2:0)..2]+$" {d:MMMM}";};DateTime s Etkileşimli derleyici şu anda dil seviyesini "önizleme" olarak değiştirmeyi desteklemiyor gibi görünüyor.
Arcanox


DataTime s
Ignorance'ın


3

MySQL, 47 45 42 bytes

SELECT DATE_FORMAT(MAKEDATE(1,n),"%D %M")

1901 can be replaced with any year that was/is not a leap year.

Edit: saved two bytes by removing spaces and another three bytes by changing the year to 1, thanks to @Embodyment of Ignorance.


Can you remove the spaces between 1901, n and the string?
Embodiment of Ignorance

@EmbodimentofIgnorance yes I can, thanks!
NicolasB

Also, why not replace 1901 with a year like 1? 1 isn't a leap year, and it's 3 bytes shorter
Embodiment of Ignorance

@EmbodimentofIgnorance bitti ve bitti :-)
NicolasB

3

05AB1E , 81 79 78 76 75 74 73 71 70 69 bayt

•ΘÏF•ºS₂+.¥-D0›©ÏθDT‰ć≠*4šß„—ÊØ3ôsè¨ð”……‚應…ä†ï€¿…Ë…ê†Ä…æ…Ì…Í”#®OèJ

@Grimy sayesinde -9 bayt .
@ JonathanAllan'ın Jelly cevabında kullandığı standard thenumara sayesinde -1 byteth,st,nd,rd.

Çevrimiçi deneyin veya tüm olası test durumlarını doğrulayın.

Açıklama:

•ΘÏF        # Push compressed integer 5254545
     º       # Mirror it vertically: 52545455454525
      S      # Converted to a list of digits: [5,2,5,4,5,4,5,5,4,5,4,5,2,5]
       ₂+    # And 26 to each: [31,28,31,30,31,30,31,31,30,31,30,31,28,31]
             # (the additional trailing 28,31 won't cause any issues)
           # Undelta this list (with automatic leading 0):
             #  [0,31,59,90,120,151,181,212,243,273,304,334,365,393,424]
  -          # Subtract each from the (implicit) input-integer
   D0       # Duplicate the list, and check for each if it's positive (> 0)
      ©      # Store the resulting list in the register (without popping)
       Ï     # Only leave the values at those truthy indices
        θ    # And get the last value from the list, which is our day
D            # Duplicate this day
 T          # Take the divmod-10 of this day: [day//10, day%10]
   ć         # Extract the head; pop and push the remainder-list and head: [day%10], day//10
            # Check whether the day//10 is NOT 1 (0 if day//10 == 1; 1 otherwise)
     *       # Multiply that by the [day%10] value
      4š     # Prepend a 4 to this list
        ß    # Pop and push the minimum of the two (so the result is one of [0,1,2,3,4],
             # where the values are mapped like this: 1..3→1..3; 4..9→4; 10..19→0; 20..23→0..3; 24..29→4; 30,31→0,1)
 thŠØ       # Push dictionary string "th standards"
      3ô     # Split it into parts of size 3: ["th ","sta","nda","rds"]
        sè   # Swap and index the integer into this list (4 wraps around to index 0)
          ¨  # And remove the trailing character from this string
ð            # Push a space " "
”……‚應…ä†ï€¿…Ë…ê†Ä…æ…Ì…Í”
             # Push dictionary string "December January February March April May June July August September October November"
 #           # Split on spaces
  ®          # Push the list of truthy/falsey values from the register again
   O         # Get the amount of truthy values by taking the sum
    è        # Use that to index into the string-list of months (12 wraps around to index 0)
J            # Join everything on the stack together to a single string
             # (and output the result implicitly)

Nedenini anlamak için bu 05AB1E ucuna bakın :

  • (bölüm Sözlük nasıl kullanılır? )”……‚應…ä†ï€¿…Ë…ê†Ä…æ…Ì…Í” is "December January February March April May June July August September October November"
  • (bölüm Sözlük nasıl kullanılır? )…thŠØ is "th standards"
  • (bölüm büyük tamsayılar sıkıştırmak için nasıl? ) •ΘÏF•olduğunu5254545

1
-2 bytes by using 5в28+ for compression: TIO
Grimmy

1
Using S is a good idea, -1 byte again: TIO
Grimmy

1
@Grimy Thanks for the -1 byte for •EË7Óæ•S₂+, but your -3 golf doesn't work unfortunately. Indexing automatically wraps around in 05AB1E, so the 5st,6nd,7rd,25st,26nd,27rd,29st will be wrong. PS: if it would have worked, could have been for an additional -1. :)
Kevin Cruijssen

1
-1 again (using "th standards" instead of "standard the" removes the need for Á).
Grimmy

1
-1 (•C.ñÒā• to •ΘÏF•º, the extra digits don't matter)
Grimmy

2

bash, 82 80 bytes

-2 bytes thanks to @ASCII-only

a=(th st nd rd);set `printf "%(%e %B)T" $[$1*86399]`;echo $1${a[$1%30%20]-th} $2

TIO

bash +GNU date, 77 bytes

a=(th st nd rd);set `date -d@$[$1*86399] +%e\ %B`;echo $1${a[$1%30%20]-th} $2


@ASCII-only, yes subtracting 100s for each day, 100*365 = 36500s which is less than one day (86400), works also with 86399 (subtract 1s by day)
Nahuel Fouilleul

:/ still looks really long but haven't found a better way yet
ASCII-only

2

Shell + coreutils, 112 90 bytes

date -d0-12-31\ $1day +%-dth\ %B|sed 's/1th/1st/;s/2th/2nd/;s/3th/3rd/;s/\(1.\).. /\1th /'

Try it online! Link includes test cases. Edit: Saved 22 bytes thanks to @NahuelFouilleul. Explanation:

date -d0-12-31\ $1day

Calculate the number of day(s) after the first day preceding a non-leap year. (Sadly you can't do relative date calculations from @-1.)

+%-dth\ %B|sed

Output the day of month (without leading zero), th, and the full month name.

's/1th/1st/;s/2th/2nd/;s/3th/3rd/;

Fix up 1st, 2nd, 3rd, 21st, 22nd, 23rd and 31st.

s/\(1.\).. /\1th /'

Restore 11th to 13th.


i saw this answer after mine, could save 18bytes using one sed command, also s in days can be removed, and 19 in 1969
Nahuel Fouilleul

@NahuelFouilleul That last one uses a Bash-ism so should be posted as a separate answer, but thanks for the other tips!
Neil

2

Jelly, 115 114 101 97 bytes

%30%20¹0<?4Ḥ+ؽị“thstndrd”ṭ
“5<Ḟ’b4+28ÄŻ_@µ>0T,>0$ƇZṪµ1ịị“£ṢtẒ⁽ẹ½MḊxɲȧėAṅ ɓaṾ¥D¹ṀẏD8÷ṬØ»Ḳ¤,2ịÇƊṚK

Try it online!

Long by Jelly standards, but done from first principles.

Thanks to @JonathanAllan for saving 13 bytes through better understanding of string compression.


“£ṢtẒ⁽ẹ½MḊxɲȧėAṅ ɓaṾ¥D¹ṀẏD8÷ṬØ»Ḳ¤ would save 13 (Compress.dictionary looks for a leading space and has special handling for it).
Jonathan Allan

2

Google Sheets, 118 103 86 bytes

=day(A1+1)&mid("stndrdth",min(7,1+2*mod(mod(day(A1+1)-1,30),20)),2)&text(A1+1," mmmm")

I can't edit my comment so, here's a working version of the Google Sheets code.

Try it Online!


1

Red, 124 bytes

func[n][d: 1-1-1 + n - 1[rejoin[d/4 either 5 > t: d/4 % 30 % 20[pick[th st nd rd]t + 1]['th]]pick system/locale/months d/3]]

Try it online!

Adds n - 1 days to 1-1-1 (1-Jan-2001) to form a date, than uses Arnauld's method to index into month suffixes. Too bad Red is 1-indexed, this requires additional tweaking. The good thing is that Red knows the names of the months :)


1

APL(NARS), 235 chars, 470 bytes

{k←↑⍸0<w←+\v←(1-⍵),(12⍴28)+13561787⊤⍨12⍴4⋄k<2:¯1⋄d←1+v[k]-w[k]⋄(⍕d),({d∊11..13:'th'⋄1=10∣d:'st'⋄2=10∣d:'nd'⋄3=10∣d:'rd'⋄'th'}),' ',(k-1)⊃(m≠' ')⊂m←'January February March April May June July August September October November December'}

13561787 is the number that in base 4 can be summed to (12⍴28) for obtain the lenght of each month... test:

  f←{k←↑⍸0<w←+\v←(1-⍵),(12⍴28)+13561787⊤⍨12⍴4⋄k<2:¯1⋄d←1+v[k]-w[k]⋄(⍕d),({d∊11..13:'th'⋄1=10∣d:'st'⋄2=10∣d:'nd'⋄3=10∣d:'rd'⋄'th'}),' ',(k-1)⊃(m≠' ')⊂m←'January February March April May June July August September October November December'}     
  ⊃f¨1 2 3 365 60 11
1st January  
2nd January  
3rd January  
31st December
1st March    
11th January 

0

C (gcc), 174 155 bytes

i;char a[99],*b="thstndrd";f(long x){x--;x*=86400;strftime(a,98,"%d   %B\0",gmtime(&x));i=*a==49?0:a[1]-48;a[2]=b[i=i>3?0:i*2];a[3]=b[++i];x=*a==48?a+1:a;}

Try it online!


-2

Python 3, 95 Bytes

Datetimed it :P

from datetime import *;f=lambda s:(datetime(2019,1,1)+timedelta(days=s-1)).strftime("%d of %B")

Try it online!


2
This doesn't produce the ordinal suffixes, and has leading zeroes in the day number. The of is also unnecessary
Jo King
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.