# Shortest self-modifying code to wish a happy New Year!

Your code just has to print "Happy 2013". However, if it detects that it's 2014, it has to modify itself (as a running process!!) and print "Happy 2014" instead.

By self-modifying I mean the running process must really modify itself: it should alter its own instructions while it is executing.

Shortest code wins.

-10% size bonus if it's general, so it works for 2015, etc.

Sorry if the task excludes some languages or systems where it's not possible...

• Please explain what "modify itself (as a running process!!)" means. – DavidC Dec 23 '13 at 17:35
• @DavidCarraher : en.wikipedia.org/wiki/Self-modifying_code – vsz Dec 23 '13 at 17:59

# Bash / shell script (35 chars - 10% = 31.5)

I think this shell script counts as self-modifying:

$eval "y()(echo Happy date +%Y)";y Happy 2013$


At least, it does modify its own function y:

$set | grep -A3 '^y ()' y () { ( echo Happy 2015 ) }$


@manatwork suggested eval "y()(date +Happy\ %Y)";y, which produces the desired output, but I'm not sure if this counts as self-modifying, to the extent that it self-modifies with the current year. The generated function is as follows, which won't be a different function on a yearly basis:

y ()
{
( date +Happy\ %Y )
}


If it does count, then the score is:

# Bash / shell script (29 chars - 10% = 26.1)

A lot of entries don't seem to make any attempt to self-modify. If we lift this restriction for shell-script, then we can do this which weighs in at:

# 15 chars - 10% = 13

date +Happy\ %Y

• Good one, but can be shorter: eval "y(){ date +Happy\ %Y;}";y. By the way, please add a heading line (with some kind of formatting) to your post containing language, character count and score. – manatwork Dec 26 '13 at 18:03
• Thanks @manatwork - I'm not sure if that counts or not - see my edit. But thanks for the suggestion. This is my first answer on PPCG, so my apologies for not getting the score and formatting thing right. – Digital Trauma Dec 26 '13 at 18:18
• Ah, you mean, the generated code is also generic, not year-specific. Good point. I thought, as function y not existed before running the code, creating it is a modification. Not sure anymore. – manatwork Dec 26 '13 at 18:32
• IMHO defining a function on the fly with eval is not self-modification of running code, it's just part of the language. – Tobia Dec 31 '13 at 10:30

## PHP

### Creation of source code statement: 26 - 10% = 23.4

eval('?>Happy '.@date(Y));


### Overlay of existing instruction: 255 - 10% = 229.5

This can only possibly work on Linux systems configured with a writable /proc/self/mem, and short_tags = On is also assumed. (If short_tags = Off, replace <? with <?php , for a score of 233.1.)

<?$p='/proc/self/';$f=fopen($p.@mem,'r+');foreach(file($p.@maps)as$L)if(sscanf($L,'%x-%x rw%c',$i,$e,$n)>2)for(fseek($f,$i),$a=@xxxx,$e-=$i-4;$e-=4;){$b=$a;$a=fread($f,4);if($j=@strpos("x$b$a",GO.LF)){fseek($f,$j-9,1);fputs($f,@date(Y));}}$f=0?>Happy GOLF


<?
$p = '/proc/self/';$f = fopen($p . @mem, 'r+'); foreach (file($p . @maps) as $L) if (sscanf($L, '%x-%x rw%c', $i,$e, $n) > 2) for (fseek($f, $i),$a = @xxxx, $e -=$i - 4; $e -= 4;) {$b = $a;$a = fread($f, 4); if ($j = @strpos("x$b$a", GO.LF)) {
fseek($f,$j - 9, /* SEEK_CUR */ 1);
fputs($f, @date(Y)); } }$f = 0
?>Happy GOLF

• +1 This is the only real self-modifying code posted yet! – Tobia Dec 31 '13 at 10:45

# APL, self-modifying*, general – 72 chars

Tested on Dyalog APL. On other systems you might have to adjust the 3+ on line 3.

∇H
y←2012
→(y=z←1⌷⎕TS)/k
x←⎕CR'H'⋄x[2;3+⍳4]←⍕z
⎕FX x⋄H⋄→0
k:⎕←'Happy'y
∇


(*) This function does the following:

• set a variable y to some constant year;

• test whether y points to the current year; if not:

• update its own definition, changing the numeric constant in the first line so that it sets variable y to the current year;
• call itself recursively, so that the recursive call uses the new definition.

Whether this is acceptable as self-modifying, I'll leave to the OP to decide.

Example invocation, displaying the function code before and after the invocation. As you can see, line 1 has changed during the invocation:

      ∇H[⎕]∇
[0]   H
[1]   y←2012
[2]   →(y=z←1⌷⎕TS)/k
[3]   x←⎕CR'H' ⋄ x[2;3+⍳4]←⍕z
[4]   ⎕FX x ⋄ H ⋄ →0
[5]  k:⎕←'Happy'y

H
Happy  2013

∇H[⎕]∇
[0]   H
[1]   y←2013
[2]   →(y=z←1⌷⎕TS)/k
[3]   x←⎕CR'H' ⋄ x[2;3+⍳4]←⍕z
[4]   ⎕FX x ⋄ H ⋄ →0
[5]  k:⎕←'Happy'y


## Python (144 characters; 130 after removal of 10%)

This codes writes a library, thats imported (again after updating the code) and used.

import datetime
f=open("y.py",'w')
f.write("def year():return "+str(datetime.date.today().year))
f.close()
import y
print "Happy "+str(y.year())


# Befunge 98, 26 bytes - 10% (bonus) = 23.4

"EMIT"4(Yd0p"  yppaH"5k,.@


The first space immediately after the quote gets overwritten with a unicode character with code point equal to the year.

The self-modifying part of this code actually makes it more verbose. The below code performs the same task without self-modification:

"EMIT"4(Y" yppaH"5k,.@


# Perl (100 characters (90 after removal of 10%))

$^I="";@ARGV=$0;s/ \K\d+/$l=(localtime)[5]+1900/e,print while<>;exec perl,$0if$&!=$l;print"Happy 1
"


It's probably too long, but I don't care (at least it's round in its size). Could be shorter if it would read UTC time (replace localtime with gmtime). Please note that after running, it will increase its size to 103 characters (unless you run this in year 10000, then 104 characters), but hey, it's self-modifying.

# Racket - 139 - 10% = 125.1

(let g((y(date-year(seconds->date(current-seconds))))(h"Happy ~a~%"))
(if(< 2013 y)(begin(set! g(lambda()(printf h y)))(g))(printf h 2013)))


Ungolfed:

(let g ((y (date-year (seconds->date (current-seconds))))
(h "Happy ~a~%"))
(if (< 2013 y)
(begin
(set! g (lambda () (printf h y)))
(g))
(printf h 2013)))


So I'm using a named let which is creating a procedure g and calling it with the parameter y (current year) and h (printf format string). If y is higher than 2013 i redefine g to a procedure that takes no arguments and prints a suitable string for the current year instead just before calling the new procedure. It's short since h and y are in the new procedures closure variables.

• Not self-modifying. – Tobia Dec 31 '13 at 10:23
• @Tobia How about now? – Sylwester Dec 31 '13 at 11:53
• IMHO you're still using an if that chooses between two code paths, you're not modifying the actual source code being run. See the PHP answer by @PleaseStand (the longer one) for an example of actual self-modifying code. – Tobia Dec 31 '13 at 18:00
• @Tobia According to the wikipedia page changing function pointers are considered self modifying. I change a two argument procedure to a zero argument procedure of one line after 2013. The PHP example doesn't change it's code but elements of it's data segment. In reality only machine code can alter itself and it needs a low security OS to do it. – Sylwester Dec 31 '13 at 18:34
• I agree that the PHP example is only changing its data segment and not its bytecode, but I still think it's the most "self-modifying" code in all this page. Self modification is not restricted to machine code: interpreted languages can alter their source, bytecode, or whatever data structure is being traversed by the interpreter. This is not exposed by most interpreters, but it can be done through pointer manipulation or /proc/self/mem tricks, like in the PHP example. Still, my answer is not better than yours, so I might as well remove my downvote :) – Tobia Jan 1 '14 at 20:33

# JavaScript (ECMAScript 5)/HTML (HTML5) - 106

<script id=k type=x>2013</script><script>k.innerHTML=new Date().getFullYear();alert('Happy '+k.innerHTML);


And here is the jsfiddle

Note that in the jsfiddle, I included a closing </script>, but it isn't necessary, it is just necessary to work in jsfiddle

• Are you sure? unclosed script tags don't work on my browsers. – xem Dec 29 '13 at 8:20
• The idea of using innerHTML to modify the source code is neat, but IMHO this is not self-modifying code, because the modified part does not actually execute. You just use k.innerHTML like any other string variable. – Tobia Dec 31 '13 at 10:27
• It doesn't say in the code anywhere that it needs to execute the code, it just needs to be self modifying. And this is. – markasoftware Jan 2 '14 at 4:56

# Javascript 122 - 10% = 109.8

function n(){y=0;z=new Date().getFullYear();if(y-z){eval((""+n).replace(y,z));alert("Happy new "+z)}setTimeout(n,1000)}n()


It will greet you with a happy new year for the current year, and also keep checking periodically forever and greet you again if a new year comes.

• Not self-modifying. – Tobia Dec 31 '13 at 10:22

## Python 2,(151-10%)=136

from datetime import*
s=int(str(datetime.now())[:4]);x=2013;q=globals
def l(): return x
n="def l():return[x,s][s>x]"
exec(n,q(),q())
print'Happy %d'%l()

• I wouldn't consider exec as self-modification, it's just part of the language. – Tobia Dec 31 '13 at 10:24
• @Tobia i have modified my answer please re-consider – Wasi Jan 1 '14 at 16:02
• I still think changing a function definition or using exec is not proper "self-modifying" code. But my answer is not better than yours, so I will remove my downvote. – Tobia Jan 1 '14 at 20:36

# PHP, 28 (-10% is 25)

echo"Happy ".date('Y')."!";

• How is this self-modifying? – nitro2k01 Dec 30 '13 at 3:05
• Not self-modifying. – Tobia Dec 31 '13 at 10:19

## HTML/JavaScript - 63 (70-10%)

<body onload="b.innerHTML=new Date().getFullYear()">Happy <b id=b>2013

• Not self-modifying. – Tobia Dec 31 '13 at 10:20