Quine

Posted on By ᵇᵒ

自产生程序,即不借助外部输入而输出自身源代码的程序。
英文 Quine,以美国哲学家奎恩(Willard Van Orman Quine)命名。

c

#include <stdio.h>
char*s="#include <stdio.h>%cchar*s=%c%s%c;%cint main(void){printf(s,10,34,s,34,10,10);}%c";
int main(void){printf(s,10,34,s,34,10,10);}

java

public class Quine {
    public static void main(String[] args) {
        char q = 34;    // Quotation mark character
        String[] s = {
            "public class Quine {",
            "    public static void main(String[] args) {",
            "        char q = 34;    // Quotation mark character",
            "        String[] s = {",
            "            ",
            "        };",
            "        for (int i = 0; i < 4; i++) {",
            "            System.out.println(s[i]);",
            "        }",
            "        for (int i = 0; i < s.length; i++) {",
            "            System.out.println(s[4] + q + s[i] + q + ',');",
            "        }",
            "        for (int i = 5; i < s.length; i++) {",
            "            System.out.println(s[i]);",
            "        }",
            "    }",
            "}",
        };
        for (int i = 0; i < 4; i++) {
            System.out.println(s[i]);
        }
        for (int i = 0; i < s.length; i++) {
            System.out.println(s[4] + q + s[i] + q + ',');
        }
        for (int i = 5; i < s.length; i++) {
            System.out.println(s[i]);
        }
    }
}

kotlin

fun main() {
    val textBlockQuotes = "\"\"\""
    val source = """
fun main() {
    val textBlockQuotes = "\"\"\""
    val source = %s
    print(source.format(textBlockQuotes + source + textBlockQuotes))
}
    """
    print(source.format(textBlockQuotes + source + textBlockQuotes))
}

java 15 开始也支持 Text Blocks。