METHINKS IT IS A WEASEL
Posted feedbacks - PHP
PHP練習中。 言語の練習にはいい問題だった。 配列周りのバグが出まくり。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | <?php
print <<< END_DOC
<HTML>
<HEAD><title>doukaku177</title>
</HEAD><BODY>
END_DOC;
$answer = str_split("METHINKS IT IS A WEASEL");
$alphabet_table = str_split(" ABCDEFGHIJKLMNOPQRSTUVWXYZ");
function getLength($targetString)
{
$length = 0;
global $answer;
for($i = 0; $i < count($answer); $i++){
$length += abs(ord($answer[$i]) - ord($targetString[$i]));
}
return $length;
}
function cmp($a, $b)
{
return $a["length"] - $b["length"];
}
function doukaku177()
{
global $answer;
global $alphabet_table;
#init
$string_pool = array();
$string_pool_max = 900;
for($i = 0; $i < $string_pool_max; $i++){
$s = array();
for($j = 0; $j < count($answer); $j++){
array_push($s, $alphabet_table[mt_rand(0, count($alphabet_table)-1)]);
}
$length = getLength($s);
$s["length"] = $length;
array_push($string_pool, $s);
}
#evolve
$i=0;
do{
usort($string_pool, "cmp");
#show top
print "Generation = $i ";
print "Str = ".join("",$string_pool[0])."<BR>";
$string_pool = array_slice($string_pool, 0, $string_pool_max / 3);
foreach($string_pool as $item){
unset($item["length"]);
$item[mt_rand(0, count($item)-1)] = $alphabet_table[mt_rand(0, count($alphabet_table)-1)];
$length = getLength($item);
$item["length"] = $length;
array_push($string_pool, $item);
}
$i++;
}while($string_pool[0]["length"]);
}
doukaku177();
print <<< END_DOC
</BODY>
</HTML>
END_DOC;
?>
|


ytakenaka
#6287()
Rating4/8=0.50
ランダムな文字からMETHINKS IT IS A WEASELを作るプログラムを作れ。
簡単に流れを書いてみます。
1:ランダムな20文字を持つ文字列をもった300個作ります。
2:その文字列が"METHINKSITISAWEASEL"に近いものからソートします。
3:それぞれの文字列のなか1文字を別の文字に変化させたものを3つ用意します。
4:それを2:のソートをして上位300個残す。(900個あるうちで上位300個残すということです。)
5:以後3:と4:を繰り返す。
ランダムな文字変化は大文字だけでいいです。簡単にするために空白文字を外してあります。
METHINKS IT IS WEASELができたら終了。3と4の間でソートしたもので一番上位のものを毎回表示させると変化が楽しめます。:-)
Rickard Dawkinsがブラインドウォッチメイカー(現題:盲目の時計職人)の3章で書いていた有名なものです。さらに一般化してもらってもいいです。
参考
[ reply ]