「prolog勉強22日目 カラーダイスパズル」の編集履歴(バックアップ)一覧に戻る

prolog勉強22日目 カラーダイスパズル - (2013/06/22 (土) 06:36:48) の編集履歴(バックアップ)


http://www.geocities.jp/m_hiroi/puzzle/colordice.html
こちらのサイトにあるパズルをプロローグで解いてみました。
カラーダイスパズルです。

単純に回転した場合の写像をとって全パタンを試しただけ、この手の回転は群論の初歩的な感じかも。
深さ優先探索がサクッと書けるのはプロローグの強みだと思う。
こんなパズルでも、データ構造や写像をどう定義するかでそれなりに遊びどころはある。
プロローグはデータをどう定義するかでコードの総量が極端に変わるので良い勉強になる。
適当に書いても重複解を排除できるかと思ったら意外と排除できなかったのでいま重複解を排除するコードを検討中。


flat_round([U,D,F,L,B,R],[U,D,R,F,L,B]).
down_round([U,D,F,L,B,R],[B,F,U,L,D,R]). 

flat_rounds(A,A).
flat_rounds(A,Re):-flat_round(A,Re).
flat_rounds(A,Re1):-flat_round(A,Re),flat_round(Re,Re1).
flat_rounds(A,Re2):-flat_round(A,Re),flat_round(Re,Re1),flat_round(Re1,Re2).

all_down(A,A).
all_down(A,Re2):-flat_rounds(A,Re1),down_round(Re1,Re2).
all_down(A,Re2):-down_round(A,Re1),down_round(Re1,Re2).

one_print([U,D,F,L,B,R]):-
	format('_~a~n',U),
	format('~a~a~a~a~n',[R,F,L,B]),
	format('_~a~n',D).

print_xai([]):-!.
print_xai([Xai|Rest]):-one_print(Xai),print_xai(Rest).


search([],Fs,Ls,Bs,Rs,Log):-
	write([Fs,Ls,Bs,Rs]),nl,
	!,print_xai(Log),write(ok).
search(Perm,Fs,Ls,Bs,Rs,Log):-
	select(T,Perm,Rest),
	xais(T,Xai),
	all_down(Xai,Xai1),
	flat_rounds(Xai1,Xai2),
	[_,_,F,L,B,R]=Xai2,
	not(member(F,Fs)),
	not(member(L,Ls)),
	not(member(R,Rs)),
	not(member(B,Bs)),
	search(Rest,[F|Fs],[L|Ls],[B|Bs],[R|Rs],[Xai2|Log]).

first(Perm):-
	select(T,Perm,Rest),
	xais(T,Xai),
	all_down(Xai,Xai1),
	[_,_,F,L,B,R]=Xai1,
	search(Rest,[F|[]],[L|[]],[B|[]],[R|[]],[Xai1|[]]).

main:-
	assert(xais(0,[])),
	assert(ansers([],[],[],[])),
	retractall(xais(_,_)),
 	retractall(ansers([],[],[],[])),
	assert(xais(0,[b,b,g,g,y,r])),
	assert(xais(1,[b,r,b,g,y,r])),
	assert(xais(2,[r,b,g,y,y,r])),
	assert(xais(3,[g,r,g,y,g,b])),
	first([0,1,2,3]).