0
\$\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\$
  • 7
    \$\begingroup\$ Please explain what "modify itself (as a running process!!)" means. \$\endgroup\$ – DavidC Dec 23 '13 at 17:35
  • 1
    \$\begingroup\$ @DavidCarraher : en.wikipedia.org/wiki/Self-modifying_code \$\endgroup\$ – vsz Dec 23 '13 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\$
  • \$\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 '13 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\$ – Digital Trauma Dec 26 '13 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 '13 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 '13 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\$
  • \$\begingroup\$ +1 This is the only real self-modifying code posted yet! \$\endgroup\$ – Tobia Dec 31 '13 at 10:45
1
\$\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\$
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\$
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\$
  • \$\begingroup\$ Not self-modifying. \$\endgroup\$ – Tobia Dec 31 '13 at 10:23
  • \$\begingroup\$ @Tobia How about now? \$\endgroup\$ – Sylwester Dec 31 '13 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 '13 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 '13 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 '14 at 20:33
0
\$\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\$
-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\$
  • \$\begingroup\$ Are you sure? unclosed script tags don't work on my browsers. \$\endgroup\$ – xem Dec 29 '13 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 '13 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\$ – markasoftware Jan 2 '14 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\$
  • \$\begingroup\$ Not self-modifying. \$\endgroup\$ – Tobia Dec 31 '13 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\$
  • \$\begingroup\$ I wouldn't consider exec as self-modification, it's just part of the language. \$\endgroup\$ – Tobia Dec 31 '13 at 10:24
  • \$\begingroup\$ @Tobia i have modified my answer please re-consider \$\endgroup\$ – Wasi Jan 1 '14 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 '14 at 20:36
-3
\$\begingroup\$

PHP, 28 (-10% is 25)

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

C++ - 97 Characters

I am not sure if this qualifies, but it prints out "Happy " and the year out until the next Y2K.

#include<ctime>
#include<iostream>
int main(){std::cout<<"Happy "<<time(0)/31557600+1970;return 0;}
\$\endgroup\$
  • \$\begingroup\$ Not self-modifying. \$\endgroup\$ – Tobia Dec 31 '13 at 10:20
  • \$\begingroup\$ Oh. I guess I will have to open the .cpp file, calculate the date, then write the date out and output it as text, not a calculation. \$\endgroup\$ – Hosch250 Dec 31 '13 at 16:14
-3
\$\begingroup\$

HTML/JavaScript - 63 (70-10%)

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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