1
\$\begingroup\$

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

\$\endgroup\$
2
  • 7
    \$\begingroup\$ Please explain what "modify itself (as a running process!!)" means. \$\endgroup\$
    – DavidC
    Dec 23, 2013 at 17:35
  • 1
    \$\begingroup\$ @DavidCarraher : en.wikipedia.org/wiki/Self-modifying_code \$\endgroup\$
    – vsz
    Dec 23, 2013 at 17:59

13 Answers 13

4
\$\begingroup\$

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
\$\endgroup\$
4
  • \$\begingroup\$ 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. \$\endgroup\$
    – manatwork
    Dec 26, 2013 at 18:03
  • \$\begingroup\$ 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. \$\endgroup\$ Dec 26, 2013 at 18:18
  • \$\begingroup\$ 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. \$\endgroup\$
    – manatwork
    Dec 26, 2013 at 18:32
  • 1
    \$\begingroup\$ IMHO defining a function on the fly with eval is not self-modification of running code, it's just part of the language. \$\endgroup\$
    – Tobia
    Dec 31, 2013 at 10:30
3
\$\begingroup\$

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

Reformatted for readability:

<?
$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
\$\endgroup\$
1
  • \$\begingroup\$ +1 This is the only real self-modifying code posted yet! \$\endgroup\$
    – Tobia
    Dec 31, 2013 at 10:45
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

Forth: 22 / 32 Chars. ( Using gforth )

s" Happy 2022" swap +!              ( 22 chars )

A compiled but slightly longer version is shown here, as the result can be decompiled, and its effects demonstrated. Principle of operation is identical to the shorter version above. Consider the longer version as demonstratable proof of concept.

: happy s" Happy 2022" swap +! ;    ( 32 chars )

I'll decompile this first, then execute, and decompile it again:

see happy    ( decompile happy, as it is now )

: happy
s" Happy 2022" swap +! ;

happy   ( execute the self-modifying happy )

see happy ( decompile happy again )

: happy
s" Rappy 2022" swap +! ;

What happens here is: s" ..." places two items on stack: address of first string character, and string length, which is 10 in this case. The sequence "swap +!" adds string length, 10, to the contents at first string address, thereby changing ASCII H to ASCII R.

A version matching the requirements slightly better is compiled using vfx:

: h 1 s" Happy 2021" 2dup type + 1- c+! ;

reason for using a different compiler for this version is that it provides c+! already which I'd have to add to gforth first, which should introduce a penalty of about 22 chars.

disassembling first:

( 080C0AF0 E81383F9FF ) CALL 08058E08 (S") "Happy 2021"
( 080C0B00 8BD3 ) MOV EDX, EBX
( 080C0B02 035D00 ) ADD EBX, [EBP]
( 080C0B05 4B ) DEC EBX
( 080C0B06 800301 ) ADD Byte Ptr 0 [EBX], 01
( 080C0B09 8BDA ) MOV EBX, EDX
( 080C0B0B FF15B9DE0408 ) CALL [0804DEB9] TYPE
( 080C0B11 C3 ) NEXT,

executing several times, output follows immediately:

h Happy 2022
h Happy 2023
h Happy 2024
h Happy 2025
h Happy 2026

disassembling again:

( 080C0B30 E8D382F9FF ) CALL 08058E08 (S") "Happy 2026"
( 080C0B40 8BD3 ) MOV EDX, EBX
( 080C0B42 035D00 ) ADD EBX, [EBP]
( 080C0B45 4B ) DEC EBX
( 080C0B46 800301 ) ADD Byte Ptr 0 [EBX], 01
( 080C0B49 8BDA ) MOV EBX, EDX
( 080C0B4B FF15B9DE0408 ) CALL [0804DEB9] TYPE
( 080C0B51 C3 ) NEXT,

\$\endgroup\$
3
  • \$\begingroup\$ Welcome to Code Golf, and nice answer! \$\endgroup\$ Nov 29, 2021 at 19:27
  • \$\begingroup\$ Thank you. I'm aware that this answer doesn't quite match the requirements. So I added the aspect of timelessness, for the years to come at least - After Rappy comes Sappy, then Tappy. After that, wait to enjoy Wappy and Zappy. \$\endgroup\$
    – Bushmills
    Nov 29, 2021 at 19:38
  • \$\begingroup\$ And not to forget Yappy :) \$\endgroup\$
    – Bushmills
    Nov 29, 2021 at 20:16
1
\$\begingroup\$

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())
\$\endgroup\$
1
\$\begingroup\$

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,.@
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
5
  • \$\begingroup\$ Not self-modifying. \$\endgroup\$
    – Tobia
    Dec 31, 2013 at 10:23
  • \$\begingroup\$ @Tobia How about now? \$\endgroup\$
    – Sylwester
    Dec 31, 2013 at 11:53
  • \$\begingroup\$ 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. \$\endgroup\$
    – Tobia
    Dec 31, 2013 at 18:00
  • \$\begingroup\$ @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. \$\endgroup\$
    – Sylwester
    Dec 31, 2013 at 18:34
  • \$\begingroup\$ 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 :) \$\endgroup\$
    – Tobia
    Jan 1, 2014 at 20:33
-1
\$\begingroup\$

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

\$\endgroup\$
3
  • \$\begingroup\$ Are you sure? unclosed script tags don't work on my browsers. \$\endgroup\$
    – xem
    Dec 29, 2013 at 8:20
  • \$\begingroup\$ 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. \$\endgroup\$
    – Tobia
    Dec 31, 2013 at 10:27
  • \$\begingroup\$ 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. \$\endgroup\$ Jan 2, 2014 at 4:56
-1
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ Not self-modifying. \$\endgroup\$
    – Tobia
    Dec 31, 2013 at 10:22
-1
\$\begingroup\$

Python 2,(151-10%)=136

Inspired by this answer

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()
\$\endgroup\$
3
  • \$\begingroup\$ I wouldn't consider exec as self-modification, it's just part of the language. \$\endgroup\$
    – Tobia
    Dec 31, 2013 at 10:24
  • \$\begingroup\$ @Tobia i have modified my answer please re-consider \$\endgroup\$
    – Wasi
    Jan 1, 2014 at 16:02
  • \$\begingroup\$ 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. \$\endgroup\$
    – Tobia
    Jan 1, 2014 at 20:36
-3
\$\begingroup\$

PHP, 28 (-10% is 25)

echo"Happy ".date('Y')."!";
\$\endgroup\$
2
  • \$\begingroup\$ How is this self-modifying? \$\endgroup\$
    – nitro2k01
    Dec 30, 2013 at 3:05
  • 1
    \$\begingroup\$ Not self-modifying. \$\endgroup\$
    – Tobia
    Dec 31, 2013 at 10:19
-3
\$\begingroup\$

HTML/JavaScript - 63 (70-10%)

<body onload="b.innerHTML=new Date().getFullYear()">Happy <b id=b>2013
\$\endgroup\$
1
  • \$\begingroup\$ Not self-modifying. \$\endgroup\$
    – Tobia
    Dec 31, 2013 at 10:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.