I've been a zone leader with DZone since 2008, and I'm crazy about community. Every day I get to work with the best that JavaScript, HTML5, Android and iOS has to offer, creating apps that truly make at difference, as principal front-end architect at Avego. James is a DZone Zone Leader and has posted 639 posts at DZone. You can read more from them at their website. View Full User Profile

Thursday Code Puzzler: Self Replicating Program

12.20.2012
| 5165 views |
  • submit to reddit

Thursday is code puzzler day here at DZone. The idea is simple: solve the coding problem as efficiently as you can, in any language or framework that you find suitable.

Note: Even though there really is nothing stopping you from finding a solution to this on the internet, try to keep honest, and come up with your own answer.  It's all about the participation!

Do you have code puzzlers that you'd like to share with the DZone community?  If so, please submit here. 

Write a Self Replicating Program

Without using file reading/copying, write a program that will create a copy of itself (with a new random name) on the file system

Catch up on all our previous puzzlers here.

Comments

Claude Lalyre replied on Thu, 2012/12/20 - 9:18am

Beware of Java viruses with such challenge...

Matt Cholick replied on Thu, 2012/12/20 - 11:29pm

Groovy:

def p = '''
@Grab(group='commons-lang', module='commons-lang', version='2.4') import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric
File file = new File("${randomAlphanumeric(8)}.groovy").write(p)
new GroovyShell(new Binding([p: "def p = ${"'"*3}${p}${"'"*3}; ${p.readLines()[3]}"])).evaluate(p.readLines()[0..2].join(';') as String)
'''; new GroovyShell(new Binding([p: "def p = ${"'"*3}${p}${"'"*3}; ${p.readLines()[3]}"])).evaluate(p.readLines()[0..2].join(';') as String)

The comment block messes with newline a bit, it's easier to read on Github: https://gist.github.com/4350645

Hari Ravula replied on Fri, 2012/12/21 - 4:46am in response to: Matt Cholick

public class SelfPrinting {
	public static void main(String[] args) {
		String str = "public class SelfPrinting {\n\tpublic static void main(String[] args) {\n\t\tString str = \"%s\";" +
		"\n\t\tSystem.out.printf(str, str, str);\n\t}\n}";
		System.out.printf(str, str, str);
	}
}

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.