『ラングトンのアリの描画』投稿

どう書く?org』への投稿
 今回は『ラングトンのアリ』と呼ばれるセル・オートマトンの問題。
お題:
http://ja.doukaku.org/276/

ラングトンのアリを描画してください。

 以下投稿したコード。言語はいつものPHP。
 方角の循環、セルの反転、アリの移動はそれぞれ工夫したつもり。
 シンプルにまとまっていると思う。

<?php
function lang_ant($w, $h)
{
$world = array_fill(0, $h, array_fill(0, $w, 1));
$x = (int)($w/2);
$y = (int)($h/2);
$dct = 0; /* 0:N 1:E 2:S 3:W */
$stp_ant = array(‘$x++;’, ‘$y++;’, ‘$x–;’, ‘$y–;’);
$chg_dct = array(‘$dct = (((++$dct)%4)+2)%4;’, ‘$dct = (++$dct)%4;’);
$print_world = array(’0′, ‘&nbsp;’);

for ( $i = 0; $i < 20000; $i++) {
eval($chg_dct[$world[$y][$x]]);
eval($stp_ant[$dct]);
if ($x<0 || $w<=$x || $y<0 || $h<=$y) {
break;
}
$world[$y][$x] = (++$world[$y][$x])%2;
}
foreach ( $world as $cels) {
foreach ($cels as $cel) {
echo $print_world[$cel];
}
echo “<br />”;
}
}
?>

投稿:
http://ja.doukaku.org/comment/9373/
ラングトンのアリ – Wikipedia
http://ja.wikipedia.org/wiki/%E3%83%A9%E3%83%B3%E3%82%B0%E3%83%88%E3%83%B3%E3%81%AE%E3%82%A2%E3%83%AA
JavaScriptでラングトンの蟻
http://www.songmu.jp/riji/archives/2009/07/javascript_1.html
PHP rank:15 (63.2%)
朝日出版社 (2009/05/08)
Related Posts

Comments are closed.