誕生日おめでとう!


21

誕生日おめでとう!

Happy birthday to me!誕生日に印刷するプログラムを作成します。

  1. プログラムの誕生日は、プログラムの作成、最終変更、またはコンパイル時(選択)であり、ハードコーディングしてはなりません。
  2. 誕生日として使用する日付は、プログラムの呼び出しや実行の影響を受けてはいけません。誕生日を変更することはできません。
  3. 追加のクレジット(-15%バイトカウント)の場合、プログラムと一致しない場合はHappy birthday to you!、誕生日(ハードコード)に印刷します。または、有名人の誕生日を使用して、-14%を獲得します。
  4. これのみを印刷し、他の日には何も印刷しないでください。
  5. UTF-8でバイトをカウントします。
  6. グレゴリオ暦を使用します。

幸運とお誕生日おめでとう(新生児プログラムへ)。

PS
Izkataのコメントに続いてHappy birthday to MelMel Kayeの誕生日に印刷すると、20%オフになります。しかし、あなたはそれがこの日付であるという信頼できる情報源を提供しなければなりません。


1
@TeunPronk、両方はできません。自分の誕生日を使用するか、有名人の誕生日を使用します(または、誕生日を使用せず、追加のクレジットを放棄します)。
ウゴレン14

4
@TeunPronk:Jon Skeetのみ:P
MSalters 14

11
私は熱い質問のサイドバーでこれを見て、「ハッピーバースデー読みメルを ...」
Izkata

1
@PeterTaylor:え?追加の機能に対してさまざまな種類のスコアボーナスを与えることは、コードゴルフの質問では非常に一般的であり、主要なスコアリング基準がコードの長さである限り、そのタグを使用することで質問が失格になると主張する人は誰もいません。
イルマリカロネン14

1
@ Izkata、Melに敬意を表して質問を更新しました。
ウゴレン14

回答:


10

PHP 77 75 74 65 60

Tim Seguineからのすばらしい提案に感謝します

<?date(dm,getlastmod())-date(dm)&&die?>Happy birthday to me!

卑劣なPHP:46 42 41 40

使い方フィルHのアイデアと再びティムSeguineの提案を

<?touch(__FILE__)?>Happy birthday to me!

比較に年が含まれていませんか?その場合、0歳の誕生日にのみ機能します。
ugoren

@ugorenそうですね!修正していただきありがとうございます。2バイトが保存されました。
ComFreek 14

ルールの「何も想定しない」が標準出力を意味すると解釈される場合''dm文字列の周囲を削除することで4バイトを獲得できます。警告が生成されましたが、エラー報告がオンになっている場合は標準エラーに送信されると思います。
ティムセギーン14

4
<?date(dm,stat(__FILE__)[9])-date(dm)&&die?>Happy birthday to me!
ティムセギーン14

1
@TimSeguineご提案ありがとうございます!私はそれらを私の答えに取り入れました。気にしないでください。
ComFreek 14

48

バッシュ(卑劣):36

touch $0;echo Happy Birthday to me\!

ルールによると:「プログラムの作成、修正、またはコンパイル時間」。修正時間と永続的な自己修正を選択します。[1文字のHT @ace]

Perl(同じく卑劣な):29

print "Happy birthday to me!"

これは間違いなく最初のものより卑劣です。Perlプログラムは、実行される前に常にコンパイルされますが、誰もが知っているわけではありません。したがって、ここで使用しているのはコンパイル日です。

-ルール変更の編集-

これは、誕生日の変更に関するルールが作成される前に書かれました。Perlがまだ残っていると思います。すべてのPerlプログラムは、実行前にコンパイルされます。教育的な理由でここに答えを残します!


6
よろしくお願いします。
ビクタースタフサ14

1
あなたは逃げることができる!との\!1つの文字を保存し、引用符を削除
user12205

1
素晴らしいトリックですが、ルールは明示的に禁止しています(現在)。
ウゴレン14

1
@ugorenは、プログラムの起動前にコンパイルされるperlソリューションを禁止していません。
ランチャー14

3
@クランチャー、私はあなたが正しいことを恐れています。弁護士に相談して請求書を送ります。
ウゴレン14

13

バッシュ-65

[ `date +%d%m -r $0` = `date +%d%m` ]&&echo Happy birthday to me!

助けてくれたugorenacenyuszika7hに感謝します。


!with をエスケープできる\!ので、引用符は必要なく、1文字節約できます。
user12205 14

エコーにはスペースが必要だと思ったので、実際には引用符がありました。私はそれらを取り出し、感嘆符を逃さず、それでもまだ機能しました。ヒントをありがとう!
潮ona 14

2
!スクリプトではなく、対話型のシェルでのみエスケープする必要があります。
nyuszika7h 14

[andの]代わりに[[and を使用して、2文字を保存できます]]
nyuszika7h 14

1
年が作成日と同じでないときに機能しますか?
ウゴレン14

6

C#198.05(233-15%)

using s=System;class P{static void Main(){string t=s.DateTime.Now.ToString("Mdd"),b="1202";if(s.IO.File.GetCreationTime(typeof(P).Assembly.Location).ToString("Mdd")==t|b==t)s.Console.Write("Happy birthday to "+(b==t?"you!":"me!"));}}

フォーマット済み:

using s = System;
class P
{
    static void Main()
    {
        string t = s.DateTime.Now.ToString("Mdd"), b = "1202";
        if (s.IO.File.GetCreationTime(typeof(P).Assembly.Location).ToString("Mdd") == t | b == t)
            s.Console.Write("Happy birthday to " + (b == t ? "you!" : "me!"));
    }
}

191(ボーナスなし)

using s=System;class P{static void Main(){if(s.IO.File.GetCreationTime(typeof(P).Assembly.Location).ToString("Mdd")==s.DateTime.Now.ToString("Mdd"))s.Console.Write("Happy birthday to me!");}}

181,05(213-15%)

いくつかの追加の指示(これをコンパイルしてb.exe、実行可能ファイルが存在するディレクトリから実行する必要があります)で、これを理解できます。

using s=System;class P{static void Main(){string t=s.DateTime.Now.ToString("Mdd"),b="1202";if(s.IO.File.GetCreationTime("b.exe").ToString("Mdd")==t|b==t)s.Console.Write("Happy birthday to "+(b==t?"you!":"me!"));}}

171(ボーナスなし)

上記と同じ手順で、今回は自分の誕生日にのみメッセージを印刷します(したがって、-15%のボーナスはありません)。

using s=System;class P{static void Main(){if(s.IO.File.GetCreationTime("b.exe").ToString("Mdd")==s.DateTime.Now.ToString("Mdd"))s.Console.Write("Happy birthday to me!");}}

,b="1202"==t日付文字列を取得した後に追加して、代わりに使用することで、ボーナスバイトに数バイトを保存できます。
ahruss

1
ありがとう!「数バイト」は1であることが判明しましたが...または何か不足していますか?編集ああ、わかりました。あなたは言った,b="1202"==tが、その==t部分はブールに評価され、他の変数は文字列であるため、その部分は不可能です。(つまり)1つの "var"宣言で2つの異なる型を使用することはできません。
RobIII 14

あ、そう。C#を使用してからしばらく経ちました。私の悪い。
ahruss

文字列ではなく日付を比較することで、より単純なバージョンを短縮できます。このメンズのようなものを使用しますCreationTime.Date == DateTime.Today
svick 14

それは今日/今年/誕生日0でのみ機能します。他の年ではどのように機能しますか?
RobIII 14

5

Java-275-15%= 233.75ボーナスあり/ 237ボーナスなし

ボーナスあり:

import java.util.*;class L{public static void main(String[]y){int s=f(new Date());String j="Happy birthday to ";System.out.print(s==f(new Date(new java.io.File("L.class").lastModified()))?j+"me!":s==183?j+"you!":"");}static int f(Date d){return d.getMonth()*40+d.getDate();}}

ボーナスなし:

import java.util.*;class L{public static void main(String[]y){if(f(new Date())==f(new Date(new java.io.File("L.class").lastModified())))System.out.print("Happy birthday to me!");}static int f(Date d){return d.getMonth()*40+d.getDate();}}

私は4月23日に生まれました。


1
幸せな誕生日には、いないため ;-)だけではあなたに別のバイト:-)保存
RobIII

@RobIIIありがとう、修正。
ビクターStafusa 14

また、改行(\n)は不要です。これにより、さらに4バイト節約できます
;

@RobIIIどうもありがとう。
ビクターStafusa 14

ええ...私は自分の足の撮影を停止する必要があります:Pどういたしまして;)
RobIII 14

3

私は、メッセージの数バイトを節約するこの小さなトリックをかなり誇りに思っています。他の回答に含まれることを期待しています。私はこれを最初に考えました!

Python

105文字、追加クレジットなし。「誕生日おめでとう」としてファイルを保存して実行します。GMTのみで実行され、「誕生日」は誕生日ではなく、記念日として定義されます(「誕生日」とも呼ばれます)。

import sys,os,time
if (int(os.stat(*sys.argv).st_atime/86400)==int(time.time()/86400)):print sys.argv[0]

動作するように、これを「誕生日おめでとう」として保存して実行します python "happy birthday to me"

注:もちろん、小さなブートストラップ以外のすべてがファイル名に含まれている可能性があり、任意の大きなコードをブートストラップまで減らすことができます。通常、私はこの「不正行為」を検討します。しかし、「誕生日おめでとう」は不当なファイル名ではありません-それはプログラムが何をするかを説明し、いくつかのプログラム(例えば「python」)よりもはるかに良いので、この場合は許可します:)


I think relying on the file name is cheating (though I didn't forbid it explicitly). If it's allowed, why not just write eval(sys.argv[0])?
ugoren

And I didn't bother to define a birthday, but it's a day that comes once a year when a person celebrates the anniversary of their birth, not the exact day when you were born.
ugoren

ugoren: I did mention that in my note at the bottom (which pre-dates your comment). However, "happy birthday to me" is not an unreasonable filename - it describes what the program does, much better than some programs (e.g. "python"), so in this case I'm going to allow it
AMADANON Inc.

2

Matlab: 66

t=dir('f.m');if strncmp(t.date,date,5),'Happy birthday to me!',end

File name has to be 'f.m'


1
On your birthday it should say "Happy birthday to you!" :-)
RobIII

@RobIII:Oops, you'r right, I didn't read carefully enough. Will remove the second version. Thanks!
H.Muster

I assume strncmp(x, y, 5) compares dates like 28-12-2013's first 15 characters (being 28-12 e.g. dec. 28th). Does this also work when the user's locale settings are yyyy/mm/dd for example? Does Matlab default to dd-mm-yyyy always? (Just curious). Edit Nevermind: found it!. It seems it does. It wouldn't matter anyway for mm/dd/yyyy or dd-mm-yyyy since both left and right operand would use the same format anyway and both 5 leftmost chars would match anyway; as long as the year is never leading.
RobIII

Why do you need the variable t? Doesn't dir('f.m').date work?
ugoren

@ugoren: t is necessary to make dir return the file attributes (otherwise it would it would just return all files in the directory that match 'f.m'). Furthermore, t is necessary to access the date field.
H.Muster

2

GNU COBOL with -free, 204

PROGRAM-ID.B.DATA DIVISION.WORKING-STORAGE SECTION.
1 A PIC XXXX/XX.
1 B PIC X(5).
1 C PIC X(21).
PROCEDURE DIVISION.ACCEPT A FROM DATE
ACCEPT C
MOVE WHEN-COMPILED TO B
IF A(3:5) = B OR "12/09" DISPLAY C.

I break the rules about the celebrity, so no bonus there...

The text produced is user-input (requested when run). If that is not good-to-go, then the line defining C needs to be deleted, as does ACCEPT C, and DISPLAY C must become DISPLAY "HAPPY BIRTHDAY TO ME!", for an extra seven characters.

WHEN-COMPILED is a special-register containing compile date/time which is available to the program (always handy, you can know you have the correct version). It is truncated in the MOVE because the rest isn't needed. DATE is the current date - this one is yymmdd.

The / in the definition of A is an insertion editing symbol, since the compile-date contains slashes. An extra character, but eases the compare.

Celebrity = Grace Hopper


2

Batch - 37 Bytes

Stealing the method used by one of the Bash answers..

@echo.>>%0&echo Happy birthday to me!

Other method - 145 Bytes

@for /f "tokens=2,3 delims=/ " %%a in ("%date%")do @for /f "tokens=1,2 delims=/" %%c in ("%~t0")do @if %%a%%b==%%c%%d @echo Happy Birthday to me!

1

Ruby, 69 characters/bytes

puts'Happy birthday to me!'if(Time.new-File.atime($0))%31536000<86400

31536000 is the number of seconds in a year, and 86400 is the number of seconds in a day.


4
Unfortunately, only works correctly for maximum of seven years or so, until you run into the first leap year after the atime.
Amadan

Also says "happy birthday" on the morning after your birthday, and doesn't say happy birthday the morning of your birthday before your birth time.
AMADANON Inc.

1

JavaScript

Node.js, 156 bytes

b=new Date(require("fs").statSync(__filename).mtime);d=new Date();b.getDate()==d.getDate()&&b.getMonth()==d.getMonth()&&console.log("Happy birthday to me!")

Uses the file's modification time.


beating you by 56 bytes so far =P
stroncium

I get a runtime error when I run yours, but the match approach is definitely much cleverer. Fix the error and you've got my upvote. ;)
Chris W.

Can you quote the error and your OS? I guess it's just not crossplatform.
stroncium

1

Powershell - 105 bytes

if('{0:M}'-f(gi $MyInvocation.MyCommand.Definition).creationtime-eq(date -f M)){'Happy birthday to me!'}

Ungolfed:

if('{0:M}' -f (gi $MyInvocation.MyCommand.Definition).creationtime -eq (date -f M)){
  'Happy birthday to me!'
}

The bonus isn't worth it, I can only get 117.5.


1

Powershell - 127

if ((gci $MyInvocation.MyCommand.Path).lastwritetime.ToString("MMdd") -eq (get-date).ToString("MMdd")){"happy birthday to me!"}

For the 15% bonus - 151 bytes, less 15% = 128.4

$r=@{"0308"="you";(gci $MyInvocation.MyCommand.Path).lastwritetime.ToString("MMdd")="me"}[(get-date).tostring("MMdd")]
if($r){"Happy birthday to $r!"}

1
I'm no powershell expert, but this will only work in the current year? What what when the "program" has it's 1st, 2nd, 3rd etc. birthday?
RobIII

You can remove the write command - With just "happy birthday to me!" it will print it out.
unclemeat

Your quite right. I should know that.
Chris J

@Robill - oops. That's what comes of writing something when I'm distracted by something else and using codegolf as procrastination. Fixed (not that it's got a chance of winning, mind).
Chris J

1

Ruby - 80 103 87 bytes

m=File.mtime $0
t=Time.now
puts"Happy birthday to me!"if t.month==m.month&&t.day==m.day

Ruby - 123 115 135 121 - 15% = 104.55 97.75 114.75 102.85 points

t=Time.now
{me:File.mtime($0),you:Time.at(36e5)}.map{|n,d|puts"Happy birthday to #{n}!"if t.month==d.month&&t.day==d.day}

Might be a little longer or shorter depending on where your birthday falls in the year, and the shortest way to represent that. For mine, that's 36e5 (seconds since epoch; time zone dependent).


Does Mel Gibson count? Here's a 138 byte - 35% bonus = 89.7-point program that celebrates itself, me, and Mel!

t=Time.now
{me:File.mtime($0),you:Time.at(36e5),Mel:Time.at(2e5)}.map{|n,d|puts"Happy birthday to #{n}!"if t.month==d.month&&t.day==d.day}

1
Your code fails on leap years, for dates after February.
ugoren

@ugoren right you are. Fixed that, but lost a lot of points :(
Tim S.

But now I've reclaimed most of those! =)
Tim S.

0

PureBasic

Without Bonus - 142

If Bool(FormatDate("%dd%mm",Date())=FormatDate("%dd%mm",GetFileDate(ProgramFilename(),0)))
MessageRequester("","Happy birthday To me!")
EndIf

With Bonus - 218 - 15% = 185.3

Dim s$(2)
s$(1)="me"
s$(2)="you"
m$="%dd%mm"
d$=FormatDate(m$,Date())
i=Bool(d$=FormatDate(m$,GetFileDate(ProgramFilename(),0)))|(Bool(d$="2301")<<1)
If i=0:End:EndIf
MessageRequester("","Happy birthday To "+s$(i)+"!")

0

TI-BASIC, 68 bytes

If Ans=0:getDate→G:0:G=G:If getDate=G:Disp "HAPPY BIRTHDAY TO ME!"

Remember, these tokens are one byte: If , Ans, →, Disp. getDate is two bytes. All other one-character symbols are one byte.


1
Are you sure that's UTF-8?
Fozzedout

3
OP explicitly states you should use UTF-8. That's 66 characters and 68 bytes.
nyuszika7h

2
If you want to claim it's 46 bytes, write it in 46 bytes. As it is now, it's 68 bytes.
ugoren

According to the token sizes in a standard TI-Basic environment it is 55 bytes, but as plain text yea its 68. Also technically there does not have to be a " at the end so that could save a byte.
Lemon Drop

0

J 79

 echo((6!:0'')(('',:'Happy birthday to me!'){~])@:-:&(1 2&{)&:>])1{,1!:0{:4!:3''

Bonus version120 - 15% = 102

Do I get extra credit for also printing both when both are having their birthday?

echo((2 6$(6!:0 '') , 0 2 7)(' ','Happy birthday to ',"2 1]3 5$'you! me!  both!'){~#.@:(-:&(1 2&{)"1)&:>])1{,1!:0{:4!:3''

Explanation (right to left):

last =: {:4!:3''     NB. Take the last script run (i.e. the file itself)
time =: 1{,1!:0 last NB. the modification time is the second element in that file's listing

The central verb of the train

unbox_both =: &:>      NB. unboxes left and right argument
match  =: -:&(1 2&{)"1 NB. for each date given, left and right, compare them
to_int =: #.           NB. convert boolean to int
from   =: {~           NB. from the left array, take element right.

NB. H contains messages an empty row, appended to all combinations of messages. 
H =: (' ','Happy birthday to ',"2 1]3 5$'you! me!  both!')

V =: (H from to_int)@:match unbox_both NB. after unboxing and comparing, 
                                       NB. select the according message

The left tine for the central train:

dates=: (2 6$(6!:0 '') , 0 2 7) NB. the current date, and the relevant fields of my birthday.

NB. Combining the bricks:
echo (dates V ]) time           NB. output the monads result on time.

0

Java - 196

This differs from the other Java submission by using Strings, shaving 41 characters off in the process. It uses String.format("%tj") to format a java.util.Date or a long as a day-of-year String, and then compares these two Strings.

class Z{public static void main(String[]y){if("".format("%tj",new java.util.Date()).equals("".format("%tj",new java.io.File("Z.class").lastModified())))System.out.print("Happy birthday to me!");}}

Formatted:

class Z
{
    public static void main(String[] y)
    {
        if ("".format("%tj", new java.util.Date()).equals("".format("%tj", new java.io.File("Z.class").lastModified())))
            System.out.print("Happy birthday to me!");
    }
}

1
Day of year doesn't work well with leap years.
ugoren

@ugoren I agree. However, since the contest is currently running and we're at Feb. 20th. the compilation dat should be fine for a few days and not cause a problem following years. When compiling after Feb. 28th there will be a (future) problem indeed.
RobIII

If I were compiling after February 28th I could change the String format to "%tm%td" at a six point character cost
timxyz

0

C# 191 no bonus

using s=System;class P{static void Main(){if(s.IO.File.GetCreationTime(typeof(P).Assembly.Location).ToString("Mdd")==s.DateTime.Now.ToString("Mdd"))s.Console.Write("Happy birthday to me!");}}

formatted:

using s = System;
class P
{
    static void Main()
    {
        if (s.IO.File.GetCreationTime(typeof(P).Assembly.Location).ToString("Mdd") == s.DateTime.Now.ToString("Mdd"))
            s.Console.Write("Happy birthday to me!");
    }
}

You use x only twice; var x="MMdd"; + ToString(x) + ToString(x) = 15 whereas ToString("MMdd"); + ToString("MMdd"); only costs 12.
RobIII

Also, a newline is not required so WriteLine() can be shortened to Write(). With above and this change in place you have the exact same solution as I do ;-)
RobIII

1
You should update the score too, which is 193 now. And you can get it down to 191 by shaving two M's off * hint * :P
RobIII

0

JavaScript (node.js) - 100 bytes

(require('fs').fstatSync(4).mtime+1).match(Date().substr(4,6))&&console.log('Happy birthday to me!')

0

vb.net ~161c

This will print the celebration message to all whose birthday it is.

Module M
Sub Main
For Each b In{({"1705","Alan"}),({"2012","You"}),({FileDateTime(Process.GetCurrentProcess.MainModule.FileName).ToString("ddMM"),"Me"})}
If b(0)=Now.ToString("ddMM") Then Console.WriteLine("Happy Birthday To {0}!",b(1))
Next
End Sub
End Module

Alan => Alan Kaye

Score: 253c (-33c vb.net min) = 220 - 15% (my birthday bonus) = 187c - 14% (Celeb Birthday) = 160.82 ~161c or 220c - 29% = 156.2 ~157c


You can get a bonus for your birthday OR a celebrity. Not both.
ugoren

@ugoren Scoring doesn't state it's an exclusive or, so I'm using the logical meaning of or.
Adam Speight

0

Powershell, 82 bytes

see also answers from Chris J and SpellingD

"Happy birthday to me!"|?{(gv My* -v|% M*|% p*h|gci|% l*w*e|% D*r)-eq(date|% D*r)}

where

gv My* -v|% M*|% p*h|gci|% l*w*e|% D*r

is the combinations of shortcuts and aliases for the expression:

Get-Valiable MyInvocation -value|% MyCommand|% Path|Get-ChildItem|% LastWritetime|% DayOfYear

that equivalent a canonical form:

(Get-ChildItem $MyInvocation.MyCommand.Path).LastWritetime.DayOfYear

Powershell, 119 bytes - 14% = 102.34 Points

filter e{$_-eq(date|% D*r)}$('me'|?{gv My* -v|% M*|% p*h|gci|% l*w*e|% D*r|e}
'Prof'|?{3|e})|%{"Happy birthday to $_!"}

At January 3, the script display Happy birthday to Prof!. If this script is saved on January 3, two greetings will be displayed.


-1

C# - 63 bytes

class P
{
    static void Main()
    {
          Console.Write("Happy birthday to me!"));
    }
}

I choose compilation time. Since the C# code compiles to MSIL which on runtime is compiled to the executable code by the JIT Compiler, this program meets the conditions.

EDIT-- Possibly invalid answer as pointed in comments.


1
Old trick, no longer valid. Rule 2 says "must not be affected by the program's invocation or execution in any way".
ugoren

updated accordingly. Thank You @ugoren
rahulroy9202

@ugoren The PERL code by Phil H also uses this very same trick. Check the highest voted answer.
rahulroy9202

2
It's also an invalid answer. But - he was first to use this trick, and at the time he did it the rules allowed it.
ugoren
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.