PHP 5.5 -> Ruby 2.0 -> Python 2.7 -> Lua -> C # -> Java -> PdfTeX -> GolfScript 855/8 ^ 2 = 13.359375
As principais idéias foram:
- Em vez de realmente criar a lógica para criar a n + 1ª linguagem em todas as linguagens de programação, faça isso apenas uma vez e use apenas os recursos básicos de escrita aleatória e stdout de cada linguagem de programação
- Para encurtar o gerador de modelos, basta compactá-lo com o zLib. Faça deste gerador o segundo idioma
- Use PHP como o primeiro idioma, pois possui descompactador zLib embutido
Portanto, o código inicial é:
<?php $x=file_get_contents("php://stdin");echo preg_replace_callback("/\[(.*?)\]/",function($m){$r=explode("/",$m[1]);return $r[array_rand($r)];},$x).gzuncompress("BINARY_DATA")."__END__\n".$x;
Onde BINARY_DATA
está a versão gzcompressed do gerador de modelos (por exemplo, o resultado do código php, que é a versão ruby)
O código inicial completo em base64 (deve ter 855 bytes após a decodificação):
PD9waHAgJHg9ZmlsZV9nZXRfY29udGVudHMoInBocDovL3N0ZGluIik7ZWNobyBw
cmVnX3JlcGxhY2VfY2FsbGJhY2soIi9cWyguKj8pXF0vIixmdW5jdGlvbigkbSl7
JHI9ZXhwbG9kZSgiLyIsJG1bMV0pO3JldHVybiAkclthcnJheV9yYW5kKCRyKV07
fSwkeCkuZ3p1bmNvbXByZXNzKCJ42o2UwXKbMBCG7zyFZj0doElV55BLiNJmmump
7aHpTA+Yg4xErA6SGCQSZ4jevZIBx3biTHywzO6y/7+fYRm5uf5zjVtOGS5XWjbY
NLWwSZzHKVx4OTa06Z/oE51iRZw6XFzV1FquXiQ/+2TEMKflKsSbViiLfFx4OTbK
puYuajpr0OUlBDmIoqrVErVUMX8I2ejWXCIvL0oejVfm0USznk0y4Fx4YWaxsUx3
Fj+0wvJkKE9mPcVCmYaX1qUpuI+wUODlgvzwjeI4XHg5NtSu8CBnOGeJNthcbsmT
NN0ToWSnHbatx1DEp3Hv/GyZ0KMyzXfaJWen4Z6aqzu7cmmRZvseknQ8c0JyT2FZ
ixKVNTUGUdRPAWOp9ce9Fgz9pEIlqc/dPhrLJf49UGqJ4g9oL1x4OTak2a79Jfl0
JXs5eiHk7AuM5d+0Mrrm+O/G/8zXVKI19hlcXAYXICqUtPgXX9sb7V15OJdzfJ72
R3uYlah2ezheG97DyTKXxQk4D1wiW+YUs64pJiRceGFm9fohFA+THM19hTd5ycDr
1nrId3mBaHtnArx/9J7izop6n99h+N0Iw4M3/JELeAlwATsIlUf4vdbUHhA8bLHP
L7R4P8FtXHhhZloNI6wJUMjeGGS0fIFgMX5EpTp5Pp9fTYGGVZ0SlW4l4/eCWn42
n8/R1qqb6oJLNLmcgpXwbtdkjU1XXHg5Ntn0RlxcvULQW17AYnsj4xWafuvG+lEc
6mf9dnD3IVQHvgjgDQxceDAwLyi8audAq3e+MR3g+O7gXHgwMJ4fxgPMR1TZ8zLc
yiDIw17YJFx4OTZPEPuBXFwMG4FiZ2GEJUJceDAw+dHiEB1cXIx1x4zAdoTlI98U
uciNR1QQ4ndQ5HdeFFZt9B9+DwFHIikuIl9fRU5EX19cbiIuJHg7
Vamos analisar todos os idiomas com a sequência de entrada de teste [Thank you/Wow/Great], this is [awesome/wonderful].
PHP
$ cat ti2 | php a.php
Great, this is wonderful.
d=DATA.read.chomp.split('[').map{|a|a.split(']')}.flatten.map{|a|a.split('/')}
d.each{|a|print a.sample}
puts <<"DATA"
from random import choice
import sys
#{d.map{|a|"sys.stdout.write(choice(#{a.inspect}))"}*"\n"}
print
print '''math.randomseed(os.time())
#{d.map{|a|"a=#{a.inspect.tr('[]','{}')};io.write(a[math.random(1,#{a.length})]);"}*"\n"}
print()
print([==[
public class a {
public static void Main() {
System.Random r=new System.Random();
#{d.map{|a|b=->m{m.length==1?"System.Console.Write(#{m.first.inspect});":"if (r.NextDouble()<0.5){System.Console.Write(#{m.shift.inspect});}else{"+b[m]+"};"};b[a.dup]}*"\n"}
System.Console.WriteLine();
System.Console.WriteLine(@"class a {
public static void main(String[] args) {
java.util.Random r=new java.util.Random();
#{d.map{|a|b=->m{m.length==1?"System.out.print(\"#{m.first.inspect}\");":"if (r.nextFloat()<0.5){System.out.print(\"#{m.shift.inspect}\");}else{"+b[m]+"};"};b[a.dup]}*"\n"}
System.out.println();
#{x="a";d.map{|a|b=->m{m.length==1?m.first: "\\\\\\\\ifnum500>\\\\\\\\pdfuniformdeviate1000 #{m.shift}\\\\\\\\else "+b[m]+"\\\\\\\\fi"};x=x.succ;a.length>1?"System.out.println(\"\"\\\\\\\\def \\\\\\\\opt#{x} {#{b[a.dup]}}%\"\");": ""}*"\n"}
System.out.println(""#{x="a";d.map{|a|x=x.succ;a.length>1?"\\\\\\\\opt#{x}{}": a.first}*""}"");
System.out.println();
System.out.println(""#{d.map{|a|a.length>1? "[#{a.map{|b|"'#{b}'"}*""}]#{a.length}rand=" : "'#{a.first}'"}*""}"");
System.out.println(""\\\\\\\\bye"");
}
}");
}
}
]==]);
'''
DATA
__END__
[Thank you/Wow/Great], this is [awesome/wonderful].
Rubi
$ ruby a.rb
Great, this is awesome.
from random import choice
import sys
sys.stdout.write(choice(["Thank you", "Wow", "Great"]))
sys.stdout.write(choice([", this is "]))
sys.stdout.write(choice(["awesome", "wonderful"]))
sys.stdout.write(choice(["."]))
print
print '''math.randomseed(os.time())
a={"Thank you", "Wow", "Great"};io.write(a[math.random(1,3)]);
a={", this is "};io.write(a[math.random(1,1)]);
a={"awesome", "wonderful"};io.write(a[math.random(1,2)]);
a={"."};io.write(a[math.random(1,1)]);
print()
print([==[
public class a {
public static void Main() {
System.Random r=new System.Random();
if (r.NextDouble()<0.5){System.Console.Write("Thank you");}else{if (r.NextDouble()<0.5){System.Console.Write("Wow");}else{System.Console.Write("Great");};};
System.Console.Write(", this is ");
if (r.NextDouble()<0.5){System.Console.Write("awesome");}else{System.Console.Write("wonderful");};
System.Console.Write(".");
System.Console.WriteLine();
System.Console.WriteLine(@"class a {
public static void main(String[] args) {
java.util.Random r=new java.util.Random();
if (r.nextFloat()<0.5){System.out.print(""Thank you"");}else{if (r.nextFloat()<0.5){System.out.print(""Wow"");}else{System.out.print(""Great"");};};
System.out.print("", this is "");
if (r.nextFloat()<0.5){System.out.print(""awesome"");}else{System.out.print(""wonderful"");};
System.out.print(""."");
System.out.println();
System.out.println(""\\\\def \\\\optb {\\\\ifnum500>\\\\pdfuniformdeviate1000 Thank you\\\\else \\\\ifnum500>\\\\pdfuniformdeviate1000 Wow\\\\else Great\\\\fi\\\\fi}%"");
System.out.println(""\\\\def \\\\optd {\\\\ifnum500>\\\\pdfuniformdeviate1000 awesome\\\\else wonderful\\\\fi}%"");
System.out.println(""\\\\optb{}, this is \\\\optd{}."");
System.out.println();
System.out.println(""['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'"");
System.out.println(""\\\\bye"");
}
}");
}
}
]==]);
'''
Pitão
$ python a.py
Great, this is wonderful.
math.randomseed(os.time())
a={"Thank you", "Wow", "Great"};io.write(a[math.random(1,3)]);
a={", this is "};io.write(a[math.random(1,1)]);
a={"awesome", "wonderful"};io.write(a[math.random(1,2)]);
a={"."};io.write(a[math.random(1,1)]);
print()
print([==[
public class a {
public static void Main() {
System.Random r=new System.Random();
if (r.NextDouble()<0.5){System.Console.Write("Thank you");}else{if (r.NextDouble()<0.5){System.Console.Write("Wow");}else{System.Console.Write("Great");};};
System.Console.Write(", this is ");
if (r.NextDouble()<0.5){System.Console.Write("awesome");}else{System.Console.Write("wonderful");};
System.Console.Write(".");
System.Console.WriteLine();
System.Console.WriteLine(@"class a {
public static void main(String[] args) {
java.util.Random r=new java.util.Random();
if (r.nextFloat()<0.5){System.out.print(""Thank you"");}else{if (r.nextFloat()<0.5){System.out.print(""Wow"");}else{System.out.print(""Great"");};};
System.out.print("", this is "");
if (r.nextFloat()<0.5){System.out.print(""awesome"");}else{System.out.print(""wonderful"");};
System.out.print(""."");
System.out.println();
System.out.println(""\\def \\optb {\\ifnum500>\\pdfuniformdeviate1000 Thank you\\else \\ifnum500>\\pdfuniformdeviate1000 Wow\\else Great\\fi\\fi}%"");
System.out.println(""\\def \\optd {\\ifnum500>\\pdfuniformdeviate1000 awesome\\else wonderful\\fi}%"");
System.out.println(""\\optb{}, this is \\optd{}."");
System.out.println();
System.out.println(""['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'"");
System.out.println(""\\bye"");
}
}");
}
}
]==]);
Lua
$ lua a.lua
Great, this is wonderful.
public class a {
public static void Main() {
System.Random r=new System.Random();
if (r.NextDouble()<0.5){System.Console.Write("Thank you");}else{if (r.NextDouble()<0.5){System.Console.Write("Wow");}else{System.Console.Write("Great");};};
System.Console.Write(", this is ");
if (r.NextDouble()<0.5){System.Console.Write("awesome");}else{System.Console.Write("wonderful");};
System.Console.Write(".");
System.Console.WriteLine();
System.Console.WriteLine(@"class a {
public static void main(String[] args) {
java.util.Random r=new java.util.Random();
if (r.nextFloat()<0.5){System.out.print(""Thank you"");}else{if (r.nextFloat()<0.5){System.out.print(""Wow"");}else{System.out.print(""Great"");};};
System.out.print("", this is "");
if (r.nextFloat()<0.5){System.out.print(""awesome"");}else{System.out.print(""wonderful"");};
System.out.print(""."");
System.out.println();
System.out.println(""\\def \\optb {\\ifnum500>\\pdfuniformdeviate1000 Thank you\\else \\ifnum500>\\pdfuniformdeviate1000 Wow\\else Great\\fi\\fi}%"");
System.out.println(""\\def \\optd {\\ifnum500>\\pdfuniformdeviate1000 awesome\\else wonderful\\fi}%"");
System.out.println(""\\optb{}, this is \\optd{}."");
System.out.println();
System.out.println(""['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'"");
System.out.println(""\\bye"");
}
}");
}
}
C #
$ mcs a.cs
$ mono a.exe
Thank you, this is wonderful.
class a {
public static void main(String[] args) {
java.util.Random r=new java.util.Random();
if (r.nextFloat()<0.5){System.out.print("Thank you");}else{if (r.nextFloat()<0.5){System.out.print("Wow");}else{System.out.print("Great");};};
System.out.print(", this is ");
if (r.nextFloat()<0.5){System.out.print("awesome");}else{System.out.print("wonderful");};
System.out.print(".");
System.out.println();
System.out.println("\\def \\optb {\\ifnum500>\\pdfuniformdeviate1000 Thank you\\else \\ifnum500>\\pdfuniformdeviate1000 Wow\\else Great\\fi\\fi}%");
System.out.println("\\def \\optd {\\ifnum500>\\pdfuniformdeviate1000 awesome\\else wonderful\\fi}%");
System.out.println("\\optb{}, this is \\optd{}.");
System.out.println();
System.out.println("['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'");
System.out.println("\\bye");
}
}
Java
$ javac a.java
$ java a
Wow, this is wonderful.
\def \optb {\ifnum500>\pdfuniformdeviate1000 Thank you\else \ifnum500>\pdfuniformdeviate1000 Wow\else Great\fi\fi}%
\def \optd {\ifnum500>\pdfuniformdeviate1000 awesome\else wonderful\fi}%
\optb{}, this is \optd{}.
['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'
\bye
PdfTeX
(o código estará dentro de a.pdf em vez de stdout. Espero que isso ainda esteja correto)
$ pdftex a.tex
This is pdfTeX, Version 3.1415926-2.4-1.40.13 (TeX Live 2012)
restricted \write18 enabled.
entering extended mode
(./a.tex [1{/usr/local/texlive/2012/texmf-var/fonts/map/pdftex/updmap/pdftex.ma
p}] )</usr/local/texlive/2012/texmf-dist/fonts/type1/public/amsfonts/cm/cmr10.p
fb>
Output written on a.pdf (1 page, 15967 bytes).
Transcript written on a.log.
$ open a.pdf
Resultado:
Em texto:
Great, this is wonderful.
['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'
Golfscript
$ ruby golfscript.rb a.gs
Wow, this is awesome.
Notas
Parece que o PHP perdoa bastante os dados binários em literais de string, exceto os códigos hexadecimais AF e 96. Não pergunte o porquê.
Eu provavelmente poderia ter adicionado códigos perl e C ++ 11 com muita facilidade (já que ambos suportam literais de strings brutos), mas 8 é um número mais redondo que 10 :)
A distribuição de valores não é uniforme, pois o primeiro elemento vem mais frequentemente do que os posteriores. De acordo com os comentários, isso deve estar bem.
O código inicial foi realmente gerado usando o seguinte código PHP 5.5. orig.rb
é realmente o mesmo que o código Ruby sem o rodapé ( __END__
e os dados anexados posteriormente)
generator.php
:
<?php
$d=file_get_contents('orig.rb');
$dc = gzcompress($d,9);
echo '<?php $x=file_get_contents("php://stdin");echo preg_replace_callback("/\\[(.*?)\\]/",function($m){$r=explode("/",$m[1]);return $r[array_rand($r)];},$x)';
?><?php
echo ".gzuncompress(\"";
for ($i=0;$i<strlen($dc);$i++) {
switch($dc[$i]) {
case '"':
echo "\\\"";break;
case "\n":
echo "\\n";break;
case '\\':
echo "\\\\";break;
case "\x00":case "\xaf":case "\x96":
echo sprintf("\\x%02x",ord($dc[$i]));
break;
default:
echo $dc[$i];
}
}
echo "\").\"__END__\\n\".\$x;";
(você pode potencialmente usar esse código para zLib incluir soluções PHP para outros desafios)