Wednesday, October 15, 2008

Self-reproducing programs

Also known as quine :D

My quick try:
(Java)


import java.io.*;

public class PrintMySelf { //Print the very source code
//this simple version replace line comment by blank line

public static void main(String args[]) throws IOException {

//use PushbackInputStream to get/unget each character
FileInputStream fileIS = new FileInputStream("PrintMySelf.java");
PushbackInputStream pushbackIS = new PushbackInputStream(fileIS);

int dataByte = 0;

while ( (dataByte = pushbackIS.read()) != -1 ) {
char dataChar = (char) dataByte;

if (dataChar == '/') { //strip all line comments
dataChar = (char) pushbackIS.read();

if (dataChar == '/') {
dataByte = pushbackIS.read();

while ( (dataByte != -1) && (dataByte != 13) ) {
dataByte = pushbackIS.read();
dataChar = (char) dataByte;
}

} else {
pushbackIS.unread( (int) dataChar );
}
}

System.out.print(dataChar);
}

fileIS.close();
pushbackIS.close();
}
}



Some other solutions:

(Python)

s = 's = %c%s%c%cprint s %% (39, s, 39, 10)'
print s % (39, s, 39, 10)


(C#)

class PrintMyself { static void Main(string[] args) {string x1 = ";char[] x2 = {'c','l','a','s','s',' ','P','r','i','n','t','M','y','s','e','l','f',' ','{','{',' ','s','t','a','t','i','c',' ','v','o','i','d',' ','M','a','i','n','(','s','t','r','i','n','g','[',']',' ','a','r','g','s',')',' ','{','{','s','t','r','i','n','g',' ','x','1',' ','=',' ','{','0','}','{','1','}','{','0','}'};System.Console.Write(string.Format(new string(x2), (char)34, x1) + x1);}}";char[] x2 = {'c','l','a','s','s',' ','P','r','i','n','t','M','y','s','e','l','f',' ','{','{',' ','s','t','a','t','i','c',' ','v','o','i','d',' ','M','a','i','n','(','s','t','r','i','n','g','[',']',' ','a','r','g','s',')',' ','{','{','s','t','r','i','n','g',' ','x','1',' ','=',' ','{','0','}','{','1','}','{','0','}'};System.Console.Write(string.Format(new string(x2), (char)34, x1) + x1);}}


Have fun,

1 comment:

moriator said...

Ồ, thì ra đây là blog của 1 Java Guru ^^ Mình cũng đang bắt đầu học Java, có gì khó khăn bạn giúp mình được không?