METHINKS IT IS A WEASEL
Posted feedbacks - Erlang
プロセスと乱数の相性が悪い様なのでちょっとべたですが。
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 | -module(methinks_it_is_a_weasel).
-import(io).
-import(lists).
-import(random).
-export([start/0]).
get_char(CS) -> lists:nth(random:uniform(length(CS)),CS).
create(T,_,TS) when TS == 0 -> T;
create(T,CS,TS) -> create([get_char(CS)|T],CS,TS-1).
create(CS,TS) -> create("",CS,TS).
create_text_list(TL,_,_,S) when S == 0 -> TL;
create_text_list(TL,CS,TS,S) -> create_text_list([create(CS,TS)|TL],CS,TS,S-1).
create_text_list(CS,TS,S) -> create_text_list([],CS,TS,S).
rank(T,G) ->
lists:foldl(
fun({CT,CG},A) ->
A +
if
CT == CG -> 1;
true -> 0
end
end,
0,
lists:zip(T,G)
).
sort_text_list(TL,G) -> lists:sort(fun(A,B) -> rank(A,G) > rank(B,G) end,TL).
update_text(T,CS) ->
P = random:uniform(length(T)),
lists:append(lists:sublist(T,P-1),[get_char(CS)|lists:sublist(T,P+1,length(T)-P)]).
update_text_list(TL,G,CS,S,N) ->
lists:sublist(
sort_text_list(
lists:foldl(
fun(T,A) ->
lists:append(
A,
lists:map(
fun(_) ->
update_text(T,CS)
end,
lists:seq(1,N,1)
)
)
end,
[],
TL
),
G
),
S
).
process([T|TL],G,CS,S,N,I) ->
R = rank(T,G),
L = length(G),
if
R == L ->
io:format("goal(~w):~p~n",[I,T]);
true ->
io:format("process(~w):~p(~w)~n",[I,T,rank(T,G)]),
process(update_text_list([T|TL],G,CS,S,N),G, CS, S, N, I+1)
end.
start() ->
G = "METHINKSITISAWEASEL",
CS = lists:seq($A,$Z,1),
S = 300,
N = 5,
process(sort_text_list(create_text_list(CS,length(G),S),G),G,CS,S,N,1).
|

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 ]